Compare commits

...
45 Commits
Author SHA1 Message Date
whoswhip 012690f507 chore: bump version and generate change log 2026-02-14 18:36:17 -05:00
whoswhip 5017e73bb5 fix(backend): use GenerateSecureRandomString for api-keys, paste ids, and refresh tokens 2026-02-14 18:31:40 -05:00
whoswhip 809b513e7a feat(backend:utilities): implement GenerateSecureRandomString function that uses RandomNumberGenerator 2026-02-14 18:30:58 -05:00
whoswhip 3374eadb56 feat(backend:authentication): implement API key authentication scheme and update authorization policies 2026-02-14 05:05:33 -05:00
whoswhip 7d09870ad2 fix(frontend:user): resolve lint errors 2026-02-13 22:08:00 -05:00
whoswhip fd1cb3998c style: format via prettier 2026-02-13 21:59:33 -05:00
whoswhip 3dc8070efe feat(frontend:api-keys): display the count of API keys in the header and adjust empty state condition 2026-02-13 21:58:31 -05:00
whoswhip 78f4ae181e fix(frontend:api-keys): add flag to track successful API key fetch
this prevents the api from being spammed when the api keys have been successfully fetched but there are no keys
2026-02-13 21:12:13 -05:00
whoswhip ee45deb439 feat(frontend:api-keys): implement API key management features including creation, deletion, and fetching
this also fixed a few layout issues and lint issues
2026-02-13 21:05:48 -05:00
whoswhip 3b2801a655 feat(frontend:modal): decrease modal background opacity and blur 2026-02-13 20:37:49 -05:00
whoswhip cac34423d9 feat(frontend:stats): enhance tooltip for total storage used to show uncompressed size 2026-02-13 18:49:31 -05:00
whoswhip 5052bbdb13 feat(frontend:user): improve UX; move user settings to settings tab 2026-02-13 18:11:55 -05:00
whoswhip 0283d987d0 docs: api-key hmac secret; show default in :**value**: format instead of the description 2026-02-13 02:45:24 -05:00
whoswhip ff706d8777 feat(frontend): improve user page UX 2026-02-13 02:35:05 -05:00
whoswhip 53d0f33ff0 feat(backend): implement api keys; rename token -> verificationToken in paste creation api
api keys can bypass authentication and captchas/verification
2026-02-13 01:47:50 -05:00
whoswhip db363f0211 feat: add dotnet-ef tool configuration to dotnet-tools.json 2026-02-13 01:45:28 -05:00
whoswhip 4feae4cadf chore: bump version and generate change log 2026-02-10 17:22:25 -05:00
whoswhip 0d9a713247 style: format via csharpier 2026-02-10 17:15:29 -05:00
whoswhip d2b9acb70f style: format via prettier 2026-02-10 17:07:22 -05:00
whoswhip 1cd6d16d85 feat: implement web worker for syntax highlighting using highlight.js 2026-02-09 17:05:18 -05:00
whoswhip 1a13694621 refactor: include all natively supported highlight.js langs and remove any unsupported langs
this one was done manually instead of laste time, majority of the extensions are either from auto-complete or just ones i know
2026-02-09 17:04:49 -05:00
whoswhip 3904ac327f docs: correct dev docs 2026-02-07 21:10:41 -05:00
whoswhip d64e1b4e82 docs: improve configuration setup 2026-02-07 15:57:36 -05:00
whoswhip 697ec384f8 fix: correct spelling of 'Verification' in PasteSettings and PasteController 2026-02-06 22:11:37 -05:00
whoswhip 4917180624 fix: prevent internal server endpoint leakage in openapi 2026-02-06 19:35:39 -05:00
whoswhip e90184992a fix: do not generate open api documents on build 2026-02-06 18:36:43 -05:00
whoswhip 698db0a85e feat: proxy openapi url 2026-02-06 18:29:20 -05:00
whoswhip 6b32994d16 feat: true total paste size; always map the openapi route
style: format via csharpier
2026-02-06 18:28:32 -05:00
whoswhip d04e2962b5 feat: cache for 6 hours instead of 24 hours 2026-02-05 19:59:55 -05:00
whoswhip b56a848d21 fix: resolve lint issues 2026-02-05 16:34:03 -05:00
whoswhip 91ad515205 style: format via prettier 2026-02-05 16:05:06 -05:00
whoswhip f37e647a1c fix: simplify height adjustment logic for text area and markdown container 2026-02-05 16:04:16 -05:00
whoswhip 54ca2ee641 fix: update stats tooltip to display correct pluralization for paste counts 2026-02-04 06:50:28 -05:00
whoswhip 22317a2fae feat: add statistics page 2026-02-03 20:16:19 -05:00
whoswhip c9591a43c7 feat: update tooltip function to accept parameters for styling 2026-02-03 20:16:03 -05:00
whoswhip cbbed2d341 feat: add statistics link to footer component 2026-02-03 20:15:39 -05:00
whoswhip 23e7973e97 feat: enhance API stats endpoint to include daily paste counts for the past week 2026-02-03 20:15:32 -05:00
whoswhip e141e1c642 style: format via prettier 2026-02-03 17:32:53 -05:00
whoswhip f95b347191 fix: ensure length > 0 and that arrays have value before validating 2026-02-01 20:12:59 -05:00
whoswhip 908441de4b fix: initialize multiselect state in modal component 2026-02-01 16:52:30 -05:00
whoswhip 755b356d61 fix: update display name validation to allow spaces and improve error message 2026-02-01 16:06:14 -05:00
whoswhip 71363fa1a4 feat(backend): allow spaces in display name during registration 2026-01-31 18:27:18 -05:00
whoswhip abcf79c645 feat: allow spaces in display names 2026-01-31 18:26:09 -05:00
whoswhip 4057f2303c refactor: update report types and statuses to remove useless values 2026-01-31 16:07:09 -05:00
whoswhip fb41995d53 chore: generate changelog for 3.0.2 2026-01-31 11:53:12 -05:00
69 changed files with 3183 additions and 1360 deletions
+81
View File
@@ -1,3 +1,84 @@
## [3.0.4](https://github.com/whoswhip/Sharpbin/compare/v3.0.3...v3.0.4) (2026-02-14)
### Bug Fixes
* **backend:** use GenerateSecureRandomString for api-keys, paste ids, and refresh tokens ([5017e73](https://github.com/whoswhip/Sharpbin/commit/5017e73bb54e626d4dc060fd553c972663eec45f))
* **frontend:api-keys:** add flag to track successful API key fetch ([78f4ae1](https://github.com/whoswhip/Sharpbin/commit/78f4ae181eb18a98ed9964d8e651d84319fa8d2c))
* **frontend:user:** resolve lint errors ([7d09870](https://github.com/whoswhip/Sharpbin/commit/7d09870ad25472ff17a1acc22d5724e199f2c931))
### Features
* add dotnet-ef tool configuration to dotnet-tools.json ([db363f0](https://github.com/whoswhip/Sharpbin/commit/db363f0211972a06b622770ca522d3ef0bba12c8))
* **backend:authentication:** implement API key authentication scheme and update authorization policies ([3374ead](https://github.com/whoswhip/Sharpbin/commit/3374eadb5654fa349a636c4a41a53df1ddf2edfe))
* **backend:utilities:** implement GenerateSecureRandomString function that uses RandomNumberGenerator ([809b513](https://github.com/whoswhip/Sharpbin/commit/809b513e7a3f5a4f7faf64b02d9ed83e81c540b8))
* **backend:** implement api keys; rename token -> verificationToken in paste creation api ([53d0f33](https://github.com/whoswhip/Sharpbin/commit/53d0f33ff026d6e5a188d80585e6a3bb633d9fa8))
* **frontend:api-keys:** display the count of API keys in the header and adjust empty state condition ([3dc8070](https://github.com/whoswhip/Sharpbin/commit/3dc8070efeb19538c4ff120d2a681c4167c716f3))
* **frontend:api-keys:** implement API key management features including creation, deletion, and fetching ([ee45deb](https://github.com/whoswhip/Sharpbin/commit/ee45deb43937cbf3996c3c379461110a484bd086))
* **frontend:modal:** decrease modal background opacity and blur ([3b2801a](https://github.com/whoswhip/Sharpbin/commit/3b2801a65509d3a894c701f03028b2cd4599b456))
* **frontend:stats:** enhance tooltip for total storage used to show uncompressed size ([cac3442](https://github.com/whoswhip/Sharpbin/commit/cac34423d99d1228f426be903da53bafca5f50e7))
* **frontend:user:** improve UX; move user settings to settings tab ([5052bbd](https://github.com/whoswhip/Sharpbin/commit/5052bbdb135dc2df08db94874de5bf2bf738364c))
* **frontend:** improve user page UX ([ff706d8](https://github.com/whoswhip/Sharpbin/commit/ff706d877742317cb8f4ccf72ba5f0791a6d2b88))
## [3.0.3](https://github.com/whoswhip/Sharpbin/compare/v3.0.2...v3.0.3) (2026-02-10)
### Bug Fixes
* correct spelling of 'Verification' in PasteSettings and PasteController ([697ec38](https://github.com/whoswhip/Sharpbin/commit/697ec384f8a0d3d86eb7e523595ddda3cda256b4))
* do not generate open api documents on build ([e901849](https://github.com/whoswhip/Sharpbin/commit/e90184992a1dd585bfb3728dc866193ab870fb86))
* ensure length > 0 and that arrays have value before validating ([f95b347](https://github.com/whoswhip/Sharpbin/commit/f95b347191854e8057c8086e52165a83e2fa8a7d))
* initialize multiselect state in modal component ([908441d](https://github.com/whoswhip/Sharpbin/commit/908441de4b7e857d8cbcc520da86cf1abaab0fa2))
* prevent internal server endpoint leakage in openapi ([4917180](https://github.com/whoswhip/Sharpbin/commit/4917180624d1ec2f7af784c50c5cd2810beba1b3))
* resolve lint issues ([b56a848](https://github.com/whoswhip/Sharpbin/commit/b56a848d21da5d8bb57c22bdc03bd84449813338))
* simplify height adjustment logic for text area and markdown container ([f37e647](https://github.com/whoswhip/Sharpbin/commit/f37e647a1c0264a3b6229c270e75b8176ec93628))
* update display name validation to allow spaces and improve error message ([755b356](https://github.com/whoswhip/Sharpbin/commit/755b356d616a339273c7e45207304e901617c367))
* update stats tooltip to display correct pluralization for paste counts ([54ca2ee](https://github.com/whoswhip/Sharpbin/commit/54ca2ee6417e0a6cfcc14ccb0be6e79d9dc4cacd))
### Features
* add statistics link to footer component ([cbbed2d](https://github.com/whoswhip/Sharpbin/commit/cbbed2d341670ba7b034af161ccdb3ddb3101dc0))
* add statistics page ([22317a2](https://github.com/whoswhip/Sharpbin/commit/22317a2fae8f8a8ed45f313a46bb2489b8042f92))
* allow spaces in display names ([abcf79c](https://github.com/whoswhip/Sharpbin/commit/abcf79c6458b97d1f75b6c31020fdc7ab957d4f2))
* **backend:** allow spaces in display name during registration ([71363fa](https://github.com/whoswhip/Sharpbin/commit/71363fa1a467c660297301d4f35513bdfe39ccd5))
* cache for 6 hours instead of 24 hours ([d04e296](https://github.com/whoswhip/Sharpbin/commit/d04e2962b51796393f77b66fd37f6efad924b413))
* enhance API stats endpoint to include daily paste counts for the past week ([23e7973](https://github.com/whoswhip/Sharpbin/commit/23e7973e972f197954568fb292f1c8f6e5272c50))
* implement web worker for syntax highlighting using highlight.js ([1cd6d16](https://github.com/whoswhip/Sharpbin/commit/1cd6d16d8538bf3b990f523703eb9abc19da5f36))
* proxy openapi url ([698db0a](https://github.com/whoswhip/Sharpbin/commit/698db0a85e000e8b1ab76d82827b8f404ffd0f67))
* true total paste size; always map the openapi route ([6b32994](https://github.com/whoswhip/Sharpbin/commit/6b32994d16b201a5a99037fcb23af30bd35876bc))
* update tooltip function to accept parameters for styling ([c9591a4](https://github.com/whoswhip/Sharpbin/commit/c9591a43c78b7c8a09b3e7afa0e8b401b70efae0))
## [3.0.2](https://github.com/whoswhip/Sharpbin/compare/v3.0.1...v3.0.2) (2026-01-31)
### Bug Fixes
* add IValidateableObject interface to required DTO's ensuring model validation ([270360a](https://github.com/whoswhip/Sharpbin/commit/270360a32f9b9217a1be1057058a61c57f578e95))
* adjust input margin for title field in paste creation ([d2486b9](https://github.com/whoswhip/Sharpbin/commit/d2486b9f6e1b87e2d4e13fcc2550292ad77170c3))
* enable AllowMissingPrunePackageData in project configuration ([c52ad8b](https://github.com/whoswhip/Sharpbin/commit/c52ad8ba9b12e62324fc6bac445a3e1c5b275e95))
* improve error handling and update user display name modal ([a6ffa98](https://github.com/whoswhip/Sharpbin/commit/a6ffa982a4225ef4512b925af39ed4836be40fbb))
* update version to 3.0.1 in package-lock.json ([15f0be5](https://github.com/whoswhip/Sharpbin/commit/15f0be5a2f902429906c1acdfe7923b25c16be12))
### Features
* add conventional-changelog and conventional-changelog-angular dependencies ([e4cf98a](https://github.com/whoswhip/Sharpbin/commit/e4cf98af096b4909e97898eaa452447a09307d31))
* add inputMaxLength property to Modal component for better input control ([005cb5d](https://github.com/whoswhip/Sharpbin/commit/005cb5de23e244a4b07ea1173b7805f7cd2b2561))
* add output caching and stats endpoint to track pastes and users ([ca210c5](https://github.com/whoswhip/Sharpbin/commit/ca210c5ea3e97d7a4e93f51794d1da7a6da40ebf))
* createdAt paste property ([9d0cc54](https://github.com/whoswhip/Sharpbin/commit/9d0cc54db46a24d16f752b5db66baf1565891d26))
* enhance PasteService with caching and cache invalidation methods ([5375e1c](https://github.com/whoswhip/Sharpbin/commit/5375e1caa64ce51bd0cd3613f8df68d6ea2d7aa4))
* include createdAt in user responses ([854e50f](https://github.com/whoswhip/Sharpbin/commit/854e50fe78265a58af6004c3db12ca551c4372f9))
* include paste createdAt in responses ([8aa1543](https://github.com/whoswhip/Sharpbin/commit/8aa1543296817745f66a724e349897d8496bb193))
* user createdAt property ([500f457](https://github.com/whoswhip/Sharpbin/commit/500f457f976bc4742e8e3395f01eef84a0c16558))
## [3.0.1](https://github.com/whoswhip/Sharpbin/compare/v3.0.0...v3.0.1) (2026-01-27)
+14 -6
View File
@@ -34,7 +34,15 @@ docker-compose up -d
### Configuration
You can configure the application using environment variables. When using Docker Compose, these can be set in the `docker-compose.yml` file.
You can configure Sharpbin using environment variables or `appsettings.json`. When using Docker Compose, these can be set in the `docker-compose.yml` file.
> When configuring via `appsettings.json` instead of for example `ConnectionStrings__DefaultConnection` it would be:
```json
"ConnectionStrings": {
"DefaultConnection": "Data Source=sharpbin.db"
},
```
#### Backend (SharpbinV3.Server)
@@ -42,16 +50,16 @@ You can configure the application using environment variables. When using Docker
- `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__Registration_Enabled`:**true**: 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.
- `AuthSettings__API_Key_HMAC_Secret`: Recommended to securely hash API keys, but is not required.
- `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__MaxPasteSizeInBytes`:**1_048_576** (1MB): Max Paste Size set in bytes.
- `PasteSettings__EnablePasteCompression`:**true**: Enables/Disables server-side paste compression.
- `PasteSettings__RequiresVerification`:**true**: Enables/Disables CAPTCHA verification when creating pastes.
- `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.
- `ASPNETCORE_ENVIRONMENT`: Set to `Production` or `Development`.
#### Frontend (SharpbinV3.Client)
+3 -11
View File
@@ -19,7 +19,7 @@ npm install
### Environment Configuration
The application requires an environment variable to point to the backend API. Create a `.env` file in this directory or set the variable in your environment:
The frontend requires an environment variable to point to the backend API. Create a `.env` file in this directory or set the variable in your environment:
- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`).
- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`)
@@ -33,21 +33,13 @@ Start the development server with Hot Module Replacement (HMR):
npm run dev
```
The application will be available at http://localhost:5173.
The frontend will be available at http://localhost:5173.
## Script Reference
- `npm run dev`: Start the Vite development server.
- `npm run build`: Create a production build of the application.
- `npm run build`: Create a production build of the frontend.
- `npm run preview`: Locally preview the production build.
- `npm run check`: Run type checking with svelte-check.
- `npm run lint`: Run ESLint and Prettier checks.
- `npm run format`: Format the codebase with Prettier.
## Tech Stack
- Svelte 5 with SvelteKit.
- Tailwind CSS for styling.
- Lucide Svelte for icons.
- Highlight.js for syntax highlighting.
- TypeScript for type safety.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "sharpbinv3.client",
"version": "3.0.2",
"version": "3.0.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sharpbinv3.client",
"version": "3.0.2",
"version": "3.0.4",
"dependencies": {
"@lucide/svelte": "^0.562.0",
"@sveltejs/adapter-node": "^5.4.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "sharpbinv3.client",
"private": true,
"version": "3.0.2",
"version": "3.0.4",
"type": "module",
"scripts": {
"dev": "vite dev",
@@ -1,3 +1,7 @@
<script lang="ts">
import { resolve } from '$app/paths';
</script>
<div
class="mb-5 max-h-10 w-full border-t border-neutral-800 pt-5 text-center text-sm text-neutral-500"
>
@@ -10,5 +14,9 @@
Source Code
</a>
<span class="mx-1">•</span>
<a href={resolve('/stats')} class="text-neutral-400 underline hover:text-neutral-200"
>Statistics</a
>
<span class="mx-1">•</span>
v{__APP_VERSION__}
</div>
@@ -43,6 +43,7 @@
let reportType = '';
let reportInitialized = false;
let reportLoading = false;
let multiselectInitialized = false;
let turnstileEl: HTMLDivElement | null = null;
let turnstileWidgetId: string | null = null;
@@ -85,6 +86,11 @@
initializeReport();
}
$: if (show && mode === 'multiselect' && !multiselectInitialized) {
multiselectInitialized = true;
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
}
function resetModal() {
inputValue =
initialValue !== null
@@ -102,6 +108,7 @@
reportType = '';
reportInitialized = false;
reportLoading = false;
multiselectInitialized = false;
if (turnstileWidgetId && typeof window !== 'undefined' && window.turnstile?.remove) {
window.turnstile.remove(turnstileWidgetId);
}
@@ -395,10 +402,10 @@
</script>
{#if show}
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-xs">
<form
on:submit|preventDefault={handleSubmit}
class="w-full max-w-md rounded bg-neutral-900 p-6"
class="w-full max-w-md rounded border border-neutral-800 bg-neutral-900 p-6"
>
<h2 class="mb-4 text-xl font-semibold text-white">
{displayTitle}
+184 -151
View File
@@ -4,157 +4,190 @@ export type Syntax = {
};
export const syntaxes: Record<string, Syntax> = {
plaintext: { name: 'Plain Text', extension: '' },
abap: { name: 'ABAP', extension: '.abap' },
'actionscript-3': { name: 'ActionScript 3', extension: '.as' },
ada: { name: 'Ada', extension: '.adb' },
apache: { name: 'Apache', extension: '.conf' },
apex: { name: 'Apex', extension: '.cls' },
apl: { name: 'APL', extension: '.apl' },
applescript: { name: 'AppleScript', extension: '.applescript' },
ara: { name: 'ARA', extension: '.ara' },
asm: { name: 'Assembly', extension: '.asm' },
astro: { name: 'Astro', extension: '.astro' },
awk: { name: 'AWK', extension: '.awk' },
ballerina: { name: 'Ballerina', extension: '.bal' },
bat: { name: 'Batch', extension: '.bat' },
berry: { name: 'Berry', extension: '.be' },
bibtex: { name: 'BibTeX', extension: '.bib' },
bicep: { name: 'Bicep', extension: '.bicep' },
blade: { name: 'Blade', extension: '.blade.php' },
c: { name: 'C', extension: '.c' },
cadence: { name: 'Cadence', extension: '.cdc' },
clarity: { name: 'Clarity', extension: '.clar' },
clojure: { name: 'Clojure', extension: '.clj' },
cmake: { name: 'CMake', extension: '.cmake' },
cobol: { name: 'COBOL', extension: '.cob' },
codeql: { name: 'CodeQL', extension: '.ql' },
coffee: { name: 'CoffeeScript', extension: '.coffee' },
cpp: { name: 'C++', extension: '.cpp' },
crystal: { name: 'Crystal', extension: '.cr' },
csharp: { name: 'C#', extension: '.cs' },
css: { name: 'CSS', extension: '.css' },
csv: { name: 'CSV', extension: '.csv' },
cue: { name: 'CUE', extension: '.cue' },
d: { name: 'D', extension: '.d' },
dart: { name: 'Dart', extension: '.dart' },
diff: { name: 'Diff', extension: '.diff' },
docker: { name: 'Docker', extension: 'Dockerfile' },
'dream-maker': { name: 'Dream Maker', extension: '.dm' },
elixir: { name: 'Elixir', extension: '.ex' },
elm: { name: 'Elm', extension: '.elm' },
erb: { name: 'ERB', extension: '.erb' },
erlang: { name: 'Erlang', extension: '.erl' },
fish: { name: 'Fish', extension: '.fish' },
fsharp: { name: 'F#', extension: '.fs' },
gdresource: { name: 'Godot Resource', extension: '.tres' },
gdscript: { name: 'GDScript', extension: '.gd' },
gdshader: { name: 'Godot Shader', extension: '.gdshader' },
gherkin: { name: 'Gherkin', extension: '.feature' },
'git-commit': { name: 'Git Commit', extension: '' },
'git-rebase': { name: 'Git Rebase', extension: '' },
glsl: { name: 'GLSL', extension: '.glsl' },
gnuplot: { name: 'Gnuplot', extension: '.gp' },
go: { name: 'Go', extension: '.go' },
graphql: { name: 'GraphQL', extension: '.graphql' },
groovy: { name: 'Groovy', extension: '.groovy' },
hack: { name: 'Hack', extension: '.hack' },
haml: { name: 'Haml', extension: '.haml' },
handlebars: { name: 'Handlebars', extension: '.hbs' },
haskell: { name: 'Haskell', extension: '.hs' },
hcl: { name: 'HCL', extension: '.hcl' },
hjson: { name: 'HJSON', extension: '.hjson' },
hlsl: { name: 'HLSL', extension: '.hlsl' },
html: { name: 'HTML', extension: '.html' },
ini: { name: 'INI', extension: '.ini' },
java: { name: 'Java', extension: '.java' },
javascript: { name: 'JavaScript', extension: '.js' },
jison: { name: 'Jison', extension: '.jison' },
json: { name: 'JSON', extension: '.json' },
json5: { name: 'JSON5', extension: '.json5' },
jsonc: { name: 'JSONC', extension: '.json' },
jsonnet: { name: 'Jsonnet', extension: '.jsonnet' },
jssm: { name: 'JSSM', extension: '.jssm' },
jsx: { name: 'JSX', extension: '.jsx' },
julia: { name: 'Julia', extension: '.jl' },
kotlin: { name: 'Kotlin', extension: '.kt' },
latex: { name: 'LaTeX', extension: '.tex' },
less: { name: 'Less', extension: '.less' },
liquid: { name: 'Liquid', extension: '.liquid' },
lisp: { name: 'Lisp', extension: '.lisp' },
logo: { name: 'Logo', extension: '.logo' },
lua: { name: 'Lua', extension: '.lua' },
makefile: { name: 'Makefile', extension: '.makefile' },
markdown: { name: 'Markdown', extension: '.md' },
marko: { name: 'Marko', extension: '.marko' },
matlab: { name: 'MATLAB', extension: '.m' },
mdx: { name: 'MDX', extension: '.mdx' },
nginx: { name: 'Nginx', extension: '.conf' },
nim: { name: 'Nim', extension: '.nim' },
nix: { name: 'Nix', extension: '.nix' },
'objective-c': { name: 'Objective-C', extension: '.m' },
'objective-cpp': { name: 'Objective-C++', extension: '.mm' },
ocaml: { name: 'OCaml', extension: '.ml' },
pascal: { name: 'Pascal', extension: '.pas' },
perl: { name: 'Perl', extension: '.pl' },
php: { name: 'PHP', extension: '.php' },
plsql: { name: 'PL/SQL', extension: '.sql' },
postcss: { name: 'PostCSS', extension: '.pcss' },
powerquery: { name: 'Power Query', extension: '.pq' },
powershell: { name: 'PowerShell', extension: '.ps1' },
prisma: { name: 'Prisma', extension: '.prisma' },
prolog: { name: 'Prolog', extension: '.pl' },
proto: { name: 'Protocol Buffers', extension: '.proto' },
pug: { name: 'Pug', extension: '.pug' },
puppet: { name: 'Puppet', extension: '.pp' },
purescript: { name: 'PureScript', extension: '.purs' },
python: { name: 'Python', extension: '.py' },
r: { name: 'R', extension: '.r' },
raku: { name: 'Raku', extension: '.raku' },
razor: { name: 'Razor', extension: '.cshtml' },
reg: { name: 'Registry', extension: '.reg' },
rel: { name: 'Rel', extension: '.rel' },
riscv: { name: 'RISC-V', extension: '.s' },
rst: { name: 'reStructuredText', extension: '.rst' },
ruby: { name: 'Ruby', extension: '.rb' },
rust: { name: 'Rust', extension: '.rs' },
sas: { name: 'SAS', extension: '.sas' },
sass: { name: 'Sass', extension: '.sass' },
scala: { name: 'Scala', extension: '.scala' },
scheme: { name: 'Scheme', extension: '.scm' },
scss: { name: 'SCSS', extension: '.scss' },
shaderlab: { name: 'ShaderLab', extension: '.shader' },
shell: { name: 'Shell', extension: '.sh' },
smalltalk: { name: 'Smalltalk', extension: '.st' },
solidity: { name: 'Solidity', extension: '.sol' },
sparql: { name: 'SPARQL', extension: '.rq' },
sql: { name: 'SQL', extension: '.sql' },
'ssh-config': { name: 'SSH Config', extension: '' },
stata: { name: 'Stata', extension: '.do' },
stylus: { name: 'Stylus', extension: '.styl' },
svelte: { name: 'Svelte', extension: '.svelte' },
swift: { name: 'Swift', extension: '.swift' },
'system-verilog': { name: 'SystemVerilog', extension: '.sv' },
tasl: { name: 'TASL', extension: '.tasl' },
tcl: { name: 'Tcl', extension: '.tcl' },
tex: { name: 'TeX', extension: '.tex' },
toml: { name: 'TOML', extension: '.toml' },
tsx: { name: 'TSX', extension: '.tsx' },
turtle: { name: 'Turtle', extension: '.ttl' },
twig: { name: 'Twig', extension: '.twig' },
typescript: { name: 'TypeScript', extension: '.ts' },
v: { name: 'V', extension: '.v' },
vb: { name: 'VB', extension: '.vb' },
verilog: { name: 'Verilog', extension: '.v' },
vhdl: { name: 'VHDL', extension: '.vhdl' },
viml: { name: 'VimL', extension: '.vim' },
vue: { name: 'Vue', extension: '.vue' },
wasm: { name: 'WebAssembly', extension: '.wasm' },
wenyan: { name: 'Wenyan', extension: '.wy' },
xml: { name: 'XML', extension: '.xml' },
xsl: { name: 'XSL', extension: '.xsl' },
yaml: { name: 'YAML', extension: '.yaml' },
zenscript: { name: 'ZenScript', extension: '.zs' }
plaintext: { name: 'Plain Text', extension: 'txt' },
'1c': { name: '1c', extension: '' },
abnf: { name: 'Augmented Backus-Naur Form', extension: 'abnf' },
accesslog: { name: 'Access Log', extension: 'log' },
actionscript: { name: 'ActionScript', extension: 'as' },
ada: { name: 'Ada', extension: 'ada' },
angelscript: { name: 'AngelScript', extension: 'angelscript' },
apache: { name: 'Apache', extension: 'apache' },
applescript: { name: 'AppleScript', extension: 'applescript' },
arcade: { name: 'Arcade', extension: 'arcade' },
arduino: { name: 'Arduino', extension: 'ino' },
arm: { name: 'ARM Assembly', extension: 's' },
asciidoc: { name: 'AsciiDoc', extension: 'adoc' },
aspectj: { name: 'AspectJ', extension: 'aj' },
autohotkey: { name: 'AutoHotkey', extension: 'ahk' },
autoit: { name: 'AutoIt', extension: 'au3' },
avrasm: { name: 'AVR Assembly', extension: 's' },
awk: { name: 'AWK', extension: 'awk' },
bash: { name: 'Bash', extension: 'sh' },
basic: { name: 'BASIC', extension: 'bas' },
bnf: { name: 'Backus-Naur Form', extension: 'bnf' },
brainfuck: { name: 'Brainfuck', extension: 'bf' },
c: { name: 'C', extension: 'c' },
cpp: { name: 'C++', extension: 'cpp' },
hpp: { name: 'C++ Header', extension: 'h' },
csharp: { name: 'C#', extension: 'cs' },
cal: { name: 'C/AL', extension: '' },
cos: { name: 'Cache Object Script', extension: '' },
capnproto: { name: "Cap'n Proto", extension: 'capnp' },
clojure: { name: 'Clojure', extension: 'clj' },
cmake: { name: 'CMake', extension: 'cmake' },
coffeescript: { name: 'CoffeeScript', extension: 'coffee' },
coq: { name: 'Coq', extension: 'v' },
crmsh: { name: 'CRMsH', extension: '' },
crystal: { name: 'Crystal', extension: 'cr' },
csp: { name: 'CSP', extension: 'csp' },
css: { name: 'CSS', extension: 'css' },
d: { name: 'D', extension: 'd' },
dart: { name: 'Dart', extension: 'dart' },
deplhi: { name: 'Delphi', extension: 'pas' },
diff: { name: 'Diff', extension: 'diff' },
django: { name: 'Django', extension: 'django' },
dns: { name: 'DNS Zone', extension: 'dns' },
dockerfile: { name: 'Dockerfile', extension: 'dockerfile' },
dos: { name: 'DOS', extension: 'bat' },
bat: { name: 'Batchfile', extension: 'bat' },
dsconfig: { name: 'DSConfig', extension: '' },
dts: { name: 'Device Tree', extension: 'dts' },
dust: { name: 'Dust', extension: 'dust' },
ebnf: { name: 'Extended Backus-Naur Form', extension: 'ebnf' },
elixir: { name: 'Elixir', extension: 'ex' },
elm: { name: 'Elm', extension: 'elm' },
erlang: { name: 'Erlang', extension: 'erl' },
excel: { name: 'Excel', extension: 'xlsx' },
fsharp: { name: 'F#', extension: 'fs' },
fix: { name: 'FIX', extension: 'fix' },
flix: { name: 'Flix', extension: 'flix' },
fortran: { name: 'Fortran', extension: 'f90' },
gcode: { name: 'G-code', extension: 'gcode' },
gams: { name: 'GAMS', extension: 'gms' },
gauss: { name: 'GAUSS', extension: 'gss' },
gherkin: { name: 'Gherkin', extension: '' },
go: { name: 'Go', extension: 'go' },
golo: { name: 'Golo', extension: 'golo' },
gradle: { name: 'Gradle', extension: 'gradle' },
graphql: { name: 'GraphQL', extension: 'graphql' },
groovy: { name: 'Groovy', extension: 'groovy' },
haml: { name: 'HAML', extension: 'haml' },
handlebars: { name: 'Handlebars', extension: 'hbs' },
haskell: { name: 'Haskell', extension: 'hs' },
haxe: { name: 'Haxe', extension: 'hx' },
html: { name: 'HTML', extension: 'html' },
xml: { name: 'XML', extension: 'xml' },
rss: { name: 'RSS', extension: 'rss' },
atom: { name: 'Atom', extension: 'atom' },
svg: { name: 'SVG', extension: 'svg' },
http: { name: 'HTTP', extension: 'http' },
https: { name: 'HTTPS', extension: 'http' },
hy: { name: 'Hy', extension: 'hy' },
inform7: { name: 'Inform 7', extension: 'ni' },
ini: { name: 'INI', extension: 'ini' },
toml: { name: 'TOML', extension: 'toml' },
irpf90: { name: 'IRPF90', extension: 'irpf90' },
java: { name: 'Java', extension: 'java' },
javascript: { name: 'JavaScript', extension: 'js' },
jolie: { name: 'Jolie', extension: 'ol' },
json: { name: 'JSON', extension: 'json' },
json5: { name: 'JSON5', extension: 'json5' },
julia: { name: 'Julia', extension: 'jl' },
'julia-repl': { name: 'Julia REPL', extension: '' },
kotlin: { name: 'Kotlin', extension: 'kt' },
lasso: { name: 'Lasso', extension: 'lasso' },
latex: { name: 'LaTeX', extension: 'tex' },
ldif: { name: 'LDIF', extension: 'ldif' },
leaf: { name: 'Leaf', extension: 'leaf' },
less: { name: 'Less', extension: 'less' },
lisp: { name: 'Lisp', extension: 'lisp' },
livecodeserver: { name: 'LiveCode Server', extension: '' },
livescript: { name: 'LiveScript', extension: 'ls' },
lua: { name: 'Lua', extension: 'lua' },
makefile: { name: 'Makefile', extension: 'makefile' },
markdown: { name: 'Markdown', extension: 'md' },
mathematica: { name: 'Mathematica', extension: 'nb' },
matlab: { name: 'MATLAB', extension: 'm' },
maxima: { name: 'Maxima', extension: 'max' },
mel: { name: 'Maya Embedded Language', extension: 'mel' },
mercury: { name: 'Mercury', extension: 'm' },
mipsasm: { name: 'MIPS Assembly', extension: 's' },
mizar: { name: 'Mizar', extension: 'miz' },
mojolicious: { name: 'Mojolicious', extension: '' },
monkey: { name: 'Monkey', extension: 'monkey' },
moonscript: { name: 'MoonScript', extension: 'moon' },
n1ql: { name: 'N1QL', extension: '' },
nginx: { name: 'Nginx', extension: 'nginx' },
nim: { name: 'Nim', extension: 'nim' },
nix: { name: 'Nix', extension: 'nix' },
nsis: { name: 'NSIS', extension: 'nsi' },
objectivec: { name: 'Objective-C', extension: 'm' },
ocaml: { name: 'OCaml', extension: 'ml' },
glsl: { name: 'OpenGL Shading Language', extension: 'glsl' },
openscad: { name: 'OpenSCAD', extension: 'scad' },
ruleslanguage: { name: 'Oracle Rules Language', extension: '' },
oxygene: { name: 'Oxygene', extension: 'oxygene' },
parser3: { name: 'Parser3', extension: '' },
perl: { name: 'Perl', extension: 'pl' },
pf: { name: 'PF', extension: 'pf' },
php: { name: 'PHP', extension: 'php' },
pony: { name: 'Pony', extension: 'pony' },
postgresql: { name: 'PostgreSQL', extension: 'sql' },
powershell: { name: 'PowerShell', extension: 'ps1' },
processing: { name: 'Processing', extension: 'pde' },
prolog: { name: 'Prolog', extension: 'pl' },
properties: { name: 'Java Properties', extension: 'properties' },
protobuf: { name: 'Protocol Buffers', extension: 'proto' },
puppet: { name: 'Puppet', extension: 'pp' },
python: { name: 'Python', extension: 'py' },
profiler: { name: 'Poython Profiler Results', extension: '' },
'python-repl': { name: 'Python REPL', extension: '' },
q: { name: 'Q', extension: 'q' },
qml: { name: 'QML', extension: 'qml' },
r: { name: 'R', extension: 'r' },
reasonml: { name: 'ReasonML', extension: 're' },
rib: { name: 'RenderMan Interface Bytestream', extension: 'rib' },
rsl: { name: 'RenderMan Shading Language', extension: 'rsl' },
graph: { name: 'Roboconf', extension: '' },
ruby: { name: 'Ruby', extension: 'rb' },
rust: { name: 'Rust', extension: 'rs' },
sas: { name: 'SAS', extension: 'sas' },
scala: { name: 'Scala', extension: 'scala' },
scheme: { name: 'Scheme', extension: 'scm' },
scilab: { name: 'Scilab', extension: 'sci' },
scss: { name: 'SCSS', extension: 'scss' },
shell: { name: 'Shell', extension: 'sh' },
smali: { name: 'Smali', extension: 'smali' },
smalltalk: { name: 'Smalltalk', extension: 'st' },
sml: { name: 'Standard ML', extension: 'sml' },
sql: { name: 'SQL', extension: 'sql' },
stan: { name: 'Stan', extension: 'stan' },
stata: { name: 'Stata', extension: 'do' },
step21: { name: 'STEP Part 21', extension: 'stp' },
stylus: { name: 'Stylus', extension: 'styl' },
subunit: { name: 'SubUnit', extension: 'subunit' },
svelte: { name: 'Svelte', extension: 'svelte' }, // svelte seems to work even though the docs say it requires a plugin
swift: { name: 'Swift', extension: 'swift' },
tcl: { name: 'Tcl', extension: 'tcl' },
tap: { name: 'Test Anything Protocol', extension: 'tap' },
thrift: { name: 'Thrift', extension: 'thrift' },
toit: { name: 'Toit', extension: 'toit' },
tp: { name: 'TP', extension: 'tp' },
twig: { name: 'Twig', extension: 'twig' },
typescript: { name: 'TypeScript', extension: 'ts' },
vala: { name: 'Vala', extension: 'vala' },
vbnet: { name: 'VB.NET', extension: 'vb' },
vba: { name: 'VBA', extension: 'vba' },
vbscript: { name: 'VBScript', extension: 'vbs' },
verilog: { name: 'Verilog', extension: 'v' },
vhdl: { name: 'VHDL', extension: 'vhd' },
vim: { name: 'Vim Script', extension: 'vim' },
axapta: { name: 'X++', extension: 'xpp' },
x86asm: { name: 'x86 Assembly', extension: 's' },
xl: { name: 'XL', extension: 'xl' },
xquery: { name: 'XQuery', extension: 'xq' },
yaml: { name: 'YAML', extension: 'yaml' },
zephir: { name: 'Zephir', extension: 'zep' }
};
export const expiresOptions = [
+2 -9
View File
@@ -24,15 +24,8 @@ export interface ReportListResponse {
pagination: Pagination;
}
export const reportTypeLabels = [
'Spam',
'Abuse',
'InappropriateContent',
'CopyrightViolation',
'Fraud',
'Other'
] as const;
export const reportTypeLabels = ['CopyrightViolation', 'IllegalContent', 'Fraud', 'Other'] as const;
export const reportStatusLabels = ['Open', 'InProgress', 'Resolved', 'Closed'] as const;
export const reportStatusLabels = ['Open', 'Closed'] as const;
export const reportTargetLabels = ['Paste', 'User'] as const;
+12 -8
View File
@@ -113,8 +113,9 @@ export function dateToRelativeString(
return `${parts.join(', ')} ${suffix}`.trim();
}
export function tooltip(node: HTMLElement, text: string) {
let currentText = text ?? '';
export function tooltip(node: HTMLElement, params: string | [string, boolean?]) {
let currentText = typeof params === 'string' ? params : (params[0] ?? '');
let darker = typeof params === 'string' ? false : (params[1] ?? false);
let tooltipEl: HTMLDivElement | null = null;
let caretEl: HTMLDivElement | null = null;
let showTimeout: ReturnType<typeof setTimeout>;
@@ -123,8 +124,9 @@ export function tooltip(node: HTMLElement, text: string) {
function createTooltip() {
if (!currentText || currentText.trim() === '') return;
const el = document.createElement('div');
el.className =
'fixed z-50 rounded bg-neutral-800 px-2 py-1 text-sm text-white shadow-lg opacity-0 transition-opacity duration-150';
el.className = `fixed z-50 rounded ${
darker ? 'bg-neutral-900 border border-neutral-800' : 'bg-neutral-800'
} px-2 py-1 text-sm text-white shadow-lg opacity-0 transition-opacity duration-150`;
el.style.maxWidth = '90%';
el.style.wordBreak = 'break-word';
@@ -219,10 +221,10 @@ export function tooltip(node: HTMLElement, text: string) {
caretEl.style.borderLeft = '7px solid transparent';
caretEl.style.borderRight = '7px solid transparent';
if (caretOnTop) {
caretEl.style.borderBottom = '7px solid #27272a';
caretEl.style.borderBottom = `7px solid ${darker ? '#171717' : '#27272a'}`;
caretEl.style.borderTop = '';
} else {
caretEl.style.borderTop = '7px solid #27272a';
caretEl.style.borderTop = `7px solid ${darker ? '#171717' : '#27272a'}`;
caretEl.style.borderBottom = '';
}
}
@@ -260,8 +262,10 @@ export function tooltip(node: HTMLElement, text: string) {
window.addEventListener('resize', mouseOut, true);
return {
update(newText: string) {
currentText = newText ?? '';
update(newParams: string | [string, boolean?]) {
currentText = typeof newParams === 'string' ? newParams : (newParams[0] ?? '');
darker = typeof newParams === 'string' ? false : (newParams[1] ?? false);
if (!currentText || currentText.trim() === '') {
if (tooltipEl) {
tooltipEl.remove();
@@ -0,0 +1,37 @@
import hljs from 'highlight.js';
type HighlightRequest = {
id: number;
code: string;
lang: string;
};
type HighlightResponse = {
id: number;
html: string;
};
const escapeHtml = (value: string) =>
value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
self.onmessage = (event: MessageEvent<HighlightRequest>) => {
const { id, code, lang } = event.data;
let html = '';
try {
if (lang === 'plaintext') {
html = escapeHtml(code);
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
html = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
} else {
html = hljs.highlightAuto(code).value;
}
} catch {
if (lang === 'plaintext') {
html = escapeHtml(code);
} else {
html = hljs.highlightAuto(code).value;
}
}
const response: HighlightResponse = { id, html };
self.postMessage(response);
};
@@ -58,7 +58,6 @@
</svelte:head>
<Navbar {data} />
<!-- <div class="h-15 w-full"></div> -->
<slot />
<Footer />
+6 -14
View File
@@ -65,17 +65,9 @@
let max: number;
let element = markdown ? markdownConatiner : textArea;
if (!markdown) {
textArea.style.height = 'auto';
h = textArea.scrollHeight;
max = MAX_HEIGHT();
} else {
markdownConatiner.style.height = 'auto';
h = markdownConatiner.scrollHeight;
max = MAX_HEIGHT();
}
element.style.height = 'auto';
h = element.scrollHeight;
max = MAX_HEIGHT();
if (h > max) {
element.style.height = max + 'px';
@@ -140,9 +132,9 @@
data.auth?.cf_turnstile_site_key &&
window.turnstile
) {
const token = window.turnstile.getResponse();
if (token) {
params.append('token', token);
const verificationToken = window.turnstile.getResponse();
if (verificationToken) {
params.append('verificationToken', verificationToken);
}
}
+37 -17
View File
@@ -43,6 +43,7 @@
import Dropdown from '$lib/components/Dropdown.svelte';
import { openModal } from '$lib/stores/modal';
import type { Paste } from '$lib/types/paste';
import HighlightWorker from '$lib/workers/highlight.worker?worker';
export let data: PageData;
let reportSiteKey: string | null = null;
@@ -59,6 +60,8 @@
let contentRendered = false;
let downloadedPaste = false;
let copiedPaste = false;
let highlightWorker: Worker | null = null;
let highlightRequestId = 0;
let scrollY = 0;
@@ -90,10 +93,12 @@
};
onMount(() => {
highlightWorker = new HighlightWorker();
interval = setInterval(() => {
now = new Date();
}, 1000);
return () => {
if (highlightWorker) highlightWorker.terminate();
if (interval) clearInterval(interval);
};
});
@@ -147,23 +152,37 @@
const lang = (data.paste.syntax ?? '').toLowerCase();
let highlighted = '';
try {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
} else {
highlighted = hljs.highlightAuto(code).value;
}
} catch {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else {
highlighted = hljs.highlightAuto(code).value;
const worker = highlightWorker;
if (worker) {
const requestId = ++highlightRequestId;
highlighted = await new Promise((resolve) => {
const handler = (event: MessageEvent<{ id: number; html: string }>) => {
if (event.data.id !== requestId) return;
worker.removeEventListener('message', handler);
resolve(event.data.html);
};
worker.addEventListener('message', handler);
worker.postMessage({ id: requestId, code, lang });
});
} else {
try {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
} else {
highlighted = hljs.highlightAuto(code).value;
}
} catch {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else {
highlighted = hljs.highlightAuto(code).value;
}
}
}
const wrapped = `<pre><code class="hljs">${highlighted}</code></pre>`;
@@ -911,6 +930,7 @@
on:click={handleMarkdownClick}
role="presentation"
>
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html pasteContent}
</div>
{/if}
@@ -17,7 +17,7 @@
let passwordFocused = false;
let showPassword = false;
1;
let passwordChecks = {
minLength: false,
maxLength: false,
@@ -0,0 +1,23 @@
import type { PageServerLoad } from './$types';
import { env } from '$env/dynamic/private';
import { error, isHttpError } from '@sveltejs/kit';
import { extractError } from '$lib/utils/misc';
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
export const load: PageServerLoad = async ({ fetch }) => {
try {
const res = await fetch(`${API_URL}/api/stats`);
if (!res.ok) {
const json = await res.json().catch(() => ({}));
const message = extractError(json);
throw error(res.status, message ?? 'Failed to load statistics');
}
const stats = await res.json();
return { stats };
} catch (e) {
if (isHttpError(e)) throw e;
throw error(500, 'Failed to load statistics');
}
};
@@ -0,0 +1,124 @@
<script lang="ts">
import type { PageData } from './$types';
import { formatBytes, formatNumber, tooltip } from '$lib/utils/misc';
import { FileText, Users, Database, TrendingUp } from '@lucide/svelte';
export let data: PageData;
$: stats = data.stats.stats;
$: dailyData = stats.pastes.daily || [];
$: maxCount = Math.max(...dailyData.map((d: { count: number; date: number }) => d.count), 5);
function getOrdinal(n: number) {
const s = ['th', 'st', 'nd', 'rd'];
const v = n % 100;
return s[(v - 20) % 10] || s[v] || s[0];
}
function formatDate(timestamp: number) {
const date = new Date(timestamp);
const day = date.getDate();
const options: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric' };
const locale = typeof navigator !== 'undefined' ? navigator.language : 'en-US';
if (!locale.startsWith('en')) {
return date.toLocaleDateString(locale, options);
}
const month = date.toLocaleString(locale, { month: 'short' });
const suffix = getOrdinal(day);
const parts = new Intl.DateTimeFormat(locale, { month: 'short', day: 'numeric' }).formatToParts(
date
);
if (parts[0].type === 'day') {
return `${day}${suffix} ${month}`;
}
return `${month} ${day}${suffix}`;
}
</script>
<svelte:head>
<title>Statistics - Sharpbin</title>
</svelte:head>
<main
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-4xl font-bold">Statistics</h1>
<div class="mb-8 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
<div class="flex items-center space-x-4 rounded-lg bg-neutral-800 p-4">
<div class="rounded-full bg-neutral-500/20 p-3 text-white">
<FileText size={24} />
</div>
<div>
<p class="text-sm text-neutral-400">Total Pastes</p>
<p class="text-2xl font-bold">{formatNumber(stats.pastes.total)}</p>
</div>
</div>
<div class="flex items-center space-x-4 rounded-lg bg-neutral-800 p-4">
<div class="rounded-full bg-neutral-500/20 p-3 text-white">
<TrendingUp size={24} />
</div>
<div>
<p class="text-sm text-neutral-400">Last 7 Days</p>
<p class="text-2xl font-bold">{formatNumber(stats.pastes.past7Days)}</p>
</div>
</div>
<div class="flex items-center space-x-4 rounded-lg bg-neutral-800 p-4">
<div class="rounded-full bg-neutral-500/20 p-3 text-white">
<Database size={24} />
</div>
<div>
<p class="text-sm text-neutral-400">Total Storage Used</p>
<p
class="text-2xl font-bold"
use:tooltip={[
`${stats.pastes.trueTotalSizeInBytes != stats.pastes.totalSizeInBytes ? `Uncompressed Size: ${formatBytes(stats.pastes.trueTotalSizeInBytes)}` : ''}`,
true
]}
>
{formatBytes(stats.pastes.totalSizeInBytes)}
</p>
</div>
</div>
<div class="flex items-center space-x-4 rounded-lg bg-neutral-800 p-4">
<div class="rounded-full bg-neutral-500/20 p-3 text-white">
<Users size={24} />
</div>
<div>
<p class="text-sm text-neutral-400">Total Users</p>
<p class="text-2xl font-bold">{formatNumber(stats.users.total)}</p>
</div>
</div>
</div>
<div class="rounded-lg bg-neutral-800 p-6">
<h2 class="mb-6 text-xl font-semibold">Pastes Growth (Last 7 Days)</h2>
<div class="flex h-64 w-full items-end justify-between gap-2 px-2">
{#if dailyData.length > 0}
{#each dailyData as d (d.date)}
<div class="group relative flex h-full flex-1 flex-col justify-end">
<div
use:tooltip={[`${formatNumber(d.count)} paste${d.count !== 1 ? 's' : ''}`, true]}
class="w-full rounded-t-sm bg-neutral-600 transition-all hover:bg-neutral-500"
style="height: {d.count === 0 ? '2px' : Math.max((d.count / maxCount) * 95, 2)}%"
></div>
<div
class="absolute top-full mt-2 w-full text-center text-[10px] text-neutral-400 sm:text-xs"
>
{formatDate(d.date)}
</div>
</div>
{/each}
{:else}
<div class="flex h-full w-full items-center justify-center text-neutral-500">
No data available for the last 7 days.
</div>
{/if}
</div>
<div class="h-6"></div>
</div>
</div>
</main>
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -21,7 +21,8 @@ export default defineConfig({
server: {
host: true,
proxy: {
'/api': apiUrl
'/api': apiUrl,
'/openapi': apiUrl
},
allowedHosts: allowedHosts
},
+5
View File
@@ -0,0 +1,5 @@
Migrations/
obj/
bin/
cache/
SharpbinV3/
+6
View File
@@ -0,0 +1,6 @@
{
"printWidth": 150,
"useTabs": false,
"indentSize": 4,
"endOfLine": "auto"
}
@@ -0,0 +1,50 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Authentication
{
public sealed class ApiKeyAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ApiKeyService apiKeyService
) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
private readonly ApiKeyService _apiKeyService = apiKeyService;
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var apiKeyString = Context.GetApiKey();
if (string.IsNullOrEmpty(apiKeyString))
return AuthenticateResult.NoResult();
var apiKey = await _apiKeyService.GetByKeyAsync(apiKeyString);
if (apiKey == null || apiKey.User == null)
return AuthenticateResult.Fail("Invalid API key.");
var claims = new List<Claim>
{
new("uuid", apiKey.User.UUID.ToString()),
new("username", apiKey.User.Username ?? ""),
new("displayname", apiKey.User.DisplayName ?? ""),
new("totp_enabled", (apiKey.User.Totp != null).ToString()),
};
if (apiKey.User.Roles != null)
claims.AddRange(apiKey.User.Roles.Select(r => new Claim(ClaimTypes.Role, r.ToString())));
var identity = new ClaimsIdentity(claims, AuthSchemes.ApiKey);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, AuthSchemes.ApiKey);
Context.SetApiKeyContext(apiKey);
await _apiKeyService.UpdateLastUsedAsync(apiKey.UUID);
return AuthenticateResult.Success(ticket);
}
}
}
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.Authentication
{
public static class AuthSchemes
{
public const string Combined = "Combined";
public const string ApiKey = "ApiKey";
}
}
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using SharpbinV3.Server.Extensions;
namespace SharpbinV3.Server.Authorization
{
@@ -7,18 +8,27 @@ namespace SharpbinV3.Server.Authorization
{
private readonly bool _requireAuth = requireAuth;
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
NotBannedRequirement requirement)
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
{
var httpContext = context.Resource as HttpContext;
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
if (!isAuthenticated && httpContext != null)
{
var apiKey = httpContext.GetApiKeyFromContext();
if (apiKey != null)
{
isAuthenticated = true;
}
}
if (_requireAuth && !isAuthenticated)
return Task.CompletedTask;
var isBanned = context.User.Claims.Any(c =>
(c.Type == ClaimTypes.Role || c.Type == "role") &&
c.Value == "403");
var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403");
if (httpContext?.GetApiKeyFromContext()?.User?.Roles?.Contains(403) == true)
isBanned = true;
if (!isBanned)
context.Succeed(requirement);
@@ -2,7 +2,5 @@
namespace SharpbinV3.Server.Authorization
{
public class NotBannedRequirement : IAuthorizationRequirement
{
}
public class NotBannedRequirement : IAuthorizationRequirement { }
}
+156 -66
View File
@@ -6,6 +6,7 @@ using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.ApiKey;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.DTOs.User;
using SharpbinV3.Server.Extensions;
@@ -19,11 +20,19 @@ namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options,
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase
public class AuthController(
UserService userService,
AuthService authService,
ApiKeyService apiKeyService,
IOptions<AuthSettings> options,
VerificationService verification,
TotpVerificationProvider totp,
AppDbContext db
) : ControllerBase
{
private readonly AuthService _authService = authService;
private readonly UserService _userService = userService;
private readonly ApiKeyService _apiKeyService = apiKeyService;
private readonly VerificationService _verification = verification;
private readonly TotpVerificationProvider _totp = totp;
private readonly AppDbContext _db = db;
@@ -37,11 +46,7 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { success = false, message = "Registration is disabled." });
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (!await _verification.VerifyAsync(new VerificationContext
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
return BadRequest(new { success = false, message = "Verification failed." });
var existingUser = await _userService.GetByUsername(request.Username);
@@ -57,21 +62,22 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { success = false, message = "Display name should not exceed 26 characters." });
var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
return Ok(new
{
message = "User registered successfully.",
user = new UserResponseDto
return Ok(
new
{
UID = user.UID,
UUID = user.UUID,
Username = user.Username,
DisplayName = user.DisplayName,
Email = user.Email,
Roles = user.Roles,
Visibility = user.Visibility,
LastLogin = user.LastLogin
message = "User registered successfully.",
user = new UserResponseDto
{
UID = user.UID,
UUID = user.UUID,
Username = user.Username,
DisplayName = user.DisplayName,
Email = user.Email,
Roles = user.Roles,
Visibility = user.Visibility,
LastLogin = user.LastLogin,
},
}
}
);
}
@@ -83,11 +89,7 @@ namespace SharpbinV3.Server.Controllers
if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email))
return BadRequest(new { success = false, message = "Username or email is required." });
if (!await _verification.VerifyAsync(new VerificationContext
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
return BadRequest(new { success = false, message = "Verification failed." });
User? user = null;
@@ -104,24 +106,25 @@ namespace SharpbinV3.Server.Controllers
{
if (string.IsNullOrWhiteSpace(request.TotpCode))
return BadRequest(new { success = false, message = "TOTP code is required." });
var totpValid = await _totp.VerifyAsync(new VerificationContext
{
UserUUID = user.UUID,
Code = request.TotpCode
});
var totpValid = await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode });
if (!totpValid)
return BadRequest(new { success = false, message = "Invalid TOTP code." });
}
var token = _authService.GenerateJWTToken(user);
await _authService.UpdateLoginTime(user);
var result = await token;
return Ok(new LoginResponseDto
{
Success = true,
Token = result.Token ?? string.Empty,
RefreshToken = result.RefreshToken ?? string.Empty
});
return Ok(
new LoginResponseDto
{
Success = true,
Token = result.Token ?? string.Empty,
RefreshToken = result.RefreshToken ?? string.Empty,
}
);
}
[HttpPost]
[Route("refresh")]
[EnableRateLimiting("Sliding")]
@@ -130,16 +133,17 @@ namespace SharpbinV3.Server.Controllers
try
{
var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken);
return Ok(new TokenRefreshResponseDto
{
Success = jwtResult?.Success ?? false,
Message = jwtResult?.Errors != null && jwtResult.Errors.Count > 0 ? string.Join("; ", jwtResult.Errors) : "Token refreshed successfully.",
Token = jwtResult != null ? new TokenData
return Ok(
new TokenRefreshResponseDto
{
Token = jwtResult.Token,
RefreshToken = jwtResult.RefreshToken
} : null
});
Success = jwtResult?.Success ?? false,
Message =
jwtResult?.Errors != null && jwtResult.Errors.Count > 0
? string.Join("; ", jwtResult.Errors)
: "Token refreshed successfully.",
Token = jwtResult != null ? new TokenData { Token = jwtResult.Token, RefreshToken = jwtResult.RefreshToken } : null,
}
);
}
catch (Exception ex)
{
@@ -153,39 +157,45 @@ namespace SharpbinV3.Server.Controllers
public IActionResult GetSiteInfo()
{
var authSettings = options.Value;
return Ok(new
{
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
registration_enabled = authSettings.Registration_Enabled
});
return Ok(
new
{
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
registration_enabled = authSettings.Registration_Enabled,
}
);
}
[HttpGet]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[Route("totp/enroll")]
public async Task<IActionResult> StartTotpEnrollment()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user is null) return BadRequest(new { success = false, message = "User not found." });
if (user is null)
return BadRequest(new { success = false, message = "User not found." });
var secret = _totp.GenerateSecret();
var secretBase32 = _totp.ToBase32(secret);
var account = string.IsNullOrWhiteSpace(user.Email) ? user.Username : user.Email!;
var uri = _totp.BuildOtpAuthUri("SharpbinV3", account, secretBase32);
return Ok(new { success = true, secret = secretBase32, otpauth = uri });
return Ok(
new
{
success = true,
secret = secretBase32,
otpauth = uri,
}
);
}
[HttpPost]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[Route("totp/enable")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
{
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
if (string.IsNullOrEmpty(uuidClaim))
return Unauthorized(new { success = false, message = "Invalid token." });
var uuid = Guid.Parse(uuidClaim);
var uuid = Guid.Parse(User.FindFirst("uuid")!.Value);
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new { success = false, message = "Secret and code are required." });
@@ -210,27 +220,107 @@ namespace SharpbinV3.Server.Controllers
}
[HttpPost]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[Route("totp/disable")]
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null) return BadRequest(new { success = false, message = "User not found." });
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
if (string.IsNullOrWhiteSpace(dto.Code))
return BadRequest(new { success = false, message = "TOTP code is required." });
var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == user.UUID);
if (existing is null)
return BadRequest(new { success = false, message = "TOTP is not enabled." });
if (!_totp.VerifyAsync(new VerificationContext
{
UserUUID = user.UUID,
Code = dto.Code
}).Result)
if (!_totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = dto.Code }).Result)
return BadRequest(new { success = false, message = "Invalid TOTP code." });
_db.UserTotps.Remove(existing);
await _db.SaveChangesAsync();
return Ok(new { success = true, message = "TOTP disabled." });
}
[HttpPost]
[Authorize(Policy = "JwtOnly")]
[Route("apikey/create")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> CreateApiKey([FromBody] CreateApiKeyRequest request)
{
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { success = false, message = "API key name is required." });
if (request.Name.Length > 26)
return BadRequest(new { success = false, message = "API key name must not exceed 26 characters." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var existingKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
if (existingKeys.Count >= 10)
return BadRequest(new { success = false, message = "API key limit reached. Please delete existing keys before creating new ones." });
var (apiKey, key) = await _apiKeyService.CreateAsync(user.UUID, request.Name);
return Ok(
new
{
success = true,
message = "API key created. Save it now as you won't be able to see it again.",
apiKey = new ApiKeyResponseDto
{
UUID = apiKey.UUID,
Key = key,
Name = apiKey.Name,
CreatedAt = apiKey.CreatedAt,
},
}
);
}
[HttpGet]
[Authorize]
[Route("apikey/list")]
public async Task<IActionResult> ListApiKeys()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var apiKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
return Ok(
new
{
success = true,
apiKeys = apiKeys
.Select(k => new ApiKeyListItemDto
{
UUID = k.UUID,
Name = k.Name,
CreatedAt = k.CreatedAt,
LastUsedAt = k.LastUsedAt,
})
.ToList(),
}
);
}
[HttpDelete]
[Authorize(Policy = "JwtOnly")]
[Route("apikey/{uuid}")]
public async Task<IActionResult> DeleteApiKey(string uuid)
{
if (!Guid.TryParse(uuid, out var keyUUID))
return BadRequest(new { success = false, message = "Invalid API key UUID." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var deleted = await _apiKeyService.DeleteAsync(user.UUID, keyUUID);
if (!deleted)
return NotFound(new { success = false, message = "API key not found." });
return Ok(new { success = true, message = "API key deleted." });
}
}
}
+181 -153
View File
@@ -15,8 +15,14 @@ namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService,
ReportService reportService, IOptions<PasteSettings> options, IOptions<AuthSettings> authSettings) : ControllerBase
public class PasteController(
PasteService pasteService,
VerificationService verificationService,
AuthService authService,
ReportService reportService,
IOptions<PasteSettings> options,
IOptions<AuthSettings> authSettings
) : ControllerBase
{
private readonly PasteService _pasteService = pasteService;
private readonly VerificationService _verificationService = verificationService;
@@ -29,7 +35,13 @@ namespace SharpbinV3.Server.Controllers
[Route("create")]
[Authorize(Policy = "NotBanned")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0, string? token = null)
public async Task<IActionResult> CreatePaste(
string title = "",
string syntax = "plaintext",
int visibility = 0,
long expiresAt = 0,
string? verificationToken = null
)
{
if (!_pasteService.ValidateExpiresAt(expiresAt))
return BadRequest(new { success = false, message = "Invalid expiration time." });
@@ -44,27 +56,37 @@ namespace SharpbinV3.Server.Controllers
if (content.Length == 0)
return BadRequest(new { success = false, message = "Paste content cannot be empty." });
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
return BadRequest(new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
return BadRequest(
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
);
if (_pasteSettings.RequiresVerfication && !await _verificationService.VerifyAsync(new VerificationContext
if (_pasteSettings.RequiresVerification && !HttpContext.IsApiKeyAuthenticated())
{
Token = token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { success = false, message = "Verification failed." });
var providedApiKey = HttpContext.GetApiKey();
if (providedApiKey != null)
return BadRequest(new { success = false, message = "Invalid API key." });
var verifyResult = await _verificationService.VerifyAsync(
new VerificationContext { Token = verificationToken, Ip = HttpContext.GetRequestIP() }
);
if (!verifyResult)
return BadRequest(new { success = false, message = "Verification failed." });
}
var user = await _authService.GetUserFromHttpContext(HttpContext);
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
return Ok(new PasteCreatedResponseDto
{
ID = paste.ID,
UUID = paste.UUID,
CreatedAt = paste.CreatedAt,
IsCompressed = paste.IsCompressed,
Size = paste.Size,
TrueSize = paste.TrueSize,
ExpiresAt = paste.ExpiresAt
});
return Ok(
new PasteCreatedResponseDto
{
ID = paste.ID,
UUID = paste.UUID,
CreatedAt = paste.CreatedAt,
IsCompressed = paste.IsCompressed,
Size = paste.Size,
TrueSize = paste.TrueSize,
ExpiresAt = paste.ExpiresAt,
}
);
}
[HttpGet]
@@ -79,42 +101,44 @@ namespace SharpbinV3.Server.Controllers
int? reportCount = null;
if (jwtUser != null && jwtUser.Roles.Any(r => r == 1 || r == 255))
{
var query = new ReportQuery
{
PastePID = paste.PID
};
var query = new ReportQuery { PastePID = paste.PID };
reportCount = await _reportService.GetReportCount(query);
}
return Ok(new
{
success = true,
paste = new PasteResponseDto
return Ok(
new
{
ID = paste.ID,
UUID = paste.UUID,
CreatedAt = paste.CreatedAt,
Title = paste.Title,
Size = paste.Size,
TrueSize = paste.TrueSize,
IsCompressed = paste.IsCompressed,
Views = paste.Views,
Syntax = paste.Syntax,
Visibility = paste.Visibility,
ExpiresAt = paste.ExpiresAt,
EditedAt = paste.EditedAt,
ReportCount = reportCount,
Author = paste.User != null && paste.User.Visibility == 0 ? new UserSimpleDto
success = true,
paste = new PasteResponseDto
{
UID = paste.User.UID,
UUID = paste.User.UUID,
Username = paste.User.Username,
DisplayName = paste.User.DisplayName,
Visibility = paste.User.Visibility,
Roles = paste.User.Roles
} : null
ID = paste.ID,
UUID = paste.UUID,
CreatedAt = paste.CreatedAt,
Title = paste.Title,
Size = paste.Size,
TrueSize = paste.TrueSize,
IsCompressed = paste.IsCompressed,
Views = paste.Views,
Syntax = paste.Syntax,
Visibility = paste.Visibility,
ExpiresAt = paste.ExpiresAt,
EditedAt = paste.EditedAt,
ReportCount = reportCount,
Author =
paste.User != null && paste.User.Visibility == 0
? new UserSimpleDto
{
UID = paste.User.UID,
UUID = paste.User.UUID,
Username = paste.User.Username,
DisplayName = paste.User.DisplayName,
Visibility = paste.User.Visibility,
Roles = paste.User.Roles,
}
: null,
},
}
});
);
}
[HttpGet]
@@ -122,7 +146,8 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> GetRawPasteByID(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound();
if (paste == null)
return NotFound();
if (paste.IsCompressed)
Response.Headers.Append("Content-Encoding", "gzip");
@@ -131,7 +156,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPut]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> EditPaste(string id)
{
string content = await new StreamReader(Request.Body).ReadToEndAsync();
@@ -142,9 +167,7 @@ namespace SharpbinV3.Server.Controllers
if (paste == null)
return StatusCode(404, new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
@@ -153,22 +176,21 @@ namespace SharpbinV3.Server.Controllers
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _pasteService.EditText(paste, content);
if (!result) return StatusCode(500, new { success = false, message = "An error occurred while editing the paste." });
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while editing the paste." });
return Ok(new { message = "Paste edited successfully." });
}
[HttpPatch]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
@@ -195,38 +217,39 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { success = false, message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
var newPaste = await _pasteService.Edit(paste);
return Ok(new
{
success = true,
message = "Paste metadata updated successfully.",
paste = new PasteResponseDto
return Ok(
new
{
ID = newPaste.ID,
UUID = newPaste.UUID,
CreatedAt = newPaste.CreatedAt,
Title = newPaste.Title,
Size = newPaste.Size,
TrueSize = newPaste.TrueSize,
IsCompressed = newPaste.IsCompressed,
Views = newPaste.Views,
Syntax = newPaste.Syntax,
Visibility = newPaste.Visibility,
ExpiresAt = newPaste.ExpiresAt
success = true,
message = "Paste metadata updated successfully.",
paste = new PasteResponseDto
{
ID = newPaste.ID,
UUID = newPaste.UUID,
CreatedAt = newPaste.CreatedAt,
Title = newPaste.Title,
Size = newPaste.Size,
TrueSize = newPaste.TrueSize,
IsCompressed = newPaste.IsCompressed,
Views = newPaste.Views,
Syntax = newPaste.Syntax,
Visibility = newPaste.Visibility,
ExpiresAt = newPaste.ExpiresAt,
},
}
});
);
}
[HttpDelete]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> DeletePaste(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound(new { success = false, message = "Paste not found." });
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
@@ -235,7 +258,8 @@ namespace SharpbinV3.Server.Controllers
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _pasteService.Delete(paste);
if (!result) return StatusCode(500, new { success = false, message = "An error occurred while deleting the paste." });
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the paste." });
return Ok(new { success = true, message = "Paste deleted successfully." });
}
@@ -250,8 +274,10 @@ namespace SharpbinV3.Server.Controllers
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"])
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);
@@ -266,55 +292,54 @@ namespace SharpbinV3.Server.Controllers
[HttpPost]
[Route("{id}/report")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext
{
Token = request.VerificationToken,
Ip = HttpContext.GetRequestIP()
}))
if (
!await _verificationService.VerifyAsync(
new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
)
)
return BadRequest(new { success = false, message = "Verification failed." });
Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description);
if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
return Ok(new
{
success = true,
message = "Paste reported successfully.",
report = new ReportResponseDto
return Ok(
new
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType,
UserUUID = report.UserUUID
success = true,
message = "Paste reported successfully.",
report = new ReportResponseDto
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType,
UserUUID = report.UserUUID,
},
}
});
);
}
[HttpPatch]
[Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
{
@@ -326,9 +351,7 @@ namespace SharpbinV3.Server.Controllers
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
@@ -350,7 +373,7 @@ namespace SharpbinV3.Server.Controllers
[HttpDelete]
[Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeletePasteReport(string id, int reportId)
{
@@ -362,9 +385,7 @@ namespace SharpbinV3.Server.Controllers
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
@@ -385,30 +406,35 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> GetRecentPastes()
{
var results = await _pasteService.GetList(0, 50, true);
return Ok(results.Select(p => new PasteResponseDto
{
ID = p.ID,
UUID = p.UUID,
CreatedAt = p.CreatedAt,
Title = p.Title,
Size = p.Size,
TrueSize = p.TrueSize,
IsCompressed = p.IsCompressed,
Views = p.Views,
Syntax = p.Syntax,
Visibility = p.Visibility,
ExpiresAt = p.ExpiresAt,
EditedAt = p.EditedAt,
Author = p.User != null && p.User.Visibility == 0 ? new UserSimpleDto
return Ok(
results.Select(p => new PasteResponseDto
{
UID = p.User.UID,
UUID = p.User.UUID,
Username = p.User.Username,
DisplayName = p.User.DisplayName,
Visibility = p.User.Visibility,
Roles = p.User.Roles
} : null
}));
ID = p.ID,
UUID = p.UUID,
CreatedAt = p.CreatedAt,
Title = p.Title,
Size = p.Size,
TrueSize = p.TrueSize,
IsCompressed = p.IsCompressed,
Views = p.Views,
Syntax = p.Syntax,
Visibility = p.Visibility,
ExpiresAt = p.ExpiresAt,
EditedAt = p.EditedAt,
Author =
p.User != null && p.User.Visibility == 0
? new UserSimpleDto
{
UID = p.User.UID,
UUID = p.User.UUID,
Username = p.User.Username,
DisplayName = p.User.DisplayName,
Visibility = p.User.Visibility,
Roles = p.User.Roles,
}
: null,
})
);
}
[HttpGet]
@@ -416,19 +442,21 @@ namespace SharpbinV3.Server.Controllers
[Route("info")]
public IActionResult GetCreatePasteOptions()
{
return Ok(new PasteOptionsDto
{
Syntaxes = [.. _pasteSettings.ValidSyntaxLanguages],
Visibilities =
[
new() { Value = 0, DisplayName = "Public" },
new() { Value = 1, DisplayName = "Unlisted" },
new() { Value = 2, DisplayName = "Private" }
],
MaxTitleLength = _pasteSettings.MaxTitleLength,
MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes,
RequiresVerification = _pasteSettings.RequiresVerfication
});
return Ok(
new PasteOptionsDto
{
Syntaxes = [.. _pasteSettings.ValidSyntaxLanguages],
Visibilities =
[
new() { Value = 0, DisplayName = "Public" },
new() { Value = 1, DisplayName = "Unlisted" },
new() { Value = 2, DisplayName = "Private" },
],
MaxTitleLength = _pasteSettings.MaxTitleLength,
MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes,
RequiresVerification = _pasteSettings.RequiresVerification,
}
);
}
}
}
@@ -15,12 +15,10 @@ namespace SharpbinV3.Server.Controllers
[Route("{reportId:int}")]
[HttpGet]
[EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportById(int reportId)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
var user = HttpContext.GetJwtUser()!;
var report = await reportService.GetReportByID(reportId);
if (report is null)
@@ -32,35 +30,35 @@ namespace SharpbinV3.Server.Controllers
var (Username, DisplayName) = await reportService.GetReporterInfo(report.ReporterUUID);
return Ok(new ReportResponseDto
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
ReporterUsername = Username,
ReporterDisplayName = DisplayName,
TargetType = report.TargetType,
PasteId = report.Paste?.ID,
PasteTitle = report.Paste?.Title,
UserUUID = report.UserUUID,
TargetUsername = report.User?.Username,
TargetDisplayName = report.User?.DisplayName
});
return Ok(
new ReportResponseDto
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
ReporterUsername = Username,
ReporterDisplayName = DisplayName,
TargetType = report.TargetType,
PasteId = report.Paste?.ID,
PasteTitle = report.Paste?.Title,
UserUUID = report.UserUUID,
TargetUsername = report.User?.Username,
TargetDisplayName = report.User?.DisplayName,
}
);
}
[Route("{reportId:int}")]
[HttpPatch]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to update reports." });
var user = HttpContext.GetJwtUser()!;
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
@@ -91,24 +89,26 @@ namespace SharpbinV3.Server.Controllers
var updated = await reportService.UpdateReport(report);
var (Username, DisplayName) = await reportService.GetReporterInfo(updated.ReporterUUID);
return Ok(new ReportResponseDto
{
ReportID = updated.ReportID,
Type = updated.Type,
Status = updated.Status,
Description = updated.Description,
CreatedAt = updated.CreatedAt,
UpdatedAt = updated.UpdatedAt,
ReporterUUID = updated.ReporterUUID,
ReporterUsername = Username,
ReporterDisplayName = DisplayName,
TargetType = updated.TargetType,
PasteId = updated.Paste?.ID,
PasteTitle = updated.Paste?.Title,
UserUUID = updated.UserUUID,
TargetUsername = updated.User?.Username,
TargetDisplayName = updated.User?.DisplayName
});
return Ok(
new ReportResponseDto
{
ReportID = updated.ReportID,
Type = updated.Type,
Status = updated.Status,
Description = updated.Description,
CreatedAt = updated.CreatedAt,
UpdatedAt = updated.UpdatedAt,
ReporterUUID = updated.ReporterUUID,
ReporterUsername = Username,
ReporterDisplayName = DisplayName,
TargetType = updated.TargetType,
PasteId = updated.Paste?.ID,
PasteTitle = updated.Paste?.Title,
UserUUID = updated.UserUUID,
TargetUsername = updated.User?.Username,
TargetDisplayName = updated.User?.DisplayName,
}
);
}
[Route("options")]
@@ -123,47 +123,40 @@ namespace SharpbinV3.Server.Controllers
[Route("pastes")]
[HttpGet]
[EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
var user = HttpContext.GetJwtUser()!;
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
var query = request with
{
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100),
UserUUID = null
};
var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null };
var reports = await reportService.GetPasteReports(query);
var totalCount = await reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
return Ok(
new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
});
);
}
[Route("users")]
[HttpGet]
[EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
var user = HttpContext.GetJwtUser()!;
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
@@ -172,40 +165,41 @@ namespace SharpbinV3.Server.Controllers
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100),
PastePID = null,
PasteId = null
PasteId = null,
};
var reports = await reportService.GetUserReports(query);
var totalCount = await reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
return Ok(
new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
});
);
}
[Route("all")]
[HttpGet]
[EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetAllReports(
[FromQuery] Guid? reporterUuid,
[FromQuery] ReportTargetType? targetType,
[FromQuery] ReportType? type,
[FromQuery] ReportStatus? status,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
[FromQuery] int pageSize = 20
)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
var user = HttpContext.GetJwtUser()!;
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
@@ -216,23 +210,25 @@ namespace SharpbinV3.Server.Controllers
Type = type,
Status = status,
Page = Math.Max(page, 1),
PageSize = Math.Clamp(pageSize, 1, 100)
PageSize = Math.Clamp(pageSize, 1, 100),
};
var reports = await reportService.GetReports(query);
var totalCount = await reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
return Ok(
new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
});
);
}
}
}
+130 -139
View File
@@ -19,8 +19,14 @@ namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp,
VerificationService verificationService, ReportService reportServer, IOptions<AuthSettings> authSettings) : ControllerBase
public class UserController(
UserService userService,
AppDbContext db,
TotpVerificationProvider totp,
VerificationService verificationService,
ReportService reportServer,
IOptions<AuthSettings> authSettings
) : ControllerBase
{
private readonly UserService _userService = userService;
private readonly AppDbContext _db = db;
@@ -47,16 +53,13 @@ namespace SharpbinV3.Server.Controllers
[Authorize]
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
{
var userUUID = HttpContext.User?.FindFirst("uuid")?.Value;
if (userUUID is null)
return Unauthorized(new { success = false, message = "Invalid token." });
var userUUID = HttpContext.User.FindFirst("uuid")!.Value;
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
}
[HttpPatch("uuid/{uuid}")]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
{
@@ -64,15 +67,16 @@ namespace SharpbinV3.Server.Controllers
if (!ModelState.IsValid)
return BadRequest(ModelState);
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
if ((user.Roles.Contains(255) && !jwtUser.Roles.Contains(255)) || (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID))
if (
(user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
|| (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID)
)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
@@ -88,11 +92,10 @@ namespace SharpbinV3.Server.Controllers
{
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled)
{
if (string.IsNullOrEmpty(updatedUser.TotpCode) || !await _totp.VerifyAsync(new VerificationContext
{
UserUUID = jwtUser.UUID,
Code = updatedUser.TotpCode
}))
if (
string.IsNullOrEmpty(updatedUser.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = updatedUser.TotpCode })
)
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
@@ -105,13 +108,11 @@ namespace SharpbinV3.Server.Controllers
}
[HttpDelete("uuid/{uuid}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
@@ -124,22 +125,20 @@ namespace SharpbinV3.Server.Controllers
if (jwtUser.TotpEnabled)
{
if (string.IsNullOrEmpty(dto.TotpCode) || !await _totp.VerifyAsync(new VerificationContext
{
UserUUID = jwtUser.UUID,
Code = dto.TotpCode
}))
if (
string.IsNullOrEmpty(dto.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = dto.TotpCode })
)
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
else
{
if (string.IsNullOrEmpty(dto.Token) || !await _verificationService.VerifyAsync(new VerificationContext
{
Token = dto.Token,
Ip = HttpContext.GetRequestIP()
}))
if (
string.IsNullOrEmpty(dto.Token)
|| !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() })
)
{
return Unauthorized(new { message = "Invalid verification token." });
}
@@ -153,12 +152,10 @@ namespace SharpbinV3.Server.Controllers
[HttpPost]
[Route("{uuid}/report")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
{
var reporter = HttpContext.GetJwtUser();
if (reporter == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var reporter = HttpContext.GetJwtUser()!;
var reportedUser = await _userService.GetByUUID(uuid);
if (reportedUser == null)
@@ -169,45 +166,45 @@ namespace SharpbinV3.Server.Controllers
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext
{
Token = request.VerificationToken,
Ip = HttpContext.GetRequestIP()
}))
if (
!await _verificationService.VerifyAsync(
new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
)
)
return Unauthorized(new { success = false, message = "Invalid verification token." });
Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description);
if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while creating the report." });
return Ok(new
{
success = true,
message = "User reported successfully.",
report = new ReportResponseDto
return Ok(
new
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType,
UserUUID = report.UserUUID
success = true,
message = "User reported successfully.",
report = new ReportResponseDto
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType,
UserUUID = report.UserUUID,
},
}
});
);
}
[HttpPatch]
[Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
@@ -231,12 +228,10 @@ namespace SharpbinV3.Server.Controllers
[HttpDelete]
[Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
@@ -254,13 +249,11 @@ namespace SharpbinV3.Server.Controllers
}
[HttpGet]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[Route("{uuid}/reports")]
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
@@ -269,36 +262,31 @@ namespace SharpbinV3.Server.Controllers
if (!jwtUser.Roles.Any(r => r == 1 || r == 255))
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
var query = request with
{
UserUUID = user.UUID,
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100)
};
var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
var reports = await _reportService.GetUserReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
return Ok(
new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
});
);
}
[HttpGet]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[Route("{uuid}/reports/submitted")]
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
@@ -309,28 +297,25 @@ namespace SharpbinV3.Server.Controllers
if (!isOwner && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
var query = request with
{
ReporterUUID = user.UUID,
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100)
};
var query = request with { ReporterUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
var reports = await _reportService.GetReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
return Ok(
new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
});
);
}
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
@@ -369,7 +354,7 @@ namespace SharpbinV3.Server.Controllers
Views = p.Views,
Visibility = p.Visibility,
EditedAt = p.EditedAt,
ExpiresAt = p.ExpiresAt
ExpiresAt = p.ExpiresAt,
})
.ToListAsync();
@@ -378,61 +363,67 @@ namespace SharpbinV3.Server.Controllers
Page = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = totalPages
TotalPages = totalPages,
};
if (isAuthenticatedUser)
{
var reports = await _reportService.GetReports(new ReportQuery
{
ReporterUUID = user.UUID,
Page = page,
PageSize = pageSize
});
var reports = await _reportService.GetReports(
new ReportQuery
{
ReporterUUID = user.UUID,
Page = page,
PageSize = pageSize,
}
);
var reportsCount = await _reportService.GetReportCountByReporter(user.UUID);
return Ok(new
return Ok(
new
{
User = new UserResponseDto
{
UID = user.UID,
Username = user.Username,
UUID = user.UUID,
CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName,
Email = user.Email,
LastLogin = user.LastLogin,
Roles = user.Roles,
Visibility = user.Visibility,
},
Pastes = pastes,
Reports = reports,
Pagination = pagination,
ReportsPagination = new
{
Page = page,
PageSize = pageSize,
TotalCount = reportsCount,
TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize),
},
}
);
}
return Ok(
new
{
User = new UserResponseDto
User = new UserSimpleDto
{
UID = user.UID,
Username = user.Username,
UUID = user.UUID,
CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName,
Email = user.Email,
LastLogin = user.LastLogin,
Roles = user.Roles,
Visibility = user.Visibility
Visibility = user.Visibility,
},
Pastes = pastes,
Reports = reports,
Pagination = pagination,
ReportsPagination = new
{
Page = page,
PageSize = pageSize,
TotalCount = reportsCount,
TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize)
}
});
}
return Ok(new
{
User = new UserSimpleDto
{
UID = user.UID,
Username = user.Username,
UUID = user.UUID,
CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName,
Roles = user.Roles,
Visibility = user.Visibility
},
Pastes = pastes,
Pagination = pagination
});
}
);
}
}
}
@@ -0,0 +1,10 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class ApiKeyListItemDto
{
public required string Name { get; set; }
public required Guid UUID { get; set; }
public required long CreatedAt { get; set; }
public long? LastUsedAt { get; set; }
}
}
@@ -0,0 +1,10 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class ApiKeyResponseDto
{
public required string Key { get; set; }
public required string Name { get; set; }
public required Guid UUID { get; set; }
public required long CreatedAt { get; set; }
}
}
@@ -0,0 +1,7 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class CreateApiKeyRequest
{
public required string Name { get; set; }
}
}
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Auth
{
[Required]
public required string Token { get; set; }
[Required]
public required string RefreshToken { get; set; }
}
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Auth
{
[JsonPropertyName("success")]
public bool Success { get; set; }
[JsonPropertyName("error-codes")]
public string[]? ErrorCodes { get; set; }
}
+2 -1
View File
@@ -7,8 +7,9 @@ namespace SharpbinV3.Server.DTOs.Report
[Required]
[MinLength(12), MaxLength(1000)]
public string Description { get; set; } = string.Empty;
[Required]
public string ReportType { get; set; } = string.Empty; // e.g., "Spam", "Abuse", etc.
public string ReportType { get; set; } = string.Empty;
public string ReportStatus { get; set; } = "Open";
public string? VerificationToken { get; set; }
}
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Report
{
public string? Status { get; set; }
public string? Type { get; set; }
[MaxLength(1000)]
public string? Description { get; set; }
}
@@ -7,6 +7,7 @@ namespace SharpbinV3.Server.DTOs.User
[StringLength(50, MinimumLength = 3)]
public string? Username { get; set; }
public string? Email { get; set; }
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
public string? Token { get; set; }
+19 -5
View File
@@ -24,16 +24,26 @@ namespace SharpbinV3.Server.DTOs
if (!ValidateUsername().IsMatch(Username))
results.Add(new ValidationResult("Username can only contain letters, numbers, underscores, and dots.", [nameof(Username)]));
if (!ValidatePassword().IsMatch(Password))
results.Add(new ValidationResult("Password should have at least 8 characters, including uppercase, lowercase, and digits.", [nameof(Password)]));
results.Add(
new ValidationResult(
"Password should have at least 8 characters, including uppercase, lowercase, and digits.",
[nameof(Password)]
)
);
if (DisplayName != null)
if (DisplayName != null && DisplayName.Length > 0)
{
if (DisplayName.Length < 3 || DisplayName.Length > 26)
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)]));
if (!ValidateUsername().IsMatch(DisplayName))
results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)]));
if (!ValidateDisplayname().IsMatch(DisplayName))
results.Add(
new ValidationResult(
"DisplayName can only contain alphanumeric characters, underscores, periods, and spaces (no leading or trailing spaces).",
[nameof(DisplayName)]
)
);
}
if (Email != null)
if (Email != null && Email.Length > 0)
{
var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(Email))
@@ -44,6 +54,10 @@ namespace SharpbinV3.Server.DTOs
[GeneratedRegex("^[A-Za-z0-9_.]+$")]
private static partial Regex ValidateUsername();
[GeneratedRegex("^[A-Za-z0-9_.]+(?: [A-Za-z0-9_.]+)*$")]
private static partial Regex ValidateDisplayname();
[GeneratedRegex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")]
public static partial Regex ValidatePassword();
}
+11 -7
View File
@@ -14,25 +14,30 @@ namespace SharpbinV3.Server.DTOs
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (DisplayName != null)
if (DisplayName != null && DisplayName.Length > 0)
{
if (DisplayName.Length < 3 || DisplayName.Length > 26)
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)]));
if (!ValidateDisplayname().IsMatch(DisplayName))
results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)]));
results.Add(
new ValidationResult(
"DisplayName can only contain alphanumeric characters, underscores, periods, and spaces (no leading or trailing spaces).",
[nameof(DisplayName)]
)
);
}
if (Email != null)
if (Email != null && Email.Length > 0)
{
var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(Email))
results.Add(new ValidationResult("Invalid email format.", [nameof(Email)]));
}
if (Visibility != null)
if (Visibility != null && Visibility.HasValue)
{
if (Visibility < 0 || Visibility > 2)
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)]));
}
if (Roles != null)
if (Roles != null && Roles.Length > 0)
{
if (Roles.Length == 0)
results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)]));
@@ -42,12 +47,11 @@ namespace SharpbinV3.Server.DTOs
if (!validRoles.Contains(role))
results.Add(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)]));
}
}
return results;
}
[GeneratedRegex("^[A-Za-z0-9_.]+$")]
[GeneratedRegex("^[A-Za-z0-9_.]+(?: [A-Za-z0-9_.]+)*$")]
private static partial Regex ValidateDisplayname();
}
}
+7
View File
@@ -11,6 +11,7 @@ namespace SharpbinV3.Server.Data
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
public DbSet<Report> Reports => Set<Report>();
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -56,6 +57,12 @@ namespace SharpbinV3.Server.Data
.WithMany(u => u.Reports)
.HasForeignKey(r => r.UserUUID)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<ApiKey>()
.HasOne(a => a.User)
.WithMany(u => u.ApiKeys)
.HasForeignKey(a => a.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
}
}
}
+16
View File
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
public sealed class ApiKey
{
[Key]
public Guid UUID { get; set; } = Guid.CreateVersion7();
public required Guid UserUUID { get; set; }
public User? User { get; set; }
public required string KeyHash { get; set; }
public required string Name { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public long? LastUsedAt { get; set; }
}
}
+1 -5
View File
@@ -36,16 +36,12 @@ namespace SharpbinV3.Server.Data.Entities
public enum ReportStatus
{
Open,
InProgress,
Resolved,
Closed
}
public enum ReportType
{
Spam,
Abuse,
InappropriateContent,
CopyrightViolation,
IllegalContent,
Fraud,
Other
}
+1
View File
@@ -23,6 +23,7 @@ namespace SharpbinV3.Server.Data.Entities
public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = [];
public List<Report> Reports { get; set; } = [];
public List<ApiKey> ApiKeys { get; set; } = [];
public UserTotp? Totp { get; set; }
}
}
@@ -1,20 +1,54 @@
using SharpbinV3.Server.Services;
using System.IdentityModel.Tokens.Jwt;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Extensions
{
public static class HttpContextExtensions
{
public readonly static string[] ipHeaders =
public static readonly string[] ipHeaders =
[
"X-Forwarded-For",
"X-Real-IP",
"CF-Connecting-IP",
"True-Client-IP",
"X-Cluster-Client-IP",
"X-ProxyUser-IP"
"X-ProxyUser-IP",
];
private const string ApiKeyContextKey = "ApiKey";
public static string? GetApiKey(this HttpContext context)
{
var apiKeyHeader = context.Request.Headers["X-API-Key"].FirstOrDefault();
if (string.IsNullOrEmpty(apiKeyHeader))
return null;
if (apiKeyHeader.Length != ApiKeyService.KeyLength)
return null;
return apiKeyHeader;
}
public static ApiKey? GetApiKeyFromContext(this HttpContext context)
{
if (context.Items.TryGetValue(ApiKeyContextKey, out var apiKey))
return apiKey as ApiKey;
return null;
}
public static void SetApiKeyContext(this HttpContext context, ApiKey apiKey)
{
context.Items[ApiKeyContextKey] = apiKey;
}
public static bool IsApiKeyAuthenticated(this HttpContext context)
{
return context.GetApiKeyFromContext() != null;
}
public static JwtUser? GetJwtUser(this HttpContext context)
{
if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
@@ -30,15 +64,13 @@ namespace SharpbinV3.Server.Extensions
var displayName = claims.FirstOrDefault(c => c.Type == "displayname")?.Value ?? "";
var totpEnabled = claims.FirstOrDefault(c => c.Type == "totp_enabled")?.Value == "True";
var roles = claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.TryParse(c.Value, out var r) ? r : 0)
.ToArray();
var roles = claims.Where(c => c.Type == ClaimTypes.Role).Select(c => int.TryParse(c.Value, out var r) ? r : 0).ToArray();
var expClaim = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value;
var expires = expClaim != null && long.TryParse(expClaim, out var expUnix)
? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime
: DateTime.UtcNow.AddMinutes(15);
var expires =
expClaim != null && long.TryParse(expClaim, out var expUnix)
? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime
: DateTime.UtcNow.AddMinutes(15);
return new JwtUser
{
@@ -47,7 +79,7 @@ namespace SharpbinV3.Server.Extensions
DisplayName = displayName,
TotpEnabled = totpEnabled,
Roles = roles.Length > 0 ? roles : [0],
Expires = expires
Expires = expires,
};
}
@@ -0,0 +1,26 @@
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Middleware
{
public sealed class ApiKeyAuthenticationMiddleware(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public async Task InvokeAsync(HttpContext context, ApiKeyService apiKeyService)
{
var apiKeyString = context.GetApiKey();
if (!string.IsNullOrEmpty(apiKeyString))
{
var apiKey = await apiKeyService.GetByKeyAsync(apiKeyString);
if (apiKey != null)
{
context.SetApiKeyContext(apiKey);
await apiKeyService.UpdateLastUsedAsync(apiKey.UUID);
}
}
await _next(context);
}
}
}
@@ -0,0 +1,405 @@
// <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("20260210231315_AddApiKeys")]
partial class AddApiKeys
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
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>("CreatedAt")
.HasColumnType("INTEGER");
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("Size");
b.HasIndex("Syntax");
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>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<int?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
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.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
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.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
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");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,49 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class AddApiKeys : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ApiKeys",
columns: table => new
{
UUID = table.Column<Guid>(type: "TEXT", nullable: false),
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
KeyHash = table.Column<string>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
LastUsedAt = table.Column<long>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ApiKeys", x => x.UUID);
table.ForeignKey(
name: "FK_ApiKeys_Users_UserUUID",
column: x => x.UserUUID,
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ApiKeys_UserUUID",
table: "ApiKeys",
column: "UserUUID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ApiKeys");
}
}
}
@@ -17,6 +17,36 @@ namespace SharpbinV3.Server.Migrations
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
@@ -276,6 +306,17 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
@@ -345,6 +386,8 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
+242 -125
View File
@@ -1,9 +1,15 @@
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using SharpbinV3.Server.Authentication;
using SharpbinV3.Server.Authorization;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Extensions;
@@ -11,9 +17,6 @@ using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
using SharpbinV3.Server.Settings;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
namespace SharpbinV3.Server
{
@@ -25,14 +28,39 @@ namespace SharpbinV3.Server
// Add services to the container.
builder.Services.AddControllers()
builder
.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer(
(document, context, cancellationToken) =>
{
document?.Components ??= new();
document?.Servers?.Clear();
document?.Components?.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
document
?.Components
?.SecuritySchemes
?["ApiKey"] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
Name = "X-API-Key",
In = ParameterLocation.Header,
Description = "Bypass authentication and captcha by providing a valid API key.",
};
return Task.CompletedTask;
}
);
});
builder.Services.AddDbContext<AppDbContext>(opt =>
{
opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
@@ -43,101 +71,164 @@ namespace SharpbinV3.Server
builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<PasteService>();
builder.Services.AddScoped<ApiKeyService>();
builder.Services.AddScoped<VerificationService>();
builder.Services.AddScoped<TotpVerificationProvider>();
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
builder.Services.AddScoped<ReportService>();
builder.Services.AddMemoryCache();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>("Database");
builder.Services.AddHealthChecks().AddDbContextCheck<AppDbContext>("Database");
builder.Services.AddOptions<PasteSettings>()
builder
.Services.AddOptions<PasteSettings>()
.Bind(builder.Configuration.GetSection("PasteSettings"))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.AddOptions<JWTSettings>()
builder
.Services.AddOptions<JWTSettings>()
.Bind(builder.Configuration.GetSection("JwtSettings"))
.ValidateDataAnnotations()
.ValidateOnStart();
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer();
builder.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<JWTSettings>>((options, jwtSettings) =>
builder
.Services.AddAuthentication(options =>
{
var settings = jwtSettings.Value;
var key = Encoding.UTF8.GetBytes(settings.Secret);
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
options.DefaultAuthenticateScheme = AuthSchemes.Combined;
options.DefaultScheme = AuthSchemes.Combined;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddPolicyScheme(
AuthSchemes.Combined,
AuthSchemes.Combined,
options =>
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
options.ForwardDefaultSelector = context =>
{
var apiKeyHeader = context.Request.Headers["X-API-Key"].ToString();
if (!string.IsNullOrEmpty(apiKeyHeader))
return AuthSchemes.ApiKey;
ValidateIssuer = true,
ValidIssuer = settings.Issuer,
var authHeader = context.Request.Headers.Authorization.ToString();
if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
return JwtBearerDefaults.AuthenticationScheme;
ValidateAudience = true,
ValidAudience = settings.Audience,
return JwtBearerDefaults.AuthenticationScheme;
};
}
)
.AddJwtBearer()
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(AuthSchemes.ApiKey, _ => { });
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
builder
.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<JWTSettings>>(
(options, jwtSettings) =>
{
var settings = jwtSettings.Value;
var key = Encoding.UTF8.GetBytes(settings.Secret);
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
};
});
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
builder.Services.AddAuthorizationBuilder()
.AddPolicy("NotBanned", policy =>
policy.Requirements.Add(new NotBannedRequirement()));
builder.Services.AddAuthorizationBuilder()
.AddPolicy("AuthAndNotBanned", policy =>
policy.Requirements.Add(new NotBannedRequirement()));
ValidateIssuer = true,
ValidIssuer = settings.Issuer,
ValidateAudience = true,
ValidAudience = settings.Audience,
RequireExpirationTime = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
};
}
);
builder.Services.AddAuthorizationBuilder().AddPolicy("NotBanned", policy => policy.Requirements.Add(new NotBannedRequirement()));
builder.Services.AddAuthorizationBuilder().AddPolicy("AuthAndNotBanned", policy => policy.Requirements.Add(new NotBannedRequirement()));
builder
.Services.AddAuthorizationBuilder()
.AddPolicy(
"JwtOnly",
policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
}
);
builder
.Services.AddAuthorizationBuilder()
.AddPolicy(
"JwtOnlyAndNotBanned",
policy =>
{
policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
policy.RequireAuthenticatedUser();
policy.Requirements.Add(new NotBannedRequirement());
}
);
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(false));
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true));
builder.Services.AddRateLimiter(options =>
{
options.AddPolicy("Sliding", httpContext =>
RateLimitPartition.GetSlidingWindowLimiter(httpContext.GetRequestIP(), _ => new SlidingWindowRateLimiterOptions
{
Window = TimeSpan.FromSeconds(10),
PermitLimit = 10,
QueueLimit = 2,
SegmentsPerWindow = 5,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
options.AddPolicy(
"Sliding",
httpContext =>
RateLimitPartition.GetSlidingWindowLimiter(
httpContext.GetRequestIP(),
_ => new SlidingWindowRateLimiterOptions
{
Window = TimeSpan.FromSeconds(10),
PermitLimit = 10,
QueueLimit = 2,
SegmentsPerWindow = 5,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
)
);
options.AddPolicy("Strict", httpContext =>
RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 5,
QueueLimit = 0,
TokensPerPeriod = 1,
ReplenishmentPeriod = TimeSpan.FromSeconds(30),
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
options.AddPolicy(
"Strict",
httpContext =>
RateLimitPartition.GetTokenBucketLimiter(
httpContext.GetRequestIP(),
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 5,
QueueLimit = 0,
TokensPerPeriod = 1,
ReplenishmentPeriod = TimeSpan.FromSeconds(30),
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
)
);
options.AddPolicy("Sensitive", httpContext =>
RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions
{
TokenLimit = 3,
QueueLimit = 0,
TokensPerPeriod = 1,
ReplenishmentPeriod = TimeSpan.FromMinutes(1),
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
));
options.AddPolicy(
"Sensitive",
httpContext =>
RateLimitPartition.GetTokenBucketLimiter(
httpContext.GetRequestIP(),
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 3,
QueueLimit = 0,
TokensPerPeriod = 1,
ReplenishmentPeriod = TimeSpan.FromMinutes(1),
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
)
);
options.AddPolicy("NoLimit", _ => RateLimitPartition.GetNoLimiter(0));
@@ -145,53 +236,52 @@ namespace SharpbinV3.Server
{
var remoteIp = httpContext.GetRequestIP();
return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0
});
return RateLimitPartition.GetFixedWindowLimiter(
remoteIp,
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
}
);
});
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) =>
{
await context.HttpContext.Response.WriteAsJsonAsync(new
{
success = false,
Message = "Too many requests. Please try again later."
}, cancellationToken: cancellationToken);
await context.HttpContext.Response.WriteAsJsonAsync(
new { success = false, Message = "Too many requests. Please try again later." },
cancellationToken: cancellationToken
);
};
});
builder.Services.AddOutputCache(options =>
{
options.AddPolicy("1Day", builder =>
{
builder.Expire(TimeSpan.FromDays(1));
});
options.AddPolicy(
"1Day",
builder =>
{
builder.Expire(TimeSpan.FromDays(1));
}
);
});
builder.Services.AddCors(o =>
{
o.AddDefaultPolicy(p =>
p.WithOrigins("http://localhost:5173")
.AllowAnyHeader()
.AllowAnyMethod());
o.AddDefaultPolicy(p => p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod());
});
builder.Services.AddDataProtection()
builder
.Services.AddDataProtection()
.PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment))
.SetApplicationName("SharpbinV3");
var app = builder.Build();
app.UseRateLimiter();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.MapOpenApi();
app.UseHttpsRedirection();
app.UseCors();
@@ -209,7 +299,8 @@ namespace SharpbinV3.Server
db.Database.Migrate();
// this is temporary since the migration doesnt seem to work properly
db.Database.ExecuteSql($"""
db.Database.ExecuteSql(
$"""
CREATE TRIGGER IF NOT EXISTS Users_UID_AutoIncrement
AFTER INSERT ON Users
BEGIN
@@ -219,49 +310,75 @@ namespace SharpbinV3.Server
)
WHERE rowid = NEW.rowid AND NEW.UID IS NULL;
END;
""");
"""
);
}
app.MapHealthChecks("/health");
app.MapGet("/api/stats", async (AppDbContext db) =>
{
var pasteCount = await db.Pastes.CountAsync();
var userCount = await db.Users.CountAsync();
var totalPasteSize = await db.Pastes.SumAsync(p => p.Size);
var pastSevenDays = DateTimeOffset.UtcNow.AddDays(-7).ToUnixTimeMilliseconds();
var pasteCountWeek = await db.Pastes.CountAsync(p => p.CreatedAt >= pastSevenDays);
return Results.Ok(new
{
success = true,
stats = new
app.MapGet(
"/api/stats",
async (AppDbContext db) =>
{
pastes = new
var now = DateTimeOffset.UtcNow;
var todayStart = new DateTimeOffset(now.Year, now.Month, now.Day, 0, 0, 0, TimeSpan.Zero);
var sevenDaysAgo = todayStart.AddDays(-6).ToUnixTimeMilliseconds();
var pasteCount = await db.Pastes.CountAsync();
var userCount = await db.Users.CountAsync();
var totalPasteSize = await db.Pastes.SumAsync(p => p.Size);
var trueTotalPasteSize = await db.Pastes.SumAsync(p => p.TrueSize);
var dailyCounts = await db
.Pastes.Where(p => p.CreatedAt >= sevenDaysAgo)
.GroupBy(p => p.CreatedAt / 86400000)
.Select(g => new { Day = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.Day, x => x.Count);
var dailyStats = new List<object>();
var pasteCountWeek = 0;
for (int i = 6; i >= 0; i--)
{
total = pasteCount,
past7Days = pasteCountWeek,
totalSizeInBytes = totalPasteSize
},
users = new
{
total = userCount
},
var dayTs = todayStart.AddDays(-i).ToUnixTimeMilliseconds();
dailyCounts.TryGetValue(dayTs / 86400000, out var count);
dailyStats.Add(new { date = dayTs, count });
pasteCountWeek += count;
}
return Results.Ok(
new
{
success = true,
stats = new
{
pastes = new
{
total = pasteCount,
past7Days = pasteCountWeek,
totalSizeInBytes = totalPasteSize,
trueTotalSizeInBytes = trueTotalPasteSize,
daily = dailyStats,
},
users = new { total = userCount },
},
}
);
}
});
}).CacheOutput(policy => policy.Expire(TimeSpan.FromDays(1)).Tag("stats"));
)
.CacheOutput(policy => policy.Expire(TimeSpan.FromHours(6)).Tag("stats"));
app.Run();
}
static DirectoryInfo GetDataProtectionKeyDirectory(IHostEnvironment env)
{
var overridepath = Environment.GetEnvironmentVariable("DATA_PROTECTION_KEY_PATH");
if (!string.IsNullOrEmpty(overridepath))
return new DirectoryInfo(overridepath);
var basePath = env.IsDevelopment()
? Environment.CurrentDirectory
: Environment.SpecialFolder.ApplicationData.ToString();
var basePath = env.IsDevelopment() ? Environment.CurrentDirectory : Environment.SpecialFolder.ApplicationData.ToString();
var path = Path.Combine(basePath, "SharpbinV3", "DataProtectionKeys");
+1 -19
View File
@@ -15,15 +15,6 @@ The server configuration is managed in `appsettings.json`. For development, ensu
- `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=/app/data/sharpbin.db`).
- `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.
@@ -43,13 +34,4 @@ Use the following command to run the server with hot reload:
dotnet watch run
```
The API will be accessible at http://localhost:8080 by default (check `Properties/launchSettings.json` or your specific configuration).
## Tech Stack
- ASP.NET Core (Web API)
- Entity Framework Core with SQLite
- JWT Authentication
- BCrypt for password hashing
- Health Checks for monitoring
- Swagger/OpenAPI for documentation
The API will be accessible at http://localhost:5050 by default (check `Properties/launchSettings.json` or your specific configuration).
@@ -0,0 +1,74 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Services
{
public sealed class ApiKeyService(AppDbContext db, IOptions<AuthSettings> authOptions)
{
private readonly AppDbContext _db = db;
private readonly AuthSettings _authSettings = authOptions.Value;
public const int KeyLength = 64;
private string ComputeHash(string input)
{
if (string.IsNullOrEmpty(_authSettings.API_Key_HMAC_Secret))
return Utilities.ComputeSha256(input);
else
return Utilities.ComputeHmacSha256(input, _authSettings.API_Key_HMAC_Secret);
}
public async Task<ApiKey?> GetByKeyAsync(string key)
{
var keyHash = ComputeHash(key);
return await _db.ApiKeys.Include(a => a.User).FirstOrDefaultAsync(a => a.KeyHash == keyHash);
}
public async Task<(ApiKey apiKey, string key)> CreateAsync(Guid userUUID, string name)
{
var key = Utilities.GenerateSecureRandomString(KeyLength);
var keyHash = ComputeHash(key);
var apiKey = new ApiKey
{
UserUUID = userUUID,
Name = name,
KeyHash = keyHash,
};
_db.ApiKeys.Add(apiKey);
await _db.SaveChangesAsync();
return (apiKey, key);
}
public async Task<bool> DeleteAsync(Guid userUUID, Guid keyUUID)
{
var apiKey = await _db.ApiKeys.FirstOrDefaultAsync(a => a.UUID == keyUUID && a.UserUUID == userUUID);
if (apiKey == null)
return false;
_db.ApiKeys.Remove(apiKey);
await _db.SaveChangesAsync();
return true;
}
public async Task<List<ApiKey>> GetUserKeysAsync(Guid userUUID)
{
return await _db.ApiKeys.Where(a => a.UserUUID == userUUID).OrderByDescending(a => a.CreatedAt).ToListAsync();
}
public async Task UpdateLastUsedAsync(Guid keyUUID)
{
var apiKey = await _db.ApiKeys.FirstOrDefaultAsync(a => a.UUID == keyUUID);
if (apiKey == null)
return;
apiKey.LastUsedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
await _db.SaveChangesAsync();
}
}
}
+47 -37
View File
@@ -1,13 +1,14 @@
using Microsoft.EntityFrameworkCore;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Settings;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.Services
@@ -21,7 +22,13 @@ namespace SharpbinV3.Server.Services
public int[] Roles { get; set; } = [];
public DateTime Expires { get; set; }
}
public sealed class AuthService(AppDbContext db, IOptions<JWTSettings> jwtOptions, IOptions<AuthSettings> authOptions, ILogger<AuthService> logger)
public sealed class AuthService(
AppDbContext db,
IOptions<JWTSettings> jwtOptions,
IOptions<AuthSettings> authOptions,
ILogger<AuthService> logger
)
{
private readonly AppDbContext _db = db;
private readonly JWTSettings _jwtSettings = jwtOptions.Value;
@@ -36,7 +43,7 @@ namespace SharpbinV3.Server.Services
PasswordHash = Bcrypt.HashPassword(password),
Email = email,
DisplayName = displayName,
UUID = Guid.CreateVersion7()
UUID = Guid.CreateVersion7(),
};
if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync())
@@ -46,6 +53,7 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
return user;
}
public async Task<CreateJWT> GenerateJWTToken(User user)
{
var jwtHandler = new JwtSecurityTokenHandler();
@@ -58,7 +66,7 @@ namespace SharpbinV3.Server.Services
new("username", user.Username),
new("displayname", user.DisplayName ?? ""),
new("totp_enabled", totpEnabled.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
if (user.Roles != null)
@@ -77,17 +85,14 @@ namespace SharpbinV3.Server.Services
Issuer = _jwtSettings.Issuer,
Audience = _jwtSettings.Audience,
Expires = DateTime.UtcNow.AddMinutes(15),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature
)
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
};
var token = jwtHandler.CreateToken(descriptor);
var jwtToken = jwtHandler.WriteToken(token);
var jti = claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value;
var rawRefreshToken = Utilities.GenerateRandomString(36) + Guid.NewGuid();
var rawRefreshToken = Utilities.GenerateSecureRandomString(36) + Guid.NewGuid();
var refreshToken = new RefreshToken
{
Id = Guid.NewGuid(),
@@ -97,7 +102,7 @@ namespace SharpbinV3.Server.Services
CreatedAt = DateTimeOffset.UtcNow,
ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6),
Used = false,
Revoked = false
Revoked = false,
};
await _db.RefreshTokens.AddAsync(refreshToken);
@@ -107,7 +112,7 @@ namespace SharpbinV3.Server.Services
{
Token = jwtToken,
Success = true,
RefreshToken = rawRefreshToken
RefreshToken = rawRefreshToken,
};
}
@@ -118,38 +123,39 @@ namespace SharpbinV3.Server.Services
try
{
var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = _jwtSettings.Issuer,
ValidateAudience = true,
ValidAudience = _jwtSettings.Audience,
ClockSkew = TimeSpan.Zero,
ValidateLifetime = false,
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
}, out SecurityToken validatedToken);
var principal = jwtHandler.ValidateToken(
token,
new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = _jwtSettings.Issuer,
ValidateAudience = true,
ValidAudience = _jwtSettings.Audience,
ClockSkew = TimeSpan.Zero,
ValidateLifetime = false,
RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
},
out SecurityToken validatedToken
);
var jti = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value;
var tokenHash = Utilities.ComputeSha256(refreshToken);
var storedToken = await _db.RefreshTokens
.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash);
var storedToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash);
if (storedToken == null
if (
storedToken == null
|| storedToken.Used
|| storedToken.Revoked
|| storedToken.ExpiresAt < DateTimeOffset.UtcNow
|| storedToken.JwtId != jti)
|| storedToken.JwtId != jti
)
{
return new CreateJWT
{
Success = false,
Errors = ["Invalid or expired refresh token."]
};
return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] };
}
storedToken.Used = true;
@@ -172,7 +178,6 @@ namespace SharpbinV3.Server.Services
}
}
public async Task<User> UpdateUser(User user)
{
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
@@ -186,6 +191,7 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
return user;
}
public async Task UpdateLoginTime(User user)
{
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
@@ -196,6 +202,10 @@ namespace SharpbinV3.Server.Services
public async Task<User?> GetUserFromHttpContext(HttpContext context)
{
var apiKey = context.GetApiKeyFromContext();
if (apiKey != null)
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == apiKey.UserUUID);
var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "uuid")?.Value;
if (uuidClaim == null)
return null;
@@ -1,6 +1,5 @@
using System.IO.Compression;
namespace SharpbinV3.Server.Services
{
public class CompressionService : ICompressionService
@@ -21,11 +20,13 @@ namespace SharpbinV3.Server.Services
return data;
}
public byte[] Compress(string data)
{
ArgumentNullException.ThrowIfNull(data);
return Compress(System.Text.Encoding.UTF8.GetBytes(data));
}
public byte[] Decompress(byte[] compressedData)
{
ArgumentNullException.ThrowIfNull(compressedData);
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.Services
public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger<PasteCleanUpService> logger) : BackgroundService
{
private readonly TimeSpan _period = TimeSpan.FromMinutes(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(_period);
+8 -33
View File
@@ -9,12 +9,7 @@ using SharpbinV3.Server.Settings;
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, IMemoryCache cache, IOptions<PasteSettings> options)
{
private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs;
@@ -40,7 +35,7 @@ namespace SharpbinV3.Server.Services
var paste = new Paste
{
UUID = Guid.CreateVersion7(),
ID = Utilities.GenerateRandomString(8),
ID = Utilities.GenerateSecureRandomString(8),
Title = title,
AuthorUUID = author?.UUID,
User = author,
@@ -114,10 +109,7 @@ namespace SharpbinV3.Server.Services
return result > 0;
}
public async Task<(Paste? paste, bool alreadyExists)> RecordView(
Paste paste,
HttpContext context
)
public async Task<(Paste? paste, bool alreadyExists)> RecordView(Paste paste, HttpContext context)
{
if (paste == null)
return (null, false);
@@ -132,21 +124,11 @@ namespace SharpbinV3.Server.Services
string viewerHash;
if (viewerUser != null)
viewerHash = Utilities.ComputeHmacSha256(
_pasteSettings.View_HMAC_Secret,
viewerUser.UUID.ToString()
);
viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerUser.UUID.ToString());
else
viewerHash = Utilities.ComputeHmacSha256(
_pasteSettings.View_HMAC_Secret,
viewerIp + viewerUserAgent
);
viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerIp + viewerUserAgent);
if (
await _db.PasteViews.AnyAsync(pv =>
pv.PastePID == paste.PID && pv.ViewerHash == viewerHash
)
)
if (await _db.PasteViews.AnyAsync(pv => pv.PastePID == paste.PID && pv.ViewerHash == viewerHash))
return (null, true);
_db.PasteViews.Add(
@@ -176,9 +158,7 @@ namespace SharpbinV3.Server.Services
async entry =>
{
entry.SetSlidingExpiration(TimeSpan.FromMinutes(10));
return await _db
.Pastes.Include(p => p.User)
.FirstOrDefaultAsync(p => p.ID == id);
return await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
}
);
return paste ?? null;
@@ -201,12 +181,7 @@ namespace SharpbinV3.Server.Services
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 await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync();
}
);
@@ -3,21 +3,16 @@ using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services
{
public sealed class PasteViewCleanUpService(
IServiceProvider serviceProvider,
ILogger<PasteViewCleanUpService> logger
) : BackgroundService
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;
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))
while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
@@ -35,16 +30,12 @@ namespace SharpbinV3.Server.Services
using var scope = serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var cutoff =
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - RetentionMs;
var cutoff = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - RetentionMs;
var deleted = await db.PasteViews
.Where(v => v.ViewedAt < cutoff)
.ExecuteDeleteAsync(token);
var deleted = await db.PasteViews.Where(v => v.ViewedAt < cutoff).ExecuteDeleteAsync(token);
if (deleted > 0)
logger.LogInformation("Deleted {Count} stale paste views", deleted);
}
}
}
+17 -39
View File
@@ -8,7 +8,9 @@ namespace SharpbinV3.Server.Services
public class ReportService(AppDbContext db)
{
private readonly AppDbContext _db = db;
private sealed record UserInfo(string Username, string? DisplayName);
public async Task<Report> CreateReport(Guid reporterUUID, ReportTargetType targetType, Guid userUUID, ReportType type, string description)
{
var report = new Report
@@ -17,12 +19,13 @@ namespace SharpbinV3.Server.Services
TargetType = targetType,
UserUUID = userUUID,
Type = type,
Description = description
Description = description,
};
await _db.Reports.AddAsync(report);
await _db.SaveChangesAsync();
return report;
}
public async Task<Report> CreateReport(Guid reporterUUID, ReportTargetType targetType, int? pastePID, ReportType type, string description)
{
var report = new Report
@@ -53,10 +56,7 @@ namespace SharpbinV3.Server.Services
if (query.PasteId != null)
{
q = q.Where(r => _db.Pastes
.Where(p => p.ID == query.PasteId)
.Select(p => (int?)p.PID)
.Contains(r.PastePID));
q = q.Where(r => _db.Pastes.Where(p => p.ID == query.PasteId).Select(p => (int?)p.PID).Contains(r.PastePID));
}
if (query.TargetType != null)
@@ -71,25 +71,16 @@ namespace SharpbinV3.Server.Services
return q;
}
public async Task<List<ReportResponseDto>> GetPasteReports(ReportQuery query)
{
query = query with
{
TargetType = ReportTargetType.Paste,
UserUUID = null
};
query = query with { TargetType = ReportTargetType.Paste, UserUUID = null };
return await GetReports(query);
}
public async Task<List<ReportResponseDto>> GetUserReports(ReportQuery query)
{
query = query with
{
TargetType = ReportTargetType.User,
PastePID = null
};
query = query with { TargetType = ReportTargetType.User, PastePID = null };
return await GetReports(query);
}
@@ -109,27 +100,22 @@ namespace SharpbinV3.Server.Services
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(),
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
TargetDisplayName = r.User != null ? r.User.DisplayName : null,
})
.ToListAsync();
}
public async Task<(string? Username, string? DisplayName)> GetReporterInfo(Guid reporterUUID)
{
var info = await _db.Users.AsNoTracking()
var info = await _db
.Users.AsNoTracking()
.Where(u => u.UUID == reporterUUID)
.Select(u => new UserInfo(u.Username, u.DisplayName))
.FirstOrDefaultAsync();
@@ -137,25 +123,19 @@ namespace SharpbinV3.Server.Services
return info is null ? (null, null) : (info.Username, info.DisplayName);
}
public async Task<int> GetReportCount(ReportTargetType targetType)
{
return await _db.Reports
.Where(r => r.TargetType == targetType)
.CountAsync();
return await _db.Reports.Where(r => r.TargetType == targetType).CountAsync();
}
public async Task<int> GetReportCountByReporter(Guid reporterUUID)
{
return await _db.Reports
.Where(r => r.ReporterUUID == reporterUUID)
.CountAsync();
return await _db.Reports.Where(r => r.ReporterUUID == reporterUUID).CountAsync();
}
public async Task<int> GetReportCount()
{
return await _db.Reports
.CountAsync();
return await _db.Reports.CountAsync();
}
public async Task<int> GetReportCount(ReportQuery query)
@@ -165,10 +145,7 @@ namespace SharpbinV3.Server.Services
public async Task<Report?> GetReportByID(int reportID)
{
return await _db.Reports
.Include(r => r.User)
.Include(r => r.Paste)
.FirstOrDefaultAsync(r => r.ReportID == reportID);
return await _db.Reports.Include(r => r.User).Include(r => r.Paste).FirstOrDefaultAsync(r => r.ReportID == reportID);
}
public async Task<Report> UpdateReport(Report report)
@@ -177,6 +154,7 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
return report;
}
public async Task<bool> DeleteReport(Report report)
{
_db.Reports.Remove(report);
+1 -1
View File
@@ -2,12 +2,12 @@
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
namespace SharpbinV3.Server.Services
{
public sealed class UserService(AppDbContext db)
{
private readonly AppDbContext _db = db;
public Task<User?> GetByUID(int uid, bool withPastes = false)
{
IQueryable<User> query = _db.Users;
@@ -6,7 +6,8 @@ using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services.Verification.Providers
{
public sealed class TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache) : IVerificationProvider
public sealed class TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache)
: IVerificationProvider
{
private readonly AppDbContext _db = db;
private readonly IDataProtector _protector = dataProtectionProvider.CreateProtector("TotpSecret-v1");
@@ -17,11 +18,14 @@ namespace SharpbinV3.Server.Services.Verification.Providers
public async Task<bool> VerifyAsync(VerificationContext ctx)
{
if (ctx.UserUUID is null) return false;
if (string.IsNullOrWhiteSpace(ctx.Code)) return false;
if (ctx.UserUUID is null)
return false;
if (string.IsNullOrWhiteSpace(ctx.Code))
return false;
var userTotp = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == ctx.UserUUID.Value);
if (userTotp is null) return false;
if (userTotp is null)
return false;
var secret = _protector.Unprotect(userTotp.EncryptedSecret);
if (!VerifyCode(secret, ctx.Code, out var step))
@@ -39,7 +43,14 @@ namespace SharpbinV3.Server.Services.Verification.Providers
public byte[] FromBase32(string base32) => string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32);
public string BuildOtpAuthUri(string issuer, string accountName, string secretBase32, int digits = 6, int period = 30, string algorithm = "SHA1")
public string BuildOtpAuthUri(
string issuer,
string accountName,
string secretBase32,
int digits = 6,
int period = 30,
string algorithm = "SHA1"
)
{
var label = Uri.EscapeDataString($"{issuer}:{accountName}");
var query = $"secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm={algorithm}&digits={digits}&period={period}";
@@ -47,6 +58,7 @@ namespace SharpbinV3.Server.Services.Verification.Providers
}
public byte[] Protect(byte[] secret) => _protector.Protect(secret);
public byte[] Unprotect(byte[] protectedSecret) => _protector.Unprotect(protectedSecret);
public bool VerifyWithSecretBase32(string secretBase32, string code, int digits = 6, int period = 30, int window = 1)
@@ -1,7 +1,7 @@
using Microsoft.Extensions.Options;
using System.Text.Json;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Settings;
using System.Text.Json;
namespace SharpbinV3.Server.Services.Verification.Providers
{
@@ -11,7 +11,8 @@ namespace SharpbinV3.Server.Services.Verification.Providers
private const string SiteverifyUrl = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
public int Priority => 1;
public bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey);
public bool IsConfigured =>
!string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey);
public async Task<bool> VerifyAsync(VerificationContext ctx)
{
@@ -20,11 +21,7 @@ namespace SharpbinV3.Server.Services.Verification.Providers
if (string.IsNullOrEmpty(ctx.Token))
return false;
var parameters = new Dictionary<string, string>
{
{ "secret", _authSettings.CF_Turnstile_SecretKey },
{ "response", ctx.Token }
};
var parameters = new Dictionary<string, string> { { "secret", _authSettings.CF_Turnstile_SecretKey }, { "response", ctx.Token } };
if (!string.IsNullOrEmpty(ctx.Ip))
parameters.Add("remoteip", ctx.Ip);
@@ -8,5 +8,4 @@
public Guid? UserUUID { get; init; }
public string? Code { get; init; }
}
}
@@ -8,10 +8,7 @@ namespace SharpbinV3.Server.Services.Verification
private IVerificationProvider? GetActiveProvider()
{
return _providers
.Where(p => p.IsConfigured)
.OrderByDescending(p => p.Priority)
.FirstOrDefault();
return _providers.Where(p => p.IsConfigured).OrderByDescending(p => p.Priority).FirstOrDefault();
}
public async Task<bool> VerifyAsync(VerificationContext context, IVerificationProvider? provider = null)
@@ -7,5 +7,6 @@
public bool Registration_Enabled { get; set; } = true;
public bool First_User_Admin { get; set; } = true;
public bool Admins_Require_2FA { get; set; } = true;
public string API_Key_HMAC_Secret { get; set; } = string.Empty;
}
}
@@ -6,8 +6,10 @@ namespace SharpbinV3.Server.Settings
{
[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";
}
+3 -1
View File
@@ -8,9 +8,11 @@ namespace SharpbinV3.Server.Settings
public int MaxTitleLength { get; set; } = 500;
public int MaxPasteSizeInBytes { get; set; } = 1_048_576; // 1 MB
public bool EnablePasteCompression { get; set; } = true;
public bool RequiresVerfication { get; set; } = true;
public bool RequiresVerification { 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;
}
+34 -31
View File
@@ -1,35 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>a95b1aac-5cce-4fa9-8056-51f0d045cf2f</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>a95b1aac-5cce-4fa9-8056-51f0d045cf2f</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<EnableStaticWebAssets>false</EnableStaticWebAssets>
<EnableDefaultContentItems>false</EnableDefaultContentItems>
<AllowMissingPrunePackageData>True</AllowMissingPrunePackageData>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.01" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageReference Include="Otp.NET" Version="1.4.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
</ItemGroup>
<EnableStaticWebAssets>false</EnableStaticWebAssets>
<EnableDefaultContentItems>false</EnableDefaultContentItems>
<AllowMissingPrunePackageData>True</AllowMissingPrunePackageData>
<OpenApiGenerateDocumentsOnBuild>false</OpenApiGenerateDocumentsOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.01" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageReference Include="Otp.NET" Version="1.4.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
</ItemGroup>
</Project>
+28
View File
@@ -10,12 +10,40 @@ namespace SharpbinV3.Server
var random = new Random();
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]);
}
public static string GenerateSecureRandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Span<byte> buffer = stackalloc byte[128];
var result = new char[length];
int pos = 0;
while (pos < length)
{
RandomNumberGenerator.Fill(buffer);
foreach (byte b in buffer)
{
if (b >= 248)
continue; // 248 is the largest multiple of 62 < 256
result[pos++] = chars[b % chars.Length];
if (pos == length)
break;
}
}
return new string(result);
}
public static string ComputeSha256(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
var hashBytes = SHA256.HashData(inputBytes);
return Convert.ToHexString(hashBytes);
}
public static string ComputeHmacSha256(string secret, string input)
{
var secretBytes = System.Text.Encoding.UTF8.GetBytes(secret);
+115 -82
View File
@@ -17,156 +17,189 @@
"PasteSettings": {
"ValidSyntaxLanguages": [
"plaintext",
"abap",
"actionscript-3",
"1c",
"abnf",
"accesslog",
"actionscript",
"ada",
"angelscript",
"apache",
"apex",
"apl",
"applescript",
"ara",
"asm",
"astro",
"arcade",
"arduino",
"arm",
"asciidoc",
"aspectj",
"autohotkey",
"autoit",
"avrasm",
"awk",
"ballerina",
"bat",
"berry",
"bibtex",
"bicep",
"blade",
"bash",
"basic",
"bnf",
"brainfuck",
"c",
"cadence",
"clarity",
"cpp",
"hpp",
"csharp",
"cal",
"cos",
"capnproto",
"clojure",
"cmake",
"cobol",
"codeql",
"coffee",
"cpp",
"coffeescript",
"coq",
"crmsh",
"crystal",
"csharp",
"csp",
"css",
"csv",
"cue",
"d",
"dart",
"deplhi",
"diff",
"docker",
"dream-maker",
"django",
"dns",
"dockerfile",
"dos",
"bat",
"dsconfig",
"dts",
"dust",
"ebnf",
"elixir",
"elm",
"erb",
"erlang",
"fish",
"excel",
"fsharp",
"gdresource",
"gdscript",
"gdshader",
"fix",
"flix",
"fortran",
"gcode",
"gams",
"gauss",
"gherkin",
"git-commit",
"git-rebase",
"glsl",
"gnuplot",
"go",
"golo",
"gradle",
"graphql",
"groovy",
"hack",
"haml",
"handlebars",
"haskell",
"hcl",
"hjson",
"hlsl",
"haxe",
"html",
"xml",
"rss",
"atom",
"svg",
"http",
"https",
"hy",
"inform7",
"ini",
"toml",
"irpf90",
"java",
"javascript",
"jison",
"jolie",
"json",
"json5",
"jsonc",
"jsonnet",
"jssm",
"jsx",
"julia",
"julia-repl",
"kotlin",
"lasso",
"latex",
"ldif",
"leaf",
"less",
"liquid",
"lisp",
"logo",
"livecodeserver",
"livescript",
"lua",
"makefile",
"markdown",
"marko",
"mathematica",
"matlab",
"mdx",
"maxima",
"mel",
"mercury",
"mipsasm",
"mizar",
"mojolicious",
"monkey",
"moonscript",
"n1ql",
"nginx",
"nim",
"nix",
"objective-c",
"objective-cpp",
"nsis",
"objectivec",
"ocaml",
"pascal",
"glsl",
"openscad",
"ruleslanguage",
"oxygene",
"parser3",
"perl",
"pf",
"php",
"plsql",
"postcss",
"powerquery",
"pony",
"postgresql",
"powershell",
"prisma",
"processing",
"prolog",
"proto",
"pug",
"properties",
"protobuf",
"puppet",
"purescript",
"python",
"profiler",
"python-repl",
"q",
"qml",
"r",
"raku",
"razor",
"reg",
"rel",
"riscv",
"rst",
"reasonml",
"rib",
"rsl",
"graph",
"ruby",
"rust",
"sas",
"sass",
"scala",
"scheme",
"scilab",
"scss",
"shaderlab",
"shell",
"smali",
"smalltalk",
"solidity",
"sparql",
"sml",
"sql",
"ssh-config",
"stan",
"stata",
"step21",
"stylus",
"subunit",
"svelte",
"swift",
"system-verilog",
"tasl",
"tcl",
"tex",
"toml",
"tsx",
"turtle",
"tap",
"thrift",
"toit",
"tp",
"twig",
"typescript",
"v",
"vb",
"vala",
"vbnet",
"vba",
"vbscript",
"verilog",
"vhdl",
"viml",
"vue",
"wasm",
"wenyan",
"xml",
"xsl",
"vim",
"axapta",
"x86asm",
"xl",
"xquery",
"yaml",
"zenscript"
"zephir"
],
"MaxPasteSizeBytes": 1048576,
"MaxTitleLength": 500
+20
View File
@@ -0,0 +1,20 @@
{
"version": 1,
"isRoot": true,
"tools": {
"csharpier": {
"version": "1.2.6",
"commands": [
"csharpier"
],
"rollForward": false
},
"dotnet-ef": {
"version": "10.0.3",
"commands": [
"dotnet-ef"
],
"rollForward": false
}
}
}