Compare commits

..
121 Commits
Author SHA1 Message Date
whoswhip ec4bbad1d7 chore: bump version to 3.0.5 2026-03-31 02:19:59 -04:00
whoswhip 3b53cfbddf fix: forward headers during requests where needed
this is mainly just so any ip headers like cf-connecting-ip are forwarded for rate limiting
2026-03-31 02:18:52 -04:00
whoswhip 6d99a06c17 fix: improve header handling and error checking in paste loading 2026-03-30 22:51:28 -04:00
whoswhip 094c8e5e08 fix: remove rate limiting on {id}/raw and {id} 2026-03-30 22:16:04 -04:00
whoswhip 801426f93e fix: make syntax extension comparison case insensitive and remove '.' 2026-03-30 22:13:19 -04:00
whoswhip abacbf14af Merge branch 'SharpbinV3' of github.com:whoswhip/Sharpbin into SharpbinV3 2026-03-30 20:34:37 -04:00
whoswhip 62d80597dc fix: forward the request header when viewing on the /[id] server route 2026-03-30 20:34:30 -04:00
whoswhip ccb5db14d2 Merge pull request #8 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/picomatch-4.0.4
chore(deps): bump picomatch from 4.0.3 to 4.0.4 in /SharpbinV3.Client
2026-03-29 23:41:48 -04:00
dependabot[bot] da423eb1c8 chore(deps): bump picomatch from 4.0.3 to 4.0.4 in /SharpbinV3.Client
Bumps [picomatch](https://github.com/micromatch/picomatch) from 4.0.3 to 4.0.4.
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/4.0.3...4.0.4)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 4.0.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-30 03:41:22 +00:00
whoswhip 08c4bf4367 Merge pull request #7 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/handlebars-4.7.9
chore(deps-dev): bump handlebars from 4.7.8 to 4.7.9 in /SharpbinV3.Client
2026-03-29 23:36:26 -04:00
dependabot[bot] 0aa9176835 chore(deps-dev): bump handlebars in /SharpbinV3.Client
Bumps [handlebars](https://github.com/handlebars-lang/handlebars.js) from 4.7.8 to 4.7.9.
- [Release notes](https://github.com/handlebars-lang/handlebars.js/releases)
- [Changelog](https://github.com/handlebars-lang/handlebars.js/blob/v4.7.9/release-notes.md)
- [Commits](https://github.com/handlebars-lang/handlebars.js/compare/v4.7.8...v4.7.9)

---
updated-dependencies:
- dependency-name: handlebars
  dependency-version: 4.7.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-30 03:36:00 +00:00
whoswhip e8eb677ba7 refactor: use getUserFromToken on report/[reportId] 2026-03-28 18:55:45 -04:00
whoswhip 322af06832 refactor(auth): simplify role checking and remove JWT decoding function
this also fixes permission checking
2026-03-28 18:53:15 -04:00
whoswhip d78baae19e feat(auth): add JWT user parsing from token 2026-03-28 18:52:51 -04:00
whoswhip e102c91d79 fix: improve icon consistency 2026-03-27 20:29:23 -04:00
whoswhip 6a59b72d08 style: format via prettier 2026-03-27 20:21:47 -04:00
whoswhip 27093acadf style: improve code line number display and adjust top-0 to top-15 on paste header 2026-03-27 20:21:33 -04:00
whoswhip 4e02399d9f style: enhance navbar styling and improve link hover effects 2026-03-27 20:21:11 -04:00
whoswhip b7ce54d5a0 feat: add HatGlasses icon for anonymous users in Paste component 2026-03-27 20:20:42 -04:00
whoswhip 8eede40000 feat: guest param in user page
shows as if the user isnt logged in, except for the settings tab
2026-03-27 20:19:54 -04:00
whoswhip c98aca92b6 fix(cache): ensure pasteExpiresAt is valid before cache deletion 2026-03-26 17:52:38 -04:00
whoswhip 5296efa9db fix: switch to better sqlite-3 instead of experimental node api 2026-03-26 17:20:38 -04:00
whoswhip 9486840f05 feat: open graph embed image generation 2026-03-26 17:13:42 -04:00
whoswhip 6047d48da2 fix(types): add missing createdAt field to Paste interface 2026-03-26 17:13:04 -04:00
whoswhip 73f73d88dc docs: add JSDoc comments for utility functions in misc.ts 2026-03-26 15:51:58 -04:00
whoswhip 1496a02b76 refactor: wrap break word instead of truncate on paste titles 2026-03-26 14:25:58 -04:00
whoswhip 059d32e42c feat: /user/{uuid} redirects to /user/{username} based off uuid 2026-03-19 10:10:20 -04:00
whoswhip 797747f718 fix(controller): update paste expiration check to handle zero expiration case 2026-03-10 19:12:54 -04:00
whoswhip f70328c93d fix(controller): only return paste not found if null or expired 2026-03-10 19:06:50 -04:00
whoswhip 8b8c0bbf7a style: format via prettier/csharpier 2026-03-10 04:10:31 -04:00
whoswhip 6eb4f699b5 refactor(backend:auth): improve banned user checks and simplify claim retrieval
1,000 commits in 270 days 🎉
2026-03-10 04:09:48 -04:00
whoswhip e0c9f1bbc1 fix(docker): correct environment variable syntax for backend service 2026-03-10 03:39:05 -04:00
whoswhip bf1c647d10 chore(docker): add missing environment section for backend service 2026-03-10 03:36:44 -04:00
whoswhip 873b1778ee refactor(migrations): correct namespace for entities in model snapshot 2026-03-10 03:23:44 -04:00
whoswhip 44d7ae8cd3 feat(roles, visibility): refactor user roles to use flags and introduce visibility enum 2026-03-10 03:21:13 -04:00
whoswhip 0564d55396 feat(email): add email verification html templates 2026-03-10 03:20:48 -04:00
whoswhip 5f11ee4350 chore(backend): remove unnecessary settings 2026-03-10 03:13:47 -04:00
whoswhip 4c071fcc39 fix(frontend:paste): increase paste views only if api returns 'Paste view recorded.' 2026-03-09 15:04:17 -04:00
whoswhip e7cd3723a7 feat(markdown): add dont warn again feature 2026-03-09 14:53:16 -04:00
whoswhip d4e2cf25d3 fix(docker-compose): add back VITE_API_URL environment variable to frontend 2026-03-08 16:41:49 -04:00
whoswhip fbec598ee2 docs(README): add backend configuration details for domain and HTTPS settings 2026-03-08 16:26:00 -04:00
whoswhip cb7f94fd5c chore(env): add example environment configuration files for backend and frontend 2026-03-08 16:14:52 -04:00
whoswhip 0c9a747935 chore(docker-compose): remove unused environment variables from backend and frontend services 2026-03-08 16:14:39 -04:00
whoswhip 38c8af1c57 fix(routes): /raw/{pasteId} no longer returns a body on error 2026-03-08 14:58:56 -04:00
whoswhip ec0635dd3b fix(backend:paste): check expiration before returning paste data or recording views; prevent paste authors from adding views to their own paste 2026-03-08 14:45:32 -04:00
whoswhip 49e73cde9c fix(auth): replace HMAC token generation with SHA256 for email verification
the HMAC is intended for other actions like change email, i just forgot and was rushing at the time, whoops!
2026-03-07 17:56:06 -05:00
whoswhip 12f716eb83 chore(deps): update package references to latest versions 2026-03-07 12:49:48 -05:00
whoswhip c986a73ef4 fix(docker-compose): add env_file entries for backend and frontend services 2026-03-07 11:30:51 -05:00
whoswhip b9cff6a0bd fix(email): ensure all email settings are validated before sending; allow nullable From property 2026-03-07 11:12:44 -05:00
whoswhip 2302ebdffc fix(dotenv): skip empty lines and comments when loading environment variables 2026-03-07 11:12:26 -05:00
whoswhip 2b66cb2762 fix(email): validate settings before sending; use hmac for tokens 2026-03-07 10:44:26 -05:00
whoswhip 32c46b8c2b refactor: remove unused EmailService dependency from AuthController 2026-03-07 10:38:41 -05:00
whoswhip e329e1f8ea Merge branch 'SharpbinV3' of github.com:whoswhip/Sharpbin into SharpbinV3 2026-03-06 20:13:58 -05:00
whoswhip 2c794b833a style: format via prettier and csharpier 2026-03-06 20:13:56 -05:00
whoswhip 5420d94595 feat(email): implement email queue management 2026-03-06 20:13:24 -05:00
whoswhip 95da3f9543 feat: email verification via smtp 2026-03-06 20:10:07 -05:00
whoswhip d21265f443 refactor: centralize API URL and internal API key management for improved maintainability 2026-03-06 20:09:14 -05:00
whoswhip 7dbbcb65ac Merge pull request #6 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/dompurify-3.3.2
chore(deps): bump dompurify from 3.3.1 to 3.3.2 in /SharpbinV3.Client
2026-03-06 15:52:37 -05:00
dependabot[bot] 980cbfa989 chore(deps): bump dompurify from 3.3.1 to 3.3.2 in /SharpbinV3.Client
Bumps [dompurify](https://github.com/cure53/DOMPurify) from 3.3.1 to 3.3.2.
- [Release notes](https://github.com/cure53/DOMPurify/releases)
- [Commits](https://github.com/cure53/DOMPurify/compare/3.3.1...3.3.2)

---
updated-dependencies:
- dependency-name: dompurify
  dependency-version: 3.3.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-06 20:51:38 +00:00
whoswhip 528456c168 refactor(encryption): replace magic numbers with constants for improved readability and maintainability 2026-03-05 22:05:24 -05:00
whoswhip b54c12ba10 fix(encryption): improve encryption security: adjust salt size and memory parameters for AES encryption 2026-03-05 22:03:32 -05:00
whoswhip eef98030d6 fix(frontend): use darker version of tooltip on generate random password 2026-03-04 15:12:00 -05:00
whoswhip 00233280d4 feat(backend): add DotEnv class for loading environment variables from .env file 2026-03-04 15:11:25 -05:00
whoswhip 4e8d71b8c6 Merge pull request #5 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/multi-770cfcd984
chore(deps): bump minimatch in /SharpbinV3.Client
2026-02-27 05:03:00 -05:00
dependabot[bot] 73a1edcc85 chore(deps): bump minimatch in /SharpbinV3.Client
Bumps  and [minimatch](https://github.com/isaacs/minimatch). These dependencies needed to be updated together.

Updates `minimatch` from 3.1.2 to 3.1.5
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

Updates `minimatch` from 9.0.5 to 9.0.9
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 3.1.5
  dependency-type: indirect
- dependency-name: minimatch
  dependency-version: 9.0.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-27 09:58:02 +00:00
whoswhip f1aef1cc3c Merge pull request #4 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/rollup-4.59.0
chore(deps): bump rollup from 4.54.0 to 4.59.0 in /SharpbinV3.Client
2026-02-27 04:56:42 -05:00
dependabot[bot] 7d87e2be13 chore(deps): bump rollup from 4.54.0 to 4.59.0 in /SharpbinV3.Client
Bumps [rollup](https://github.com/rollup/rollup) from 4.54.0 to 4.59.0.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.54.0...v4.59.0)

---
updated-dependencies:
- dependency-name: rollup
  dependency-version: 4.59.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-27 09:56:06 +00:00
whoswhip 51c6ea5f98 Merge pull request #3 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/svelte-5.53.5
chore(deps-dev): bump svelte from 5.48.3 to 5.53.5 in /SharpbinV3.Client
2026-02-27 04:54:54 -05:00
dependabot[bot] 3c346353aa chore(deps-dev): bump svelte from 5.48.3 to 5.53.5 in /SharpbinV3.Client
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 5.48.3 to 5.53.5.
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.53.5/packages/svelte)

---
updated-dependencies:
- dependency-name: svelte
  dependency-version: 5.53.5
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-27 09:36:58 +00:00
whoswhip ac2f0a3dcf refactor(backend:utilties): simplify GenerateSecureRandomString 2026-02-21 01:35:34 -05:00
whoswhip 75ecfbe7e7 feat(auth): improve token refreshing 2026-02-18 19:08:15 -05:00
whoswhip 2c3f8c95ac fix(frontend:user): resolve lint error 2026-02-18 19:07:46 -05:00
whoswhip f64584602e fix: set default value for AuthSettings__First_User_Admin and pass GIT_COMMIT_HASH as build argument 2026-02-17 20:40:52 -05:00
whoswhip 5eebea314e feat: add GIT_COMMIT_HASH support for versioning in Dockerfile and footer 2026-02-17 20:40:44 -05:00
whoswhip f786117cad fix: correct expiration time for 'Expire in 5 Minutes' option 2026-02-14 18:52:25 -05:00
whoswhip 3ba63f692c fix: add back CSV syntax support in consts and appsettings 2026-02-14 18:50:49 -05:00
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
119 changed files with 8024 additions and 1853 deletions
+2
View File
@@ -324,3 +324,5 @@ FodyWeavers.xsd
Data Data
!SharpbinV3.Server/Data !SharpbinV3.Server/Data
.idea .idea
**/.env
+133
View File
@@ -1,3 +1,136 @@
## [3.0.5](https://github.com/whoswhip/Sharpbin/compare/v3.0.4...v3.0.5) (2026-03-31)
### Bug Fixes
* add back CSV syntax support in consts and appsettings ([3ba63f6](https://github.com/whoswhip/Sharpbin/commit/3ba63f692c25e016f226fccc9120a3649c7150d9))
* **auth:** replace HMAC token generation with SHA256 for email verification ([49e73cd](https://github.com/whoswhip/Sharpbin/commit/49e73cde9c856bee9f36e2cedb9742bd6a3e9942))
* **backend:paste:** check expiration before returning paste data or recording views; prevent paste authors from adding views to their own paste ([ec0635d](https://github.com/whoswhip/Sharpbin/commit/ec0635dd3b6401679e1a4a923302de5dcdbecda8))
* **cache:** ensure pasteExpiresAt is valid before cache deletion ([c98aca9](https://github.com/whoswhip/Sharpbin/commit/c98aca92b68a761056b5610d893c7be17da06d96))
* **controller:** only return paste not found if null or expired ([f70328c](https://github.com/whoswhip/Sharpbin/commit/f70328c93d8b008f6015ec239cc984bbcc0b57e3))
* **controller:** update paste expiration check to handle zero expiration case ([797747f](https://github.com/whoswhip/Sharpbin/commit/797747f718913f1b52d0d17caf7fc1f720bde59b))
* correct expiration time for 'Expire in 5 Minutes' option ([f786117](https://github.com/whoswhip/Sharpbin/commit/f786117cad468d0c0cacae10bbfe82c8d647353b))
* **docker-compose:** add back VITE_API_URL environment variable to frontend ([d4e2cf2](https://github.com/whoswhip/Sharpbin/commit/d4e2cf25d3c4eb4c414b59ce6b5655cd9a3ba8a7))
* **docker-compose:** add env_file entries for backend and frontend services ([c986a73](https://github.com/whoswhip/Sharpbin/commit/c986a73ef44df90c2e47f3a2dc60900b2271d230))
* **docker:** correct environment variable syntax for backend service ([e0c9f1b](https://github.com/whoswhip/Sharpbin/commit/e0c9f1bbc1fc150d139043bbfb84ff16a86b20be))
* **dotenv:** skip empty lines and comments when loading environment variables ([2302ebd](https://github.com/whoswhip/Sharpbin/commit/2302ebdffc74dbd5023803919730ac5bb8243abf))
* **email:** ensure all email settings are validated before sending; allow nullable From property ([b9cff6a](https://github.com/whoswhip/Sharpbin/commit/b9cff6a0bd5899e3aaa3775981ae0782d621fa97))
* **email:** validate settings before sending; use hmac for tokens ([2b66cb2](https://github.com/whoswhip/Sharpbin/commit/2b66cb27629726480c00ffae4775810a35ee4fcf))
* **encryption:** improve encryption security: adjust salt size and memory parameters for AES encryption ([b54c12b](https://github.com/whoswhip/Sharpbin/commit/b54c12ba10c3f6607a6345caaa4d528e90f1ce0a))
* forward headers during requests where needed ([3b53cfb](https://github.com/whoswhip/Sharpbin/commit/3b53cfbddf0397c8b040641d784dce8b070c9753))
* forward the request header when viewing on the /[id] server route ([62d8059](https://github.com/whoswhip/Sharpbin/commit/62d80597dc51428fc3be810fb268b4bfd4cd6098))
* **frontend:paste:** increase paste views only if api returns 'Paste view recorded.' ([4c071fc](https://github.com/whoswhip/Sharpbin/commit/4c071fcc3965f1164d95d0c2dfd729059ee7cfad))
* **frontend:user:** resolve lint error ([2c3f8c9](https://github.com/whoswhip/Sharpbin/commit/2c3f8c95ac55a891caeaebacadad808bfc7180d2))
* **frontend:** use darker version of tooltip on generate random password ([eef9803](https://github.com/whoswhip/Sharpbin/commit/eef98030d6daf6c223d5e12e7ad024211e411d13))
* improve header handling and error checking in paste loading ([6d99a06](https://github.com/whoswhip/Sharpbin/commit/6d99a06c17b7365c26d4dd48405f2963f5826f1f))
* improve icon consistency ([e102c91](https://github.com/whoswhip/Sharpbin/commit/e102c91d79618b87b71653e23df7a6511a6c09ba))
* make syntax extension comparison case insensitive and remove '.' ([801426f](https://github.com/whoswhip/Sharpbin/commit/801426f93e08fdce0d548f8c539c5f7dc06fea93))
* remove rate limiting on {id}/raw and {id} ([094c8e5](https://github.com/whoswhip/Sharpbin/commit/094c8e5e08dcbef33d4f0e4d965ac467d8d4d6d4))
* **routes:** /raw/{pasteId} no longer returns a body on error ([38c8af1](https://github.com/whoswhip/Sharpbin/commit/38c8af1c5713defe06077842bacbf69ef47eff00))
* set default value for AuthSettings__First_User_Admin and pass GIT_COMMIT_HASH as build argument ([f645846](https://github.com/whoswhip/Sharpbin/commit/f64584602eb7b29a7854923420c25811a2a64946))
* switch to better sqlite-3 instead of experimental node api ([5296efa](https://github.com/whoswhip/Sharpbin/commit/5296efa9dbf4bfd6f6613cdee4806d170de9ba6d))
* **types:** add missing createdAt field to Paste interface ([6047d48](https://github.com/whoswhip/Sharpbin/commit/6047d48da2d5920e9e79b4e12b48a142ec9e2646))
### Features
* /user/{uuid} redirects to /user/{username} based off uuid ([059d32e](https://github.com/whoswhip/Sharpbin/commit/059d32e42c93fa0113e0bf253ab8bb432b3fa0b2))
* add GIT_COMMIT_HASH support for versioning in Dockerfile and footer ([5eebea3](https://github.com/whoswhip/Sharpbin/commit/5eebea314e6c475e012d0378aa4d6147485210f4))
* add HatGlasses icon for anonymous users in Paste component ([b7ce54d](https://github.com/whoswhip/Sharpbin/commit/b7ce54d5a0e00ee27e53e492b71a973d63e94bef))
* **auth:** add JWT user parsing from token ([d78baae](https://github.com/whoswhip/Sharpbin/commit/d78baae19e2508cac2205fcc9b3b09ee600d95fe))
* **auth:** improve token refreshing ([75ecfbe](https://github.com/whoswhip/Sharpbin/commit/75ecfbe7e7724addf71f2a9d1de41f28132602a1))
* **backend:** add DotEnv class for loading environment variables from .env file ([0023328](https://github.com/whoswhip/Sharpbin/commit/00233280d45a2fa87c4c01b9086620606be210e1))
* email verification via smtp ([95da3f9](https://github.com/whoswhip/Sharpbin/commit/95da3f95435709692de347272fae01dff13ddf7c))
* **email:** add email verification html templates ([0564d55](https://github.com/whoswhip/Sharpbin/commit/0564d55396da1f811aa7fa624a8f42392aeb49b9))
* **email:** implement email queue management ([5420d94](https://github.com/whoswhip/Sharpbin/commit/5420d94595bba2731409677631551b7bc265ad3c))
* guest param in user page ([8eede40](https://github.com/whoswhip/Sharpbin/commit/8eede40000f6a541188c95370073e76113d152d8))
* **markdown:** add dont warn again feature ([e7cd372](https://github.com/whoswhip/Sharpbin/commit/e7cd3723a7c60e3f058de990e1b7ac2efb414683))
* open graph embed image generation ([9486840](https://github.com/whoswhip/Sharpbin/commit/9486840f05fadac604f1ccd3a838f3f0d1a71f51))
* **roles, visibility:** refactor user roles to use flags and introduce visibility enum ([44d7ae8](https://github.com/whoswhip/Sharpbin/commit/44d7ae8cd3ead498f7975a20b5269ee311553d23))
## [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) ## [3.0.1](https://github.com/whoswhip/Sharpbin/compare/v3.0.0...v3.0.1) (2026-01-27)
+17 -7
View File
@@ -34,29 +34,39 @@ docker-compose up -d
### Configuration ### 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) #### Backend (SharpbinV3.Server)
- `Domain`: The domain your instance of Sharpbin will be hosted at (e.g., example.com)
- `Https`: Whether or not your instance is behind https. Used when sendings emails.
- `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=/app/data/sharpbin.db`). - `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=/app/data/sharpbin.db`).
- `JwtSettings__Secret`: A secure string used for signing JWT tokens. - `JwtSettings__Secret`: A secure string used for signing JWT tokens.
- `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key. - `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key.
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site 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__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__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__MaxTitleLength`: Max title length in characters.
- `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB) - `PasteSettings__MaxPasteSizeInBytes`:**1_048_576** (1MB): Max Paste Size set in bytes.
- `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default. - `PasteSettings__EnablePasteCompression`:**true**: Enables/Disables server-side paste compression.
- `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default. - `PasteSettings__RequiresVerification`:**true**: Enables/Disables CAPTCHA verification when creating pastes.
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers - `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. - `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) #### Frontend (SharpbinV3.Client)
- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`). - `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`) - `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.cc`)
- `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. - `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.
The frontend will be accessible at http://localhost:5173. The frontend will be accessible at http://localhost:5173.
+1
View File
@@ -7,6 +7,7 @@ node_modules
.wrangler .wrangler
/.svelte-kit /.svelte-kit
/build /build
.cache
# OS # OS
.DS_Store .DS_Store
+2
View File
@@ -1,5 +1,7 @@
# syntax=docker/dockerfile:1 # syntax=docker/dockerfile:1
FROM node:20-alpine as build FROM node:20-alpine as build
ARG GIT_COMMIT_HASH
ENV GIT_COMMIT_HASH=${GIT_COMMIT_HASH}
WORKDIR /app WORKDIR /app
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
RUN npm ci RUN npm ci
+3 -11
View File
@@ -19,7 +19,7 @@ npm install
### Environment Configuration ### 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_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`) - `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 npm run dev
``` ```
The application will be available at http://localhost:5173. The frontend will be available at http://localhost:5173.
## Script Reference ## Script Reference
- `npm run dev`: Start the Vite development server. - `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 preview`: Locally preview the production build.
- `npm run check`: Run type checking with svelte-check. - `npm run check`: Run type checking with svelte-check.
- `npm run lint`: Run ESLint and Prettier checks. - `npm run lint`: Run ESLint and Prettier checks.
- `npm run format`: Format the codebase with Prettier. - `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.
+1572 -133
View File
File diff suppressed because it is too large Load Diff
+12 -4
View File
@@ -1,7 +1,7 @@
{ {
"name": "sharpbinv3.client", "name": "sharpbinv3.client",
"private": true, "private": true,
"version": "3.0.2", "version": "3.0.5",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite dev", "dev": "vite dev",
@@ -21,6 +21,7 @@
"@sveltejs/kit": "^2.50.0", "@sveltejs/kit": "^2.50.0",
"@sveltejs/vite-plugin-svelte": "^6.2.1", "@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17", "@tailwindcss/vite": "^4.1.17",
"@types/better-sqlite3": "^7.6.13",
"@types/jsdom": "^27.0.0", "@types/jsdom": "^27.0.0",
"@types/node": "^22", "@types/node": "^22",
"@types/papaparse": "^5.5.2", "@types/papaparse": "^5.5.2",
@@ -34,7 +35,7 @@
"prettier": "^3.7.4", "prettier": "^3.7.4",
"prettier-plugin-svelte": "^3.4.0", "prettier-plugin-svelte": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.7.2", "prettier-plugin-tailwindcss": "^0.7.2",
"svelte": "^5.48.3", "svelte": "^5.53.5",
"svelte-check": "^4.3.4", "svelte-check": "^4.3.4",
"tailwind-scrollbar": "^4.0.2", "tailwind-scrollbar": "^4.0.2",
"tailwindcss": "^4.1.17", "tailwindcss": "^4.1.17",
@@ -43,14 +44,21 @@
"vite": "^7.2.6" "vite": "^7.2.6"
}, },
"dependencies": { "dependencies": {
"@fontsource/inter": "^5.2.8",
"@fontsource/jetbrains-mono": "^5.2.8",
"@lucide/svelte": "^0.562.0", "@lucide/svelte": "^0.562.0",
"@resvg/resvg-js": "^2.6.2",
"@sveltejs/adapter-node": "^5.4.0", "@sveltejs/adapter-node": "^5.4.0",
"dompurify": "^3.3.1", "better-sqlite3": "^12.8.0",
"dompurify": "^3.3.2",
"hash-wasm": "^4.12.0", "hash-wasm": "^4.12.0",
"highlight.js": "^11.8.0", "highlight.js": "^11.8.0",
"jsdom": "^27.4.0", "jsdom": "^27.4.0",
"marked": "^17.0.1", "marked": "^17.0.1",
"papaparse": "^5.5.3", "papaparse": "^5.5.3",
"qrcode": "^1.5.4" "qrcode": "^1.5.4",
"satori": "^0.26.0",
"satori-html": "^0.3.2",
"sharp": "^0.34.5"
} }
} }
+1
View File
@@ -27,6 +27,7 @@ declare global {
| undefined; | undefined;
var turnstileLoaded: (() => void) | undefined; var turnstileLoaded: (() => void) | undefined;
declare const __APP_VERSION__: string; declare const __APP_VERSION__: string;
declare const COMMIT_HASH: string;
} }
export {}; export {};
@@ -1,3 +1,7 @@
<script lang="ts">
import { resolve } from '$app/paths';
</script>
<div <div
class="mb-5 max-h-10 w-full border-t border-neutral-800 pt-5 text-center text-sm text-neutral-500" 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,18 @@
Source Code Source Code
</a> </a>
<span class="mx-1">•</span> <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__} v{__APP_VERSION__}
<a
href="https://github.com/whoswhip/Sharpbin/commit/{COMMIT_HASH}"
target="_blank"
rel="noopener noreferrer"
class="text-neutral-400 underline hover:text-neutral-200"
>{(COMMIT_HASH?.length ?? 0) >= 7 && COMMIT_HASH !== 'unknown'
? `(${COMMIT_HASH.slice(0, 7)})`
: ''}</a
>
</div> </div>
@@ -43,6 +43,7 @@
let reportType = ''; let reportType = '';
let reportInitialized = false; let reportInitialized = false;
let reportLoading = false; let reportLoading = false;
let multiselectInitialized = false;
let turnstileEl: HTMLDivElement | null = null; let turnstileEl: HTMLDivElement | null = null;
let turnstileWidgetId: string | null = null; let turnstileWidgetId: string | null = null;
@@ -85,6 +86,11 @@
initializeReport(); initializeReport();
} }
$: if (show && mode === 'multiselect' && !multiselectInitialized) {
multiselectInitialized = true;
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
}
function resetModal() { function resetModal() {
inputValue = inputValue =
initialValue !== null initialValue !== null
@@ -102,6 +108,7 @@
reportType = ''; reportType = '';
reportInitialized = false; reportInitialized = false;
reportLoading = false; reportLoading = false;
multiselectInitialized = false;
if (turnstileWidgetId && typeof window !== 'undefined' && window.turnstile?.remove) { if (turnstileWidgetId && typeof window !== 'undefined' && window.turnstile?.remove) {
window.turnstile.remove(turnstileWidgetId); window.turnstile.remove(turnstileWidgetId);
} }
@@ -395,10 +402,10 @@
</script> </script>
{#if show} {#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 <form
on:submit|preventDefault={handleSubmit} 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"> <h2 class="mb-4 text-xl font-semibold text-white">
{displayTitle} {displayTitle}
@@ -2,7 +2,7 @@
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { page } from '$app/state'; import { page } from '$app/state';
import { clearTokens } from '$lib/utils/auth'; import { clearTokens, hasRole } from '$lib/utils/auth';
import logo from '$lib/assets/favicon.svg'; import logo from '$lib/assets/favicon.svg';
import type { PageData } from '../../routes/$types'; import type { PageData } from '../../routes/$types';
import { slide } from 'svelte/transition'; import { slide } from 'svelte/transition';
@@ -41,28 +41,40 @@
}); });
</script> </script>
<div class="top-0 left-0 z-100 h-15 w-full bg-neutral-900" id="navbar"> <div
class="sticky top-0 left-0 z-100 h-15 w-full border-b border-neutral-800 bg-neutral-900 shadow-md"
id="navbar"
>
<div class="mx-auto hidden h-15 w-[95%] max-w-7xl items-center py-2 md:flex"> <div class="mx-auto hidden h-15 w-[95%] max-w-7xl items-center py-2 md:flex">
<div> <div class="flex items-center gap-6">
<a href={resolve('/')} class="text-xl font-bold text-white hover:text-neutral-300">Sharpbin</a <a href={resolve('/')} class="group flex items-center gap-2">
<img src={logo} alt="Sharpbin Logo" class="h-7 w-7 group-hover:opacity-80" />
<span class="text-xl font-bold text-white group-hover:text-neutral-300">Sharpbin</span>
</a>
<div class="h-5 w-px bg-neutral-700"></div>
<a
href={resolve('/recent')}
class="relative text-neutral-300 after:absolute after:-bottom-0.5 after:left-0 after:h-px after:w-0 after:bg-white after:transition-all hover:text-white hover:after:w-full"
>Recent Pastes</a
> >
<a href={resolve('/recent')} class="ml-6 text-white hover:text-neutral-300">Recent Pastes</a>
</div> </div>
{#if $user} {#if $user}
<div class="ml-auto flex items-center space-x-4"> <div class="ml-auto flex items-center space-x-4">
{#if $user.roles.includes(1) || $user.roles.includes(255)} {#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
<a <a
href={resolve('/reports')} href={resolve('/reports')}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Reports</a class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
>Reports</a
> >
{/if} {/if}
<a <a
href={resolve(`/user/${$user.username}`)} href={resolve(`/user/${$user.username}`)}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Profile</a class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
>Profile</a
> >
<button <button
on:click={logout} on:click={logout}
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800" class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
>Logout</button >Logout</button
> >
</div> </div>
@@ -70,13 +82,14 @@
<div class="ml-auto flex items-center space-x-4"> <div class="ml-auto flex items-center space-x-4">
<a <a
href={resolve(`/login${returnParam}`)} href={resolve(`/login${returnParam}`)}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Login</a class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
>Login</a
> >
<!-- eslint-disable svelte/no-navigation-without-resolve --> <!-- eslint-disable svelte/no-navigation-without-resolve -->
<a <a
href={data.options?.registration_enabled ? resolve(`/register${returnParam}`) : '#'} href={data.options?.registration_enabled ? resolve(`/register${returnParam}`) : '#'}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800 {data.options class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600 {data
?.registration_enabled .options?.registration_enabled
? '' ? ''
: 'cursor-not-allowed bg-neutral-800 text-neutral-500!'}">Register</a : 'cursor-not-allowed bg-neutral-800 text-neutral-500!'}">Register</a
> >
@@ -116,7 +129,7 @@
on:click={() => (menuOpen = false)}>Recent Pastes</a on:click={() => (menuOpen = false)}>Recent Pastes</a
> >
{#if $user} {#if $user}
{#if $user.roles.includes(1) || $user.roles.includes(255)} {#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
<a <a
href={resolve('/reports')} href={resolve('/reports')}
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700" class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
@@ -1,11 +1,5 @@
<script lang="ts"> <script lang="ts">
import { import { tooltip, dateToRelativeString, formatNumber, formatBytes } from '$lib/utils/misc';
tooltip,
dateToRelativeString,
extractDateFromUUIDv7,
formatNumber,
formatBytes
} from '$lib/utils/misc';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { import {
Eye, Eye,
@@ -13,11 +7,12 @@
Code, Code,
User, User,
History, History,
Calendar, CalendarDays,
Timer, CalendarOff,
Lock, Lock,
EyeOff, EyeOff,
Globe Globe,
HatGlasses
} from '@lucide/svelte'; } from '@lucide/svelte';
import { syntaxes } from '$lib/consts'; import { syntaxes } from '$lib/consts';
import type { Paste } from '$lib/types/paste'; import type { Paste } from '$lib/types/paste';
@@ -27,7 +22,6 @@
export let showUser: boolean = true; export let showUser: boolean = true;
export let compact: boolean = false; export let compact: boolean = false;
const createdAt = extractDateFromUUIDv7(paste.uuid);
const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext']; const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext'];
</script> </script>
@@ -45,14 +39,14 @@
</span> </span>
<div <div
class="flex items-center gap-2 text-sm text-neutral-400" class="flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={`${createdAt?.toLocaleString()} • ${dateToRelativeString(createdAt ?? new Date(), true, false, now)}`} use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
> >
<Calendar class="h-4 w-4" /> <CalendarDays class="h-4 w-4" />
{#if createdAt} {#if paste.createdAt}
{#if createdAt.getTime() > Date.now() - 86_400_000} {#if paste.createdAt > Date.now() - 86_400_000}
Created {dateToRelativeString(createdAt, true, false, now)} Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
{:else} {:else}
Created on {createdAt.toLocaleDateString()} Created on {new Date(paste.createdAt).toLocaleDateString()}
{/if} {/if}
{:else} {:else}
Creation date unknown Creation date unknown
@@ -64,7 +58,11 @@
<div> <div>
{#if showUser} {#if showUser}
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
{#if paste.author}
<User class="h-4 w-4" /> <User class="h-4 w-4" />
{:else}
<HatGlasses class="h-4 w-4" />
{/if}
{paste.author?.username ?? 'Anonymous'} {paste.author?.username ?? 'Anonymous'}
</div> </div>
{:else} {:else}
@@ -117,15 +115,15 @@
<div> <div>
<div <div
class="flex items-center gap-2 text-sm text-neutral-400" class="flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={`${createdAt?.toLocaleString()} • ${dateToRelativeString(createdAt ?? new Date(), true, false, now)}`} use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
> >
<Calendar class="h-4 w-4" /> <CalendarDays class="h-4 w-4" />
<span> <span>
{#if createdAt} {#if paste.createdAt}
{#if createdAt.getTime() > Date.now() - 86_400_000} {#if paste.createdAt > Date.now() - 86_400_000}
Created {dateToRelativeString(createdAt, true, false, now)} Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
{:else} {:else}
Created on {createdAt.toLocaleDateString()} Created on {new Date(paste.createdAt).toLocaleDateString()}
{/if} {/if}
{:else} {:else}
Creation date unknown Creation date unknown
@@ -146,7 +144,7 @@
class="mt-1 flex items-center gap-2 text-sm text-neutral-400" class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={new Date(paste.expiresAt).toLocaleString()} use:tooltip={new Date(paste.expiresAt).toLocaleString()}
> >
<Timer class="h-4 w-4" /> <CalendarOff class="h-4 w-4" />
<span> <span>
{paste.expiresAt > 0 && paste.expiresAt < Date.now() {paste.expiresAt > 0 && paste.expiresAt < Date.now()
? `Expired ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}` ? `Expired ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`
@@ -156,7 +154,11 @@
{/if} {/if}
{#if showUser} {#if showUser}
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400"> <div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
{#if paste.author}
<User class="h-4 w-4" /> <User class="h-4 w-4" />
{:else}
<HatGlasses class="h-4 w-4" />
{/if}
<span>{paste.author?.username ?? 'Anonymous'}</span> <span>{paste.author?.username ?? 'Anonymous'}</span>
</div> </div>
{/if} {/if}
+186 -159
View File
@@ -4,162 +4,196 @@ export type Syntax = {
}; };
export const syntaxes: Record<string, Syntax> = { export const syntaxes: Record<string, Syntax> = {
plaintext: { name: 'Plain Text', extension: '' }, plaintext: { name: 'Plain Text', extension: 'txt' },
abap: { name: 'ABAP', extension: '.abap' }, '1c': { name: '1c', extension: '' },
'actionscript-3': { name: 'ActionScript 3', extension: '.as' }, abnf: { name: 'Augmented Backus-Naur Form', extension: 'abnf' },
ada: { name: 'Ada', extension: '.adb' }, accesslog: { name: 'Access Log', extension: 'log' },
apache: { name: 'Apache', extension: '.conf' }, actionscript: { name: 'ActionScript', extension: 'as' },
apex: { name: 'Apex', extension: '.cls' }, ada: { name: 'Ada', extension: 'ada' },
apl: { name: 'APL', extension: '.apl' }, angelscript: { name: 'AngelScript', extension: 'angelscript' },
applescript: { name: 'AppleScript', extension: '.applescript' }, apache: { name: 'Apache', extension: 'apache' },
ara: { name: 'ARA', extension: '.ara' }, applescript: { name: 'AppleScript', extension: 'applescript' },
asm: { name: 'Assembly', extension: '.asm' }, arcade: { name: 'Arcade', extension: 'arcade' },
astro: { name: 'Astro', extension: '.astro' }, arduino: { name: 'Arduino', extension: 'ino' },
awk: { name: 'AWK', extension: '.awk' }, arm: { name: 'ARM Assembly', extension: 's' },
ballerina: { name: 'Ballerina', extension: '.bal' }, asciidoc: { name: 'AsciiDoc', extension: 'adoc' },
bat: { name: 'Batch', extension: '.bat' }, aspectj: { name: 'AspectJ', extension: 'aj' },
berry: { name: 'Berry', extension: '.be' }, autohotkey: { name: 'AutoHotkey', extension: 'ahk' },
bibtex: { name: 'BibTeX', extension: '.bib' }, autoit: { name: 'AutoIt', extension: 'au3' },
bicep: { name: 'Bicep', extension: '.bicep' }, avrasm: { name: 'AVR Assembly', extension: 's' },
blade: { name: 'Blade', extension: '.blade.php' }, awk: { name: 'AWK', extension: 'awk' },
c: { name: 'C', extension: '.c' }, bash: { name: 'Bash', extension: 'sh' },
cadence: { name: 'Cadence', extension: '.cdc' }, basic: { name: 'BASIC', extension: 'bas' },
clarity: { name: 'Clarity', extension: '.clar' }, bnf: { name: 'Backus-Naur Form', extension: 'bnf' },
clojure: { name: 'Clojure', extension: '.clj' }, brainfuck: { name: 'Brainfuck', extension: 'bf' },
cmake: { name: 'CMake', extension: '.cmake' }, c: { name: 'C', extension: 'c' },
cobol: { name: 'COBOL', extension: '.cob' }, cpp: { name: 'C++', extension: 'cpp' },
codeql: { name: 'CodeQL', extension: '.ql' }, hpp: { name: 'C++ Header', extension: 'h' },
coffee: { name: 'CoffeeScript', extension: '.coffee' }, csharp: { name: 'C#', extension: 'cs' },
cpp: { name: 'C++', extension: '.cpp' }, cal: { name: 'C/AL', extension: '' },
crystal: { name: 'Crystal', extension: '.cr' }, cos: { name: 'Cache Object Script', extension: '' },
csharp: { name: 'C#', extension: '.cs' }, capnproto: { name: "Cap'n Proto", extension: 'capnp' },
css: { name: 'CSS', extension: '.css' }, clojure: { name: 'Clojure', extension: 'clj' },
csv: { name: 'CSV', extension: '.csv' }, cmake: { name: 'CMake', extension: 'cmake' },
cue: { name: 'CUE', extension: '.cue' }, coffeescript: { name: 'CoffeeScript', extension: 'coffee' },
d: { name: 'D', extension: '.d' }, coq: { name: 'Coq', extension: 'v' },
dart: { name: 'Dart', extension: '.dart' }, crmsh: { name: 'CRMsH', extension: '' },
diff: { name: 'Diff', extension: '.diff' }, crystal: { name: 'Crystal', extension: 'cr' },
docker: { name: 'Docker', extension: 'Dockerfile' }, csp: { name: 'CSP', extension: 'csp' },
'dream-maker': { name: 'Dream Maker', extension: '.dm' }, css: { name: 'CSS', extension: 'css' },
elixir: { name: 'Elixir', extension: '.ex' }, csv: { name: 'CSV', extension: 'csv' },
elm: { name: 'Elm', extension: '.elm' }, d: { name: 'D', extension: 'd' },
erb: { name: 'ERB', extension: '.erb' }, dart: { name: 'Dart', extension: 'dart' },
erlang: { name: 'Erlang', extension: '.erl' }, deplhi: { name: 'Delphi', extension: 'pas' },
fish: { name: 'Fish', extension: '.fish' }, diff: { name: 'Diff', extension: 'diff' },
fsharp: { name: 'F#', extension: '.fs' }, django: { name: 'Django', extension: 'django' },
gdresource: { name: 'Godot Resource', extension: '.tres' }, dns: { name: 'DNS Zone', extension: 'dns' },
gdscript: { name: 'GDScript', extension: '.gd' }, dockerfile: { name: 'Dockerfile', extension: 'dockerfile' },
gdshader: { name: 'Godot Shader', extension: '.gdshader' }, dos: { name: 'DOS', extension: 'bat' },
gherkin: { name: 'Gherkin', extension: '.feature' }, bat: { name: 'Batchfile', extension: 'bat' },
'git-commit': { name: 'Git Commit', extension: '' }, dsconfig: { name: 'DSConfig', extension: '' },
'git-rebase': { name: 'Git Rebase', extension: '' }, dts: { name: 'Device Tree', extension: 'dts' },
glsl: { name: 'GLSL', extension: '.glsl' }, dust: { name: 'Dust', extension: 'dust' },
gnuplot: { name: 'Gnuplot', extension: '.gp' }, ebnf: { name: 'Extended Backus-Naur Form', extension: 'ebnf' },
go: { name: 'Go', extension: '.go' }, elixir: { name: 'Elixir', extension: 'ex' },
graphql: { name: 'GraphQL', extension: '.graphql' }, elm: { name: 'Elm', extension: 'elm' },
groovy: { name: 'Groovy', extension: '.groovy' }, erlang: { name: 'Erlang', extension: 'erl' },
hack: { name: 'Hack', extension: '.hack' }, excel: { name: 'Excel', extension: 'xlsx' },
haml: { name: 'Haml', extension: '.haml' }, fsharp: { name: 'F#', extension: 'fs' },
handlebars: { name: 'Handlebars', extension: '.hbs' }, fix: { name: 'FIX', extension: 'fix' },
haskell: { name: 'Haskell', extension: '.hs' }, flix: { name: 'Flix', extension: 'flix' },
hcl: { name: 'HCL', extension: '.hcl' }, fortran: { name: 'Fortran', extension: 'f90' },
hjson: { name: 'HJSON', extension: '.hjson' }, gcode: { name: 'G-code', extension: 'gcode' },
hlsl: { name: 'HLSL', extension: '.hlsl' }, gams: { name: 'GAMS', extension: 'gms' },
html: { name: 'HTML', extension: '.html' }, gauss: { name: 'GAUSS', extension: 'gss' },
ini: { name: 'INI', extension: '.ini' }, gherkin: { name: 'Gherkin', extension: '' },
java: { name: 'Java', extension: '.java' }, go: { name: 'Go', extension: 'go' },
javascript: { name: 'JavaScript', extension: '.js' }, golo: { name: 'Golo', extension: 'golo' },
jison: { name: 'Jison', extension: '.jison' }, gradle: { name: 'Gradle', extension: 'gradle' },
json: { name: 'JSON', extension: '.json' }, graphql: { name: 'GraphQL', extension: 'graphql' },
json5: { name: 'JSON5', extension: '.json5' }, groovy: { name: 'Groovy', extension: 'groovy' },
jsonc: { name: 'JSONC', extension: '.json' }, haml: { name: 'HAML', extension: 'haml' },
jsonnet: { name: 'Jsonnet', extension: '.jsonnet' }, handlebars: { name: 'Handlebars', extension: 'hbs' },
jssm: { name: 'JSSM', extension: '.jssm' }, haskell: { name: 'Haskell', extension: 'hs' },
jsx: { name: 'JSX', extension: '.jsx' }, haxe: { name: 'Haxe', extension: 'hx' },
julia: { name: 'Julia', extension: '.jl' }, html: { name: 'HTML', extension: 'html' },
kotlin: { name: 'Kotlin', extension: '.kt' }, xml: { name: 'XML', extension: 'xml' },
latex: { name: 'LaTeX', extension: '.tex' }, rss: { name: 'RSS', extension: 'rss' },
less: { name: 'Less', extension: '.less' }, atom: { name: 'Atom', extension: 'atom' },
liquid: { name: 'Liquid', extension: '.liquid' }, svg: { name: 'SVG', extension: 'svg' },
lisp: { name: 'Lisp', extension: '.lisp' }, http: { name: 'HTTP', extension: 'http' },
logo: { name: 'Logo', extension: '.logo' }, https: { name: 'HTTPS', extension: 'http' },
lua: { name: 'Lua', extension: '.lua' }, hy: { name: 'Hy', extension: 'hy' },
makefile: { name: 'Makefile', extension: '.makefile' }, inform7: { name: 'Inform 7', extension: 'ni' },
markdown: { name: 'Markdown', extension: '.md' }, ini: { name: 'INI', extension: 'ini' },
marko: { name: 'Marko', extension: '.marko' }, toml: { name: 'TOML', extension: 'toml' },
matlab: { name: 'MATLAB', extension: '.m' }, irpf90: { name: 'IRPF90', extension: 'irpf90' },
mdx: { name: 'MDX', extension: '.mdx' }, java: { name: 'Java', extension: 'java' },
nginx: { name: 'Nginx', extension: '.conf' }, javascript: { name: 'JavaScript', extension: 'js' },
nim: { name: 'Nim', extension: '.nim' }, jolie: { name: 'Jolie', extension: 'ol' },
nix: { name: 'Nix', extension: '.nix' }, json: { name: 'JSON', extension: 'json' },
'objective-c': { name: 'Objective-C', extension: '.m' }, json5: { name: 'JSON5', extension: 'json5' },
'objective-cpp': { name: 'Objective-C++', extension: '.mm' }, julia: { name: 'Julia', extension: 'jl' },
ocaml: { name: 'OCaml', extension: '.ml' }, 'julia-repl': { name: 'Julia REPL', extension: '' },
pascal: { name: 'Pascal', extension: '.pas' }, kotlin: { name: 'Kotlin', extension: 'kt' },
perl: { name: 'Perl', extension: '.pl' }, lasso: { name: 'Lasso', extension: 'lasso' },
php: { name: 'PHP', extension: '.php' }, latex: { name: 'LaTeX', extension: 'tex' },
plsql: { name: 'PL/SQL', extension: '.sql' }, ldif: { name: 'LDIF', extension: 'ldif' },
postcss: { name: 'PostCSS', extension: '.pcss' }, leaf: { name: 'Leaf', extension: 'leaf' },
powerquery: { name: 'Power Query', extension: '.pq' }, less: { name: 'Less', extension: 'less' },
powershell: { name: 'PowerShell', extension: '.ps1' }, lisp: { name: 'Lisp', extension: 'lisp' },
prisma: { name: 'Prisma', extension: '.prisma' }, livecodeserver: { name: 'LiveCode Server', extension: '' },
prolog: { name: 'Prolog', extension: '.pl' }, livescript: { name: 'LiveScript', extension: 'ls' },
proto: { name: 'Protocol Buffers', extension: '.proto' }, lua: { name: 'Lua', extension: 'lua' },
pug: { name: 'Pug', extension: '.pug' }, makefile: { name: 'Makefile', extension: 'makefile' },
puppet: { name: 'Puppet', extension: '.pp' }, markdown: { name: 'Markdown', extension: 'md' },
purescript: { name: 'PureScript', extension: '.purs' }, mathematica: { name: 'Mathematica', extension: 'nb' },
python: { name: 'Python', extension: '.py' }, matlab: { name: 'MATLAB', extension: 'm' },
r: { name: 'R', extension: '.r' }, maxima: { name: 'Maxima', extension: 'max' },
raku: { name: 'Raku', extension: '.raku' }, mel: { name: 'Maya Embedded Language', extension: 'mel' },
razor: { name: 'Razor', extension: '.cshtml' }, mercury: { name: 'Mercury', extension: 'm' },
reg: { name: 'Registry', extension: '.reg' }, mipsasm: { name: 'MIPS Assembly', extension: 's' },
rel: { name: 'Rel', extension: '.rel' }, mizar: { name: 'Mizar', extension: 'miz' },
riscv: { name: 'RISC-V', extension: '.s' }, mojolicious: { name: 'Mojolicious', extension: '' },
rst: { name: 'reStructuredText', extension: '.rst' }, monkey: { name: 'Monkey', extension: 'monkey' },
ruby: { name: 'Ruby', extension: '.rb' }, moonscript: { name: 'MoonScript', extension: 'moon' },
rust: { name: 'Rust', extension: '.rs' }, n1ql: { name: 'N1QL', extension: '' },
sas: { name: 'SAS', extension: '.sas' }, nginx: { name: 'Nginx', extension: 'nginx' },
sass: { name: 'Sass', extension: '.sass' }, nim: { name: 'Nim', extension: 'nim' },
scala: { name: 'Scala', extension: '.scala' }, nix: { name: 'Nix', extension: 'nix' },
scheme: { name: 'Scheme', extension: '.scm' }, nsis: { name: 'NSIS', extension: 'nsi' },
scss: { name: 'SCSS', extension: '.scss' }, objectivec: { name: 'Objective-C', extension: 'm' },
shaderlab: { name: 'ShaderLab', extension: '.shader' }, ocaml: { name: 'OCaml', extension: 'ml' },
shell: { name: 'Shell', extension: '.sh' }, glsl: { name: 'OpenGL Shading Language', extension: 'glsl' },
smalltalk: { name: 'Smalltalk', extension: '.st' }, openscad: { name: 'OpenSCAD', extension: 'scad' },
solidity: { name: 'Solidity', extension: '.sol' }, ruleslanguage: { name: 'Oracle Rules Language', extension: '' },
sparql: { name: 'SPARQL', extension: '.rq' }, oxygene: { name: 'Oxygene', extension: 'oxygene' },
sql: { name: 'SQL', extension: '.sql' }, parser3: { name: 'Parser3', extension: '' },
'ssh-config': { name: 'SSH Config', extension: '' }, perl: { name: 'Perl', extension: 'pl' },
stata: { name: 'Stata', extension: '.do' }, pf: { name: 'PF', extension: 'pf' },
stylus: { name: 'Stylus', extension: '.styl' }, php: { name: 'PHP', extension: 'php' },
svelte: { name: 'Svelte', extension: '.svelte' }, pony: { name: 'Pony', extension: 'pony' },
swift: { name: 'Swift', extension: '.swift' }, postgresql: { name: 'PostgreSQL', extension: 'sql' },
'system-verilog': { name: 'SystemVerilog', extension: '.sv' }, powershell: { name: 'PowerShell', extension: 'ps1' },
tasl: { name: 'TASL', extension: '.tasl' }, processing: { name: 'Processing', extension: 'pde' },
tcl: { name: 'Tcl', extension: '.tcl' }, prolog: { name: 'Prolog', extension: 'pl' },
tex: { name: 'TeX', extension: '.tex' }, properties: { name: 'Java Properties', extension: 'properties' },
toml: { name: 'TOML', extension: '.toml' }, protobuf: { name: 'Protocol Buffers', extension: 'proto' },
tsx: { name: 'TSX', extension: '.tsx' }, puppet: { name: 'Puppet', extension: 'pp' },
turtle: { name: 'Turtle', extension: '.ttl' }, python: { name: 'Python', extension: 'py' },
twig: { name: 'Twig', extension: '.twig' }, profiler: { name: 'Poython Profiler Results', extension: '' },
typescript: { name: 'TypeScript', extension: '.ts' }, 'python-repl': { name: 'Python REPL', extension: '' },
v: { name: 'V', extension: '.v' }, q: { name: 'Q', extension: 'q' },
vb: { name: 'VB', extension: '.vb' }, qml: { name: 'QML', extension: 'qml' },
verilog: { name: 'Verilog', extension: '.v' }, r: { name: 'R', extension: 'r' },
vhdl: { name: 'VHDL', extension: '.vhdl' }, reasonml: { name: 'ReasonML', extension: 're' },
viml: { name: 'VimL', extension: '.vim' }, rib: { name: 'RenderMan Interface Bytestream', extension: 'rib' },
vue: { name: 'Vue', extension: '.vue' }, rsl: { name: 'RenderMan Shading Language', extension: 'rsl' },
wasm: { name: 'WebAssembly', extension: '.wasm' }, graph: { name: 'Roboconf', extension: '' },
wenyan: { name: 'Wenyan', extension: '.wy' }, ruby: { name: 'Ruby', extension: 'rb' },
xml: { name: 'XML', extension: '.xml' }, rust: { name: 'Rust', extension: 'rs' },
xsl: { name: 'XSL', extension: '.xsl' }, sas: { name: 'SAS', extension: 'sas' },
yaml: { name: 'YAML', extension: '.yaml' }, scala: { name: 'Scala', extension: 'scala' },
zenscript: { name: 'ZenScript', extension: '.zs' } 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 = [ export const expiresOptions = [
{ value: 0, label: 'Never Expire' }, { value: 0, label: 'Never Expire' },
{ value: 30000, label: 'Expire in 5 Minutes' }, { value: 300000, label: 'Expire in 5 Minutes' },
{ value: 600000, label: 'Expire in 10 Minutes' }, { value: 600000, label: 'Expire in 10 Minutes' },
{ value: 1800000, label: 'Expire in 30 Minutes' }, { value: 1800000, label: 'Expire in 30 Minutes' },
{ value: 3600000, label: 'Expire in 1 Hour' }, { value: 3600000, label: 'Expire in 1 Hour' },
@@ -177,13 +211,6 @@ export const expiresOptions = [
{ value: 315360000000, label: 'Expire in 10 Years' } { value: 315360000000, label: 'Expire in 10 Years' }
]; ];
export const roles = {
0: 'User',
1: 'Moderator',
255: 'Administrator',
403: 'Banned'
};
export const trustedDomains = [ export const trustedDomains = [
'img.youtube.com', 'img.youtube.com',
'i.ytimg.com', 'i.ytimg.com',
+7
View File
@@ -0,0 +1,7 @@
import { env } from '$env/dynamic/private';
export const apiUrl = env.VITE_API_URL ?? 'http://localhost:5050';
export const viewInternalApiKey =
env.NODE_ENV === 'development'
? 'cccdd42d9f2f648493e402f1da7c855ea798ad510e6bb9ea712dd7bed838e58'
: (env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '');
@@ -0,0 +1,114 @@
<script lang="ts">
import CalendarDays from '@lucide/svelte/icons/calendar-days';
import CalendarOff from '@lucide/svelte/icons/calendar-off';
import Code from '@lucide/svelte/icons/code';
import Eye from '@lucide/svelte/icons/eye';
import EyeOff from '@lucide/svelte/icons/eye-off';
import FileBox from '@lucide/svelte/icons/file-box';
import Globe from '@lucide/svelte/icons/globe';
import Lock from '@lucide/svelte/icons/lock';
import User from '@lucide/svelte/icons/user';
import type { PasteEmbedProps } from './pasteEmbed';
export let title: PasteEmbedProps['title'];
export let uploader: PasteEmbedProps['uploader'];
export let metadata: PasteEmbedProps['metadata'];
export let previewLines: PasteEmbedProps['previewLines'];
export let isEncrypted: PasteEmbedProps['isEncrypted'];
const metadataIcons = {
size: FileBox,
views: Eye,
created: CalendarDays,
expires: CalendarOff,
syntax: Code,
'visibility-0': Globe,
'visibility-1': EyeOff,
'visibility-2': Lock
} as const;
</script>
<!--
the following tailwindcss styles fail to parse, so they are applied inline:
neutral-950
gap-1.5
truncate
whitespace-nowrap
gap-2
gap-x-6.5
gap-y-3
gap-0.75
gap-3
whitespace-pre
-->
<!-- 630px by 1200px -->
<div class="flex h-157.5 w-300 p-6" style="font-family:'Inter'; background-color: #0a0a0a;">
<div
class="flex h-full w-full flex-col rounded-lg border-2 border-neutral-800 bg-neutral-900 p-4"
>
<div class="mb-3.5 flex flex-col items-center justify-center" style="gap: 6px;">
<div
class="max-w-250 text-[54px] leading-[1.1] font-bold text-white"
style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
>
{title}
</div>
<div class="flex items-center text-[20px] text-neutral-400" style="gap: 8px;">
<User class="h-4.5 w-4.5 text-neutral-400" />
<div>{uploader}</div>
</div>
</div>
<div class="mb-3 flex flex-wrap items-center justify-center" style="gap: 12px;">
{#each metadata as item (item.value)}
{@const Icon = metadataIcons[item.icon]}
<div class="flex items-center text-[24px] leading-none text-neutral-400">
<Icon class="mr-2 h-5.5 w-5.5 text-neutral-400" />
<div class="text-[24px] text-neutral-400">{item.value}</div>
</div>
{/each}
</div>
{#if isEncrypted}
<div
class="flex flex-1 items-center justify-center overflow-hidden rounded-lg bg-neutral-800"
>
<div class="flex flex-col items-center justify-center gap-3.5 p-6">
<Lock class="h-16 w-16 text-neutral-400" />
<div class="text-[36px] leading-[1.1] font-bold text-neutral-100">Encrypted Paste</div>
<div class="max-w-195 text-center text-[20px] leading-[1.3] text-neutral-400">
Preview is hidden for private encrypted pastes. Open the paste page and decrypt with the
password to view content.
</div>
</div>
</div>
{:else}
<div class="relative flex flex-1 overflow-hidden rounded-lg bg-neutral-800">
<div class="flex w-full flex-col pt-3" style="gap: 3px;">
{#each previewLines as line, index (index)}
<!-- emulates whitespace for indentation since satori doesnt seem to render it properly -->
{@const leadingSpaceCount = line.length - line.trimStart().length}
{@const contentWithoutIndent = line.trimStart()}
<div class="flex items-center px-3.5" style="gap: 12px;">
<div
class="w-7.5 text-right text-[20px] text-neutral-500"
style="font-family:'JetBrains Mono'; white-space: pre;"
>
{String(index + 1).padStart(3, ' ')}
</div>
<div
class="flex items-center text-[20px] text-neutral-100"
style="font-family:'JetBrains Mono'; white-space: pre;"
>
<div style={`width: ${leadingSpaceCount * 12}px;`}></div>
<div>{contentWithoutIndent}</div>
</div>
</div>
{/each}
</div>
<div
class="absolute right-0 bottom-0 left-0"
style="height: 58px; background: linear-gradient(to bottom, rgba(38, 38, 38, 0), rgba(38, 38, 38, 1));"
></div>
</div>
{/if}
</div>
</div>
@@ -0,0 +1,210 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
import { mkdirSync } from 'node:fs';
import { dirname, join } from 'node:path';
import BetterSqlite3 from 'better-sqlite3';
import type { Database } from 'better-sqlite3';
const CACHE_DIR = '.cache/og-images';
const CACHE_DB_PATH = join(CACHE_DIR, 'index.db');
const CACHE_EXPIRY_MS = 24 * 60 * 60 * 1000;
const CACHE_CLEAN_INTERVAL_MS = 60 * 60 * 1000;
const CACHE_STALE_WHILE_REVALIDATE_SECONDS = 300;
const PURGE_BATCH_SIZE = 200;
type CacheRow = {
relativePath: string;
pasteExpiresAt: number | null;
cacheExpiresAt: number;
};
type ExpiredCacheRow = {
pasteId: string;
relativePath: string;
};
export type CachedOgImage = {
jpg: Buffer;
ttlSeconds: number;
};
export type StoreCachedOgImageInput = {
id: string;
jpg: Buffer;
pasteExpiresAt?: number | null;
};
let database: Database | null = null;
let lastPurgeAt = 0;
let purgeInFlight: Promise<void> | null = null;
function getDatabase(): Database {
if (database) return database;
mkdirSync(CACHE_DIR, { recursive: true });
const nextDatabase = new BetterSqlite3(CACHE_DB_PATH);
nextDatabase.exec('PRAGMA journal_mode = WAL');
nextDatabase.exec('PRAGMA synchronous = NORMAL');
nextDatabase.exec(`
CREATE TABLE IF NOT EXISTS og_image_cache (
paste_id TEXT PRIMARY KEY,
relative_path TEXT NOT NULL,
paste_expires_at INTEGER,
cache_expires_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_og_image_cache_cache_expires_at
ON og_image_cache (cache_expires_at);
CREATE INDEX IF NOT EXISTS idx_og_image_cache_paste_expires_at
ON og_image_cache (paste_expires_at);
`);
database = nextDatabase;
return nextDatabase;
}
function getCacheTtlExpiry(pasteExpiresAt?: number | null): number {
const cacheExpiresAt = Date.now() + CACHE_EXPIRY_MS;
if (!pasteExpiresAt) return cacheExpiresAt;
return Math.min(cacheExpiresAt, pasteExpiresAt);
}
export function getCacheTtlSeconds(expiresAt?: number | null): number {
if (!expiresAt) return CACHE_EXPIRY_MS / 1000;
const secondsUntilExpiry = Math.floor((expiresAt - Date.now()) / 1000);
if (secondsUntilExpiry <= 0) return 0;
return Math.min(secondsUntilExpiry, CACHE_EXPIRY_MS / 1000);
}
export function getCacheControlHeader(ttlSeconds: number): string {
return ttlSeconds > 0
? `private, max-age=${ttlSeconds}, stale-while-revalidate=${CACHE_STALE_WHILE_REVALIDATE_SECONDS}`
: 'no-store, max-age=0';
}
function getShardRelativePath(id: string): string {
const hash = createHash('sha256').update(id).digest('hex');
return join(hash.slice(0, 2), hash.slice(2, 4), `${id}.jpg`);
}
function getAbsolutePath(relativePath: string): string {
return join(CACHE_DIR, relativePath);
}
async function deleteCacheFile(relativePath: string): Promise<void> {
await unlink(getAbsolutePath(relativePath)).catch(() => undefined);
}
async function deleteCacheEntry(id: string, relativePath?: string): Promise<void> {
const db = getDatabase();
const resolvedPath =
relativePath ??
(
db
.prepare('SELECT relative_path AS relativePath FROM og_image_cache WHERE paste_id = ?')
.get(id) as { relativePath: string } | undefined
)?.relativePath ??
null;
db.prepare('DELETE FROM og_image_cache WHERE paste_id = ?').run(id);
if (resolvedPath) {
await deleteCacheFile(resolvedPath);
}
}
export async function getCachedOgImage(id: string): Promise<CachedOgImage | null> {
const db = getDatabase();
const row = db
.prepare(
'SELECT relative_path AS relativePath, paste_expires_at AS pasteExpiresAt, cache_expires_at AS cacheExpiresAt FROM og_image_cache WHERE paste_id = ?'
)
.get(id) as CacheRow | undefined;
if (!row) {
return null;
}
const ttlSeconds = getCacheTtlSeconds(row.cacheExpiresAt);
if (ttlSeconds <= 0) {
await deleteCacheEntry(id, row.relativePath);
return null;
}
if (
typeof row.pasteExpiresAt === 'number' &&
row.pasteExpiresAt > 0 &&
row.pasteExpiresAt <= Date.now()
) {
await deleteCacheEntry(id, row.relativePath);
return null;
}
try {
const jpg = await readFile(getAbsolutePath(row.relativePath));
return { jpg, ttlSeconds };
} catch {
await deleteCacheEntry(id, row.relativePath);
return null;
}
}
export async function storeCachedOgImage({
id,
jpg,
pasteExpiresAt
}: StoreCachedOgImageInput): Promise<void> {
const db = getDatabase();
const relativePath = getShardRelativePath(id);
const absolutePath = getAbsolutePath(relativePath);
const tempPath = `${absolutePath}.tmp-${process.pid}-${Date.now()}`;
await mkdir(dirname(absolutePath), { recursive: true });
await writeFile(tempPath, jpg);
await rename(tempPath, absolutePath);
try {
db.prepare(
`INSERT INTO og_image_cache (paste_id, relative_path, paste_expires_at, cache_expires_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(paste_id) DO UPDATE SET
relative_path = excluded.relative_path,
paste_expires_at = excluded.paste_expires_at,
cache_expires_at = excluded.cache_expires_at`
).run(id, relativePath, pasteExpiresAt ?? null, getCacheTtlExpiry(pasteExpiresAt));
} catch (error) {
await unlink(absolutePath).catch(() => undefined);
throw error;
}
}
async function purgeExpiredCache(limit: number = PURGE_BATCH_SIZE): Promise<void> {
const db = getDatabase();
const now = Date.now();
const rows = db
.prepare(
`SELECT paste_id AS pasteId, relative_path AS relativePath
FROM og_image_cache
WHERE cache_expires_at <= ?
OR (paste_expires_at IS NOT NULL AND paste_expires_at > 0 AND paste_expires_at <= ?)
LIMIT ?`
)
.all(now, now, limit) as ExpiredCacheRow[];
if (rows.length === 0) {
return;
}
for (const row of rows) {
await deleteCacheFile(row.relativePath);
db.prepare('DELETE FROM og_image_cache WHERE paste_id = ?').run(row.pasteId);
}
}
export function scheduleOgImageCachePurge(): void {
const now = Date.now();
if (purgeInFlight || now - lastPurgeAt < CACHE_CLEAN_INTERVAL_MS) {
return;
}
purgeInFlight = purgeExpiredCache().finally(() => {
lastPurgeAt = Date.now();
purgeInFlight = null;
});
}
@@ -0,0 +1,20 @@
export type PasteEmbedMetadataItem = {
icon:
| 'size'
| 'views'
| 'created'
| 'expires'
| 'syntax'
| 'visibility-0'
| 'visibility-1'
| 'visibility-2';
value: string;
};
export type PasteEmbedProps = {
title: string;
uploader: string;
metadata: PasteEmbedMetadataItem[];
previewLines: string[];
isEncrypted: boolean;
};
+1
View File
@@ -3,6 +3,7 @@ import type { Author } from './author';
export interface Paste { export interface Paste {
id: string; id: string;
uuid: string; uuid: string;
createdAt: number;
title: string | null; title: string | null;
size: number; size: number;
trueSize: number; trueSize: number;
+2 -9
View File
@@ -24,15 +24,8 @@ export interface ReportListResponse {
pagination: Pagination; pagination: Pagination;
} }
export const reportTypeLabels = [ export const reportTypeLabels = ['CopyrightViolation', 'IllegalContent', 'Fraud', 'Other'] as const;
'Spam',
'Abuse',
'InappropriateContent',
'CopyrightViolation',
'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; export const reportTargetLabels = ['Paste', 'User'] as const;
+11 -1
View File
@@ -8,7 +8,8 @@ export interface User {
displayName: string | null; displayName: string | null;
email: string | null; email: string | null;
lastLogin: number | null; lastLogin: number | null;
roles: number[]; roles: number; // bitfield; 5 = User | Admin
isBanned: boolean;
visibility: 0 | 1 | 2; visibility: 0 | 1 | 2;
pastes: Paste[] | null; pastes: Paste[] | null;
pagination: Pagination | null; pagination: Pagination | null;
@@ -17,3 +18,12 @@ export interface User {
export interface AuthUser extends User { export interface AuthUser extends User {
totpEnabled: boolean; totpEnabled: boolean;
} }
export interface JWTUser {
uuid: string;
username: string;
displayname: string;
totpEnabled: boolean;
roles: number;
isBanned: boolean;
}
+79 -12
View File
@@ -1,10 +1,23 @@
import { browser } from '$app/environment'; import { browser } from '$app/environment';
import type { Cookies } from '@sveltejs/kit'; import type { Cookies } from '@sveltejs/kit';
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import type { JWTUser } from '$lib/types/user';
export const roles = {
User: 1,
Moderator: 2,
Admin: 4
} as const;
export type Role = keyof typeof roles;
const TOKEN_KEY = 'token'; const TOKEN_KEY = 'token';
const REFRESH_TOKEN_KEY = 'refreshToken'; const REFRESH_TOKEN_KEY = 'refreshToken';
let refreshPromise: Promise<void> | null = null;
let lastRefreshAttempt = 0;
let refreshFailureCount = 0;
export function getToken() { export function getToken() {
if (!browser) return null; if (!browser) return null;
return ( return (
@@ -27,19 +40,25 @@ export function getRefreshToken() {
export function setTokens(token: string, refreshToken: string) { export function setTokens(token: string, refreshToken: string) {
if (!browser) return; if (!browser) return;
console.log('Setting tokens');
document.cookie = `${TOKEN_KEY}=${token}; path=/; secure; samesite=strict`; document.cookie = `${TOKEN_KEY}=${token}; path=/; secure; samesite=strict`;
document.cookie = `${REFRESH_TOKEN_KEY}=${refreshToken}; path=/; secure; samesite=strict`; document.cookie = `${REFRESH_TOKEN_KEY}=${refreshToken}; path=/; secure; samesite=strict`;
refreshFailureCount = 0;
} }
export function clearTokens() { export function clearTokens() {
if (!browser) return; if (!browser) return;
console.log('Clearing tokens');
document.cookie = `${TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`; document.cookie = `${TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`; document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
user.set(null); user.set(null);
} }
function getBackoffDelay(attempt: number): number {
const baseDelay = 1000;
const maxDelay = 30000;
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
return delay + Math.random() * 1000;
}
export async function refreshTokenIfNeeded() { export async function refreshTokenIfNeeded() {
const token = getToken(); const token = getToken();
const refreshToken = getRefreshToken(); const refreshToken = getRefreshToken();
@@ -49,28 +68,55 @@ export async function refreshTokenIfNeeded() {
const exp = payload.exp * 1000; const exp = payload.exp * 1000;
const now = Date.now(); const now = Date.now();
if (exp - now < 2 * 60 * 1000) { if (exp - now >= 2 * 60 * 1000) return;
console.log('Refreshing token...');
if (refreshPromise) {
await refreshPromise;
return;
}
const timeSinceLastAttempt = now - lastRefreshAttempt;
const minDelay = getBackoffDelay(refreshFailureCount);
if (timeSinceLastAttempt < minDelay) return;
refreshPromise = performRefresh(token, refreshToken);
try {
await refreshPromise;
} finally {
refreshPromise = null;
}
}
async function performRefresh(token: string, refreshToken: string) {
lastRefreshAttempt = Date.now();
try {
const res = await fetch('/api/auth/refresh', { const res = await fetch('/api/auth/refresh', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, refreshToken }) body: JSON.stringify({ token, refreshToken })
}); });
if (res.ok) {
if (!res.ok) {
refreshFailureCount++;
if (res.status === 400 || res.status === 401 || res.status === 403) {
clearTokens();
}
return;
}
const data = await res.json(); const data = await res.json();
if (data.success && data.token?.token && data.token?.refreshToken) { if (data.success && data.token?.token && data.token?.refreshToken) {
console.log('Token refreshed successfully');
setTokens(data.token.token, data.token.refreshToken); setTokens(data.token.token, data.token.refreshToken);
} else { } else {
console.log('Invalid tokens received during refresh'); refreshFailureCount++;
clearTokens(); if (!data.success) {
}
} else {
console.log('Failed to refresh token');
clearTokens(); clearTokens();
} }
} }
console.log('Token is still valid, no refresh needed'); } catch {
refreshFailureCount++;
}
} }
export function startTokenRefreshInterval() { export function startTokenRefreshInterval() {
@@ -100,3 +146,24 @@ export function clearServerTokens(cookies: Cookies) {
cookies.delete('token', { path: '/' }); cookies.delete('token', { path: '/' });
cookies.delete('refreshToken', { path: '/' }); cookies.delete('refreshToken', { path: '/' });
} }
export function getUserFromToken(token: string): JWTUser | null {
try {
const payload = JSON.parse(atob(token.split('.')[1]));
return {
uuid: payload.uuid,
username: payload.username,
displayname: payload.displayname,
totpEnabled: payload.totp_enabled === 'True',
roles: typeof payload.roles === 'string' ? parseInt(payload.roles, 10) : payload.roles,
isBanned: payload.is_banned === 'True'
};
} catch {
return null;
}
}
export const hasRole = (userRoles: number, role: number) => (userRoles & role) !== 0;
export const getUserRoles = (userRoles: number): Role[] =>
(Object.keys(roles) as Role[]).filter((role) => hasRole(userRoles, roles[role]));
+37 -27
View File
@@ -1,10 +1,21 @@
import { argon2id } from 'hash-wasm'; import { argon2id } from 'hash-wasm';
const BASE64_CHUNK_SIZE = 0x8000;
const SALT_LENGTH = 16;
const IV_LENGTH = 12;
const ARGON2_MEMORY_SIZE = 262144;
const ARGON2_ITERATIONS = 3;
const ARGON2_PARALLELISM = 1;
const ARGON2_HASH_LENGTH = 32;
const AES_KEY_LENGTH = 256;
const ENCRYPTION_AAD = 'enc-v4';
const ENCRYPTED_DATA_OVERHEAD = 60;
const ENCRYPTED_METADATA_OVERHEAD = 150;
function toBase64(bytes: Uint8Array): string { function toBase64(bytes: Uint8Array): string {
let binary = ''; let binary = '';
const chunkSize = 0x8000; for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) {
for (let i = 0; i < bytes.length; i += chunkSize) { binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK_SIZE));
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
} }
return btoa(binary); return btoa(binary);
} }
@@ -20,34 +31,32 @@ function fromBase64(data: string): Uint8Array {
export async function encryptAES(content: string, password: string): Promise<string> { export async function encryptAES(content: string, password: string): Promise<string> {
const enc = new TextEncoder(); const enc = new TextEncoder();
const salt = window.crypto.getRandomValues(new Uint8Array(32)); const salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
const memorySize = 65536;
const iterations = 3;
const parallelism = 1;
const keyMaterial = await argon2id({ const keyMaterial = await argon2id({
password, password,
salt, salt,
iterations, iterations: ARGON2_ITERATIONS,
memorySize, memorySize: ARGON2_MEMORY_SIZE,
parallelism, parallelism: ARGON2_PARALLELISM,
hashLength: 32, hashLength: ARGON2_HASH_LENGTH,
outputType: 'binary' outputType: 'binary'
}); });
const key = await window.crypto.subtle.importKey( const key = await window.crypto.subtle.importKey(
'raw', 'raw',
keyMaterial as unknown as BufferSource, new Uint8Array(keyMaterial),
{ name: 'AES-GCM' }, { name: 'AES-GCM', length: AES_KEY_LENGTH },
false, false,
['encrypt'] ['encrypt']
); );
const iv = window.crypto.getRandomValues(new Uint8Array(12)); const iv = window.crypto.getRandomValues(new Uint8Array(IV_LENGTH));
const encryptedContent = await window.crypto.subtle.encrypt( const encryptedContent = await window.crypto.subtle.encrypt(
{ {
name: 'AES-GCM', name: 'AES-GCM',
iv iv,
additionalData: enc.encode(ENCRYPTION_AAD)
}, },
key, key,
enc.encode(content) enc.encode(content)
@@ -61,9 +70,9 @@ export async function encryptAES(content: string, password: string): Promise<str
return JSON.stringify({ return JSON.stringify({
version: 4, version: 4,
kdf: 'Argon2id', kdf: 'Argon2id',
memorySize, memorySize: ARGON2_MEMORY_SIZE,
iterations, iterations: ARGON2_ITERATIONS,
parallelism, parallelism: ARGON2_PARALLELISM,
algorithm: 'AES-GCM', algorithm: 'AES-GCM',
saltLength: salt.byteLength, saltLength: salt.byteLength,
ivLength: iv.byteLength, ivLength: iv.byteLength,
@@ -73,9 +82,9 @@ export async function encryptAES(content: string, password: string): Promise<str
export function estimateEncryptedSize(content: string): number { export function estimateEncryptedSize(content: string): number {
const rawSize = new TextEncoder().encode(content).length; const rawSize = new TextEncoder().encode(content).length;
const combinedSize = rawSize + 60; const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
const b64Size = Math.ceil(combinedSize / 3) * 4; const b64Size = Math.ceil(combinedSize / 3) * 4;
return b64Size + 150; return b64Size + ENCRYPTED_METADATA_OVERHEAD;
} }
export async function decryptAES(result: string, password: string): Promise<string | null> { export async function decryptAES(result: string, password: string): Promise<string | null> {
@@ -84,8 +93,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
const combined = fromBase64(parsed.data); const combined = fromBase64(parsed.data);
const saltLength = parsed.saltLength || 16; const saltLength = parsed.saltLength || SALT_LENGTH;
const ivLength = parsed.ivLength || 12; const ivLength = parsed.ivLength || IV_LENGTH;
const salt = combined.slice(0, saltLength); const salt = combined.slice(0, saltLength);
const iv = combined.slice(saltLength, saltLength + ivLength); const iv = combined.slice(saltLength, saltLength + ivLength);
const data = combined.slice(saltLength + ivLength); const data = combined.slice(saltLength + ivLength);
@@ -99,7 +108,7 @@ export async function decryptAES(result: string, password: string): Promise<stri
iterations: parsed.iterations, iterations: parsed.iterations,
memorySize: parsed.memorySize, memorySize: parsed.memorySize,
parallelism: parsed.parallelism, parallelism: parsed.parallelism,
hashLength: 32, hashLength: ARGON2_HASH_LENGTH,
outputType: 'binary' outputType: 'binary'
}); });
} else { } else {
@@ -118,7 +127,7 @@ export async function decryptAES(result: string, password: string): Promise<stri
hash: parsed.hash hash: parsed.hash
}, },
baseKey, baseKey,
{ name: 'AES-GCM', length: 256 }, { name: 'AES-GCM', length: AES_KEY_LENGTH },
true, true,
['encrypt', 'decrypt'] ['encrypt', 'decrypt']
); );
@@ -127,8 +136,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
const key = await window.crypto.subtle.importKey( const key = await window.crypto.subtle.importKey(
'raw', 'raw',
keyMaterial as unknown as BufferSource, new Uint8Array(keyMaterial),
{ name: 'AES-GCM' }, { name: 'AES-GCM', length: AES_KEY_LENGTH },
false, false,
['decrypt'] ['decrypt']
); );
@@ -136,7 +145,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
const decryptedContent = await window.crypto.subtle.decrypt( const decryptedContent = await window.crypto.subtle.decrypt(
{ {
name: 'AES-GCM', name: 'AES-GCM',
iv iv,
additionalData: enc.encode(ENCRYPTION_AAD)
}, },
key, key,
data data
+31 -1
View File
@@ -3,6 +3,8 @@ import createDOMPurify from 'dompurify';
import type { WindowLike } from 'dompurify'; import type { WindowLike } from 'dompurify';
import { trustedDomains } from '$lib/consts'; import { trustedDomains } from '$lib/consts';
export const externalMediaWarningStorageKey = 'sharpbin:ignore-external-media-warning';
const tagMap: Record<string, string> = { const tagMap: Record<string, string> = {
IMG: 'image', IMG: 'image',
VIDEO: 'video', VIDEO: 'video',
@@ -10,6 +12,18 @@ const tagMap: Record<string, string> = {
IFRAME: 'iframe' IFRAME: 'iframe'
}; };
export function getIgnoreExternalMediaWarning(): boolean {
if (typeof window === 'undefined') return false;
return window.localStorage.getItem(externalMediaWarningStorageKey) === 'true';
}
export function setIgnoreExternalMediaWarning(ignore: boolean) {
if (typeof window === 'undefined') return;
window.localStorage.setItem(externalMediaWarningStorageKey, ignore ? 'true' : 'false');
}
export async function parseMarkdown( export async function parseMarkdown(
md: string, md: string,
preventExternal: boolean = true, preventExternal: boolean = true,
@@ -80,6 +94,14 @@ export async function parseMarkdown(
'background-color: #404040; color: white; padding: 0.25rem 0.75rem; border-radius: 0.25rem; cursor: pointer; text-decoration: none;' 'background-color: #404040; color: white; padding: 0.25rem 0.75rem; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
); );
const ignoreButton = dom.document.createElement('button');
ignoreButton.textContent = "Don't warn again";
ignoreButton.className = 'ignore-media-warning-btn';
ignoreButton.setAttribute(
'style',
'background-color: transparent; color: #d4d4d8; padding: 0.25rem 0.75rem; border: 1px solid #525252; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
);
if (element.getAttribute('alt')) if (element.getAttribute('alt'))
button.setAttribute('data-alt', element.getAttribute('alt') || ''); button.setAttribute('data-alt', element.getAttribute('alt') || '');
if (element.getAttribute('title')) if (element.getAttribute('title'))
@@ -89,9 +111,17 @@ export async function parseMarkdown(
if (element.getAttribute('height')) if (element.getAttribute('height'))
button.setAttribute('data-height', element.getAttribute('height') || ''); button.setAttribute('data-height', element.getAttribute('height') || '');
const actions = dom.document.createElement('span');
actions.setAttribute(
'style',
'display: flex; gap: 0.5rem; justify-content: center; flex-wrap: wrap;'
);
actions.appendChild(button);
actions.appendChild(ignoreButton);
placeholder.appendChild(warning); placeholder.appendChild(warning);
placeholder.appendChild(subWarning); placeholder.appendChild(subWarning);
placeholder.appendChild(button); placeholder.appendChild(actions);
const parent = element.parentNode; const parent = element.parentNode;
if (parent && parent.nodeName === 'A') { if (parent && parent.nodeName === 'A') {
+40 -11
View File
@@ -1,5 +1,10 @@
import { syntaxes } from '$lib/consts'; import { syntaxes } from '$lib/consts';
/**
* @param bytes Bytes to format.
* @param decimals Number of decimal places to include for non-integer values. Defaults to 2.
* @returns A human readable string representing the byte size, e.g. "1.5 MB".
*/
export function formatBytes(bytes: number, decimals = 2): string { export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes'; if (bytes === 0) return '0 Bytes';
@@ -15,6 +20,10 @@ export function formatBytes(bytes: number, decimals = 2): string {
return `${formattedValue} ${unitLabel}`; return `${formattedValue} ${unitLabel}`;
} }
/**
* @param num The number to format with commas as thousand separators.
* @returns The formatted number as a string with commas. For example, 1234567 becomes "1,234,567".
*/
export function formatNumber(num: number): string { export function formatNumber(num: number): string {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
} }
@@ -61,13 +70,21 @@ export function extractError(resData: unknown): string | null {
export function syntaxFromExtension(extension: string): string | null { export function syntaxFromExtension(extension: string): string | null {
const ext = extension.startsWith('.') ? extension.slice(1) : extension; const ext = extension.startsWith('.') ? extension.slice(1) : extension;
for (const [key, value] of Object.entries(syntaxes)) { for (const [key, value] of Object.entries(syntaxes)) {
if (value.extension === `.${ext}`) { if (value.extension.toLowerCase() === ext.toLowerCase()) {
return key; return key;
} }
} }
return null; return null;
} }
/**
* @param date The date to compare to the current time.
* @param useSuffix Whether to include "ago" or "from now" suffixes. Defaults to true.
* @param full Whether to return a full breakdown of all time units (e.g. "1 year, 2 months, 3 days ago") or just the largest unit (e.g. "1 year ago"). Defaults to false.
* @param nowArg Optional date to use as the current time for comparison, useful for testing. Defaults to the actual current time.
* @param accuracy The maximum number of time units to include in the output when full is true. For example, with an accuracy of 2, you might get "1 year, 2 months ago" but not "1 year, 2 months, 3 days ago". Defaults to 1.
* @returns A human readable relative time string.
*/
export function dateToRelativeString( export function dateToRelativeString(
date: Date, date: Date,
useSuffix = true, useSuffix = true,
@@ -96,7 +113,7 @@ export function dateToRelativeString(
return `${count} ${unit.name}${count > 1 ? 's' : ''} ${suffix}`.trim(); return `${count} ${unit.name}${count > 1 ? 's' : ''} ${suffix}`.trim();
} }
} }
return `0 seconds ${suffix}`.trim(); return useSuffix ? 'just now' : '0 seconds';
} }
const parts: string[] = []; const parts: string[] = [];
let acc = 0; let acc = 0;
@@ -109,12 +126,21 @@ export function dateToRelativeString(
acc++; acc++;
} }
} }
if (parts.length === 0) parts.push('0 seconds'); if (parts.length === 0) return useSuffix ? 'just now' : '0 seconds';
return `${parts.join(', ')} ${suffix}`.trim(); return `${parts.join(', ')} ${suffix}`.trim();
} }
export function tooltip(node: HTMLElement, text: string) { /**
let currentText = text ?? ''; * @param node The HTML element to attach the tooltip to.
* @param params The tooltip text, or an array where the first element is the tooltip text and the second element is a boolean indicating whether to use a darker background for the tooltip.
* @returns An object with update and destroy methods to manage the tooltip lifecycle.
* @example
* <button use:tooltip="This is a tooltip">Hover me</button>
* <button use:tooltip={["This is a darker tooltip", true]}>Hover me</button>
*/
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 tooltipEl: HTMLDivElement | null = null;
let caretEl: HTMLDivElement | null = null; let caretEl: HTMLDivElement | null = null;
let showTimeout: ReturnType<typeof setTimeout>; let showTimeout: ReturnType<typeof setTimeout>;
@@ -123,8 +149,9 @@ export function tooltip(node: HTMLElement, text: string) {
function createTooltip() { function createTooltip() {
if (!currentText || currentText.trim() === '') return; if (!currentText || currentText.trim() === '') return;
const el = document.createElement('div'); const el = document.createElement('div');
el.className = el.className = `fixed z-50 rounded ${
'fixed z-50 rounded bg-neutral-800 px-2 py-1 text-sm text-white shadow-lg opacity-0 transition-opacity duration-150'; 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.maxWidth = '90%';
el.style.wordBreak = 'break-word'; el.style.wordBreak = 'break-word';
@@ -219,10 +246,10 @@ export function tooltip(node: HTMLElement, text: string) {
caretEl.style.borderLeft = '7px solid transparent'; caretEl.style.borderLeft = '7px solid transparent';
caretEl.style.borderRight = '7px solid transparent'; caretEl.style.borderRight = '7px solid transparent';
if (caretOnTop) { if (caretOnTop) {
caretEl.style.borderBottom = '7px solid #27272a'; caretEl.style.borderBottom = `7px solid ${darker ? '#171717' : '#27272a'}`;
caretEl.style.borderTop = ''; caretEl.style.borderTop = '';
} else { } else {
caretEl.style.borderTop = '7px solid #27272a'; caretEl.style.borderTop = `7px solid ${darker ? '#171717' : '#27272a'}`;
caretEl.style.borderBottom = ''; caretEl.style.borderBottom = '';
} }
} }
@@ -260,8 +287,10 @@ export function tooltip(node: HTMLElement, text: string) {
window.addEventListener('resize', mouseOut, true); window.addEventListener('resize', mouseOut, true);
return { return {
update(newText: string) { update(newParams: string | [string, boolean?]) {
currentText = newText ?? ''; currentText = typeof newParams === 'string' ? newParams : (newParams[0] ?? '');
darker = typeof newParams === 'string' ? false : (newParams[1] ?? false);
if (!currentText || currentText.trim() === '') { if (!currentText || currentText.trim() === '') {
if (tooltipEl) { if (tooltipEl) {
tooltipEl.remove(); tooltipEl.remove();
+3 -3
View File
@@ -10,9 +10,9 @@ export function parseTotpEnabled(tokenValue: string | null) {
} }
} }
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number[], nextRoles: number[]) { export function needsAdminTotp(totpEnabled: boolean, currentRoles: number, nextRoles: number) {
if (!totpEnabled) return false; if (!totpEnabled) return false;
const nextHasAdmin = nextRoles.includes(255); const nextHasAdmin = (nextRoles & 4) !== 0;
const alreadyAdmin = currentRoles.includes(255); const alreadyAdmin = (currentRoles & 4) !== 0;
return nextHasAdmin && !alreadyAdmin; return nextHasAdmin && !alreadyAdmin;
} }
@@ -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> </svelte:head>
<Navbar {data} /> <Navbar {data} />
<!-- <div class="h-15 w-full"></div> -->
<slot /> <slot />
<Footer /> <Footer />
+8 -16
View File
@@ -65,17 +65,9 @@
let max: number; let max: number;
let element = markdown ? markdownConatiner : textArea; let element = markdown ? markdownConatiner : textArea;
if (!markdown) { element.style.height = 'auto';
textArea.style.height = 'auto'; h = element.scrollHeight;
h = textArea.scrollHeight;
max = MAX_HEIGHT(); max = MAX_HEIGHT();
} else {
markdownConatiner.style.height = 'auto';
h = markdownConatiner.scrollHeight;
max = MAX_HEIGHT();
}
if (h > max) { if (h > max) {
element.style.height = max + 'px'; element.style.height = max + 'px';
@@ -140,9 +132,9 @@
data.auth?.cf_turnstile_site_key && data.auth?.cf_turnstile_site_key &&
window.turnstile window.turnstile
) { ) {
const token = window.turnstile.getResponse(); const verificationToken = window.turnstile.getResponse();
if (token) { if (verificationToken) {
params.append('token', token); params.append('verificationToken', verificationToken);
} }
} }
@@ -447,7 +439,7 @@
crypto.getRandomValues(bytes); crypto.getRandomValues(bytes);
password = Array.from(bytes, (b) => chars[b % chars.length]).join(''); password = Array.from(bytes, (b) => chars[b % chars.length]).join('');
}} }}
use:tooltip={'Generate Random Password'} use:tooltip={['Generate Random Password', true]}
> >
<Dices class="h-5 w-5" /> <Dices class="h-5 w-5" />
</button> </button>
@@ -481,7 +473,7 @@
{/if} {/if}
<button <button
type="submit" type="submit"
disabled={$user?.roles && $user.roles.includes(403)} disabled={$user?.isBanned}
class="mb-2 w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400" class="mb-2 w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
>Create Paste</button >Create Paste</button
> >
@@ -493,7 +485,7 @@
{error} {error}
</div> </div>
{/if} {/if}
{#if $user?.roles && $user.roles.includes(403)} {#if $user?.isBanned}
<div <div
transition:fly={{ y: 40, duration: 300 }} transition:fly={{ y: 40, duration: 300 }}
class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200" class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
@@ -0,0 +1,223 @@
import { syntaxes } from '$lib/consts';
import { apiUrl } from '$lib/server/api';
import {
getCachedOgImage,
getCacheControlHeader,
getCacheTtlSeconds,
scheduleOgImageCachePurge,
storeCachedOgImage
} from '$lib/server/og/cache';
import OgPasteEmbed from '$lib/server/og/PasteEmbed.svelte';
import type { PasteEmbedProps } from '$lib/server/og/pasteEmbed';
import type { Paste } from '$lib/types/paste';
import {
dateToRelativeString,
extractDateFromUUIDv7,
formatBytes,
formatNumber
} from '$lib/utils/misc';
import { Resvg } from '@resvg/resvg-js';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import satori from 'satori';
import { html } from 'satori-html';
import sharp from 'sharp';
import type { Component } from 'svelte';
import { render } from 'svelte/server';
import type { RequestHandler } from './$types';
const WIDTH = 1200;
const HEIGHT = 630;
const require = createRequire(import.meta.url);
type FontConfig = {
name: string;
data: Buffer;
weight: 400 | 700;
style: 'normal';
};
type GeneratedImage = {
jpg: Buffer;
cacheControl: string;
};
const generationInFlight = new Map<string, Promise<GeneratedImage>>();
const visibilityLabels: Record<Paste['visibility'], string> = {
0: 'Public',
1: 'Unlisted',
2: 'Private'
};
const fontsPromise: Promise<FontConfig[]> = Promise.all([
readFile(require.resolve('@fontsource/inter/files/inter-latin-400-normal.woff')),
readFile(require.resolve('@fontsource/inter/files/inter-latin-700-normal.woff')),
readFile(require.resolve('@fontsource/jetbrains-mono/files/jetbrains-mono-latin-400-normal.woff'))
]).then(([inter400, inter700, mono400]) => [
{ name: 'Inter', data: inter400, weight: 400, style: 'normal' },
{ name: 'Inter', data: inter700, weight: 700, style: 'normal' },
{ name: 'JetBrains Mono', data: mono400, weight: 400, style: 'normal' }
]);
function getPreviewLines(content: string): string[] {
return content
.split('\n')
.slice(0, 15)
.map((line) => {
const normalized = line.replace(/\t/g, ' ');
return normalized.length > 86 ? `${normalized.slice(0, 83)}...` : normalized;
});
}
const entityMap: Record<string, string> = {
lt: '<',
gt: '>',
amp: '&',
quot: '"',
'#39': "'",
'#x27': "'"
};
// satori sanitizes html but doesnt render them properly (stays as &lt; for example)
// so replace sanitized entities with the actual characters
function decodeHtmlEntities(value: string): string {
let output = value;
for (;;) {
const next = output.replace(
/&(lt|gt|amp|quot|#39|#x27);/g,
(_, entity: string) => entityMap[entity]
);
if (next === output) return next;
output = next;
}
}
function normalizeSatoriTextNodes(node: unknown): unknown {
if (typeof node === 'string') return decodeHtmlEntities(node);
if (Array.isArray(node)) return node.map(normalizeSatoriTextNodes);
if (!node || typeof node !== 'object') return node;
const props = (node as { props?: { children?: unknown } }).props;
if (props && 'children' in props) {
props.children = normalizeSatoriTextNodes(props.children);
}
if (props && Array.isArray(props.children) && props.children.length === 0) {
delete (props as Record<string, unknown>).children;
}
return node;
}
export const GET: RequestHandler = async ({ params, fetch }) => {
const id = params.id;
if (!id) {
return new Response('Missing paste id.', { status: 400 });
}
scheduleOgImageCachePurge();
const cachedImage = await getCachedOgImage(id);
if (cachedImage) {
return new Response(new Uint8Array(cachedImage.jpg), {
headers: {
'Content-Type': 'image/jpeg',
'Cache-Control': getCacheControlHeader(cachedImage.ttlSeconds)
}
});
}
const existingGeneration = generationInFlight.get(id);
if (existingGeneration) {
const generated = await existingGeneration;
return new Response(new Uint8Array(generated.jpg), {
headers: {
'Content-Type': 'image/jpeg',
'Cache-Control': generated.cacheControl
}
});
}
const generation = (async (): Promise<GeneratedImage> => {
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`);
if (!pasteRes.ok) {
throw new Response('Paste not found.', { status: pasteRes.status === 404 ? 404 : 500 });
}
const pasteData = (await pasteRes.json()) as { paste?: Paste };
const paste = pasteData.paste;
if (!paste) {
throw new Response('Invalid paste response.', { status: 500 });
}
const isEncrypted = paste.visibility === 2;
let rawContent = '';
if (!isEncrypted) {
const rawRes = await fetch(`${apiUrl}/api/paste/${id}/raw`);
rawContent = rawRes.ok ? await rawRes.text() : '';
}
const content = rawContent || 'No content available.';
const created = paste.createdAt ? new Date(paste.createdAt) : extractDateFromUUIDv7(paste.uuid);
const metadata: PasteEmbedProps['metadata'] = [
{ icon: 'size', value: formatBytes(paste.trueSize) },
{
icon: 'views',
value: `${formatNumber(paste.views)} view${paste.views === 1 ? '' : 's'}`
},
{ icon: 'created', value: created ? created.toLocaleDateString() : 'Unknown' },
...(paste.expiresAt
? [
{
icon: 'expires' as const,
value: `Expires in ${dateToRelativeString(new Date(paste.expiresAt), false)}`
}
]
: []),
{ icon: 'syntax', value: syntaxes[paste.syntax]?.name ?? paste.syntax },
{ icon: `visibility-${paste.visibility}`, value: visibilityLabels[paste.visibility] }
];
const props: PasteEmbedProps = {
title: paste.title?.trim() || 'Untitled Paste',
uploader: paste.author?.username ?? 'Anonymous Uploader',
metadata,
previewLines: isEncrypted ? [] : getPreviewLines(content),
isEncrypted
};
const fonts = await fontsPromise;
const markup = render(OgPasteEmbed as unknown as Component<PasteEmbedProps>, { props }).body;
const satoriNode = normalizeSatoriTextNodes(html(markup));
const svg = await satori(satoriNode, { width: WIDTH, height: HEIGHT, fonts });
const png = new Resvg(svg, { fitTo: { mode: 'width', value: WIDTH } }).render().asPng();
const jpg = await sharp(png).jpeg({ quality: 92, mozjpeg: true }).toBuffer();
const cacheTtlSeconds = getCacheTtlSeconds(paste.expiresAt);
const cacheControl = getCacheControlHeader(cacheTtlSeconds);
await storeCachedOgImage({ id, jpg, pasteExpiresAt: paste.expiresAt ?? null }).catch(
() => undefined
);
return { jpg, cacheControl };
})();
generationInFlight.set(id, generation);
try {
const generated = await generation;
return new Response(new Uint8Array(generated.jpg), {
headers: {
'Content-Type': 'image/jpeg',
'Cache-Control': generated.cacheControl
}
});
} catch (error) {
if (error instanceof Response) {
return error;
}
throw error;
} finally {
generationInFlight.delete(id);
}
};
@@ -1,37 +1,33 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import type { Paste } from '$lib/types/paste'; import type { Paste } from '$lib/types/paste';
import { getServerToken } from '$lib/utils/auth'; import { getServerToken } from '$lib/utils/auth';
import { env } from '$env/dynamic/private'; import { apiUrl, viewInternalApiKey } from '$lib/server/api';
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050'; export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent, request }) => {
const apiKey =
env.NODE_ENV === 'development'
? 'cccdd42d9f2f648493e402f1da7c855ea798ad510e6bb9ea712dd7bed838e58'
: (env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '');
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent }) => {
const { id } = params; const { id } = params;
const parentData = await parent().catch(() => null); if (!id) {
// realistically this shouldnt happen
const token = getServerToken(cookies); throw error(400, 'Missing paste id.');
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, {
headers: {
Authorization: token ? `Bearer ${token}` : ''
} }
}); const parentData = await parent().catch(() => null);
const token = getServerToken(cookies);
const userAgent = request.headers.get('user-agent') ?? 'Sharpbin Client';
const clientHeaders = new Headers(request.headers);
clientHeaders.set('Authorization', token ? `Bearer ${token}` : '');
clientHeaders.set('User-Agent', userAgent);
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, { headers: clientHeaders });
if (pasteRes.status === 404) { if (pasteRes.status === 404) {
throw error(pasteRes.status, 'Paste not found.'); throw error(pasteRes.status, 'Paste not found.');
} }
const viewedHeaders = new Headers(clientHeaders);
viewedHeaders.set('X-Internal-API-Key', viewInternalApiKey);
const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, { const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, {
method: 'POST', method: 'POST',
headers: { headers: viewedHeaders
'X-Internal-API-Key': apiKey,
Authorization: token ? `Bearer ${token}` : ''
}
}); });
const pasteData = await pasteRes.json(); const pasteData = await pasteRes.json();
@@ -39,22 +35,17 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent
if (viewed.status === 200) { if (viewed.status === 200) {
const viewJson = await viewed.json(); const viewJson = await viewed.json();
if (viewJson.success === true && viewJson.message !== 'View already recorded.') { if (viewJson.success === true && viewJson.message === 'Paste view recorded.') {
pasteData.views += 1; pasteData.views += 1;
} }
} else { } else if (viewInternalApiKey === '') {
console.error(
`Failed to increment view count for paste ${id}, status code ${viewed.status}: ${await viewed.text()}`
);
if (apiKey === '') {
console.error( console.error(
'The API key for internal requests is not set. Please configure it in the environment variables.' 'The API key for internal requests is not set. Please configure it in the environment variables.'
); );
} }
}
const pasteContent = await fetch(`/api/paste/${id}/raw`); const pasteContent = await fetch(`${apiUrl}/api/paste/${id}/raw`, { headers: clientHeaders });
const pasteOptions = await fetch('/api/paste/info'); const pasteOptions = await fetch(`${apiUrl}/api/paste/info`, { headers: clientHeaders });
const options = await pasteOptions.json(); const options = await pasteOptions.json();
const content = await pasteContent.text(); const content = await pasteContent.text();
+75 -16
View File
@@ -23,7 +23,8 @@
Check, Check,
CalendarCog, CalendarCog,
Flag, Flag,
ArrowUp ArrowUp,
HatGlasses
} from '@lucide/svelte/icons/index'; } from '@lucide/svelte/icons/index';
import { import {
formatBytes, formatBytes,
@@ -33,16 +34,21 @@
tooltip, tooltip,
isBinaryData isBinaryData
} from '$lib/utils/misc'; } from '$lib/utils/misc';
import { parseMarkdown } from '$lib/utils/markdown'; import {
getIgnoreExternalMediaWarning,
parseMarkdown,
setIgnoreExternalMediaWarning
} from '$lib/utils/markdown';
import { syntaxes, expiresOptions } from '$lib/consts'; import { syntaxes, expiresOptions } from '$lib/consts';
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { decryptAES, encryptAES } from '$lib/utils/encryption'; import { decryptAES, encryptAES } from '$lib/utils/encryption';
import { fade } from 'svelte/transition'; import { fade } from 'svelte/transition';
import { getToken } from '$lib/utils/auth'; import { getToken, hasRole } from '$lib/utils/auth';
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import Dropdown from '$lib/components/Dropdown.svelte'; import Dropdown from '$lib/components/Dropdown.svelte';
import { openModal } from '$lib/stores/modal'; import { openModal } from '$lib/stores/modal';
import type { Paste } from '$lib/types/paste'; import type { Paste } from '$lib/types/paste';
import HighlightWorker from '$lib/workers/highlight.worker?worker';
export let data: PageData; export let data: PageData;
let reportSiteKey: string | null = null; let reportSiteKey: string | null = null;
@@ -59,6 +65,9 @@
let contentRendered = false; let contentRendered = false;
let downloadedPaste = false; let downloadedPaste = false;
let copiedPaste = false; let copiedPaste = false;
let highlightWorker: Worker | null = null;
let highlightRequestId = 0;
let ignoreExternalMediaWarning = false;
let scrollY = 0; let scrollY = 0;
@@ -90,10 +99,12 @@
}; };
onMount(() => { onMount(() => {
highlightWorker = new HighlightWorker();
interval = setInterval(() => { interval = setInterval(() => {
now = new Date(); now = new Date();
}, 1000); }, 1000);
return () => { return () => {
if (highlightWorker) highlightWorker.terminate();
if (interval) clearInterval(interval); if (interval) clearInterval(interval);
}; };
}); });
@@ -107,7 +118,7 @@
const numbered = lines const numbered = lines
.map( .map(
(line, i) => (line, i) =>
`<div class="code-row"><span class="line-number" style="width:${digits}ch">${i + 1}</span><span class="code-line">${line}</span></div>` `<div class="code-row"><span class="line-number" style="--digits:${digits}">${i + 1}</span><span class="code-line">${line}</span></div>`
) )
.join(''); .join('');
return html.replace(code, numbered); return html.replace(code, numbered);
@@ -127,7 +138,7 @@
switch (data.paste.syntax) { switch (data.paste.syntax) {
case 'markdown': case 'markdown':
pasteContent = await parseMarkdown(contentToRender); pasteContent = await parseMarkdown(contentToRender, !ignoreExternalMediaWarning);
contentRendered = true; contentRendered = true;
decryptStatus = ''; decryptStatus = '';
break; break;
@@ -147,6 +158,19 @@
const lang = (data.paste.syntax ?? '').toLowerCase(); const lang = (data.paste.syntax ?? '').toLowerCase();
let highlighted = ''; let highlighted = '';
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 { try {
if (lang === 'plaintext') { if (lang === 'plaintext') {
const escapeHtml = (s: string) => const escapeHtml = (s: string) =>
@@ -166,6 +190,7 @@
highlighted = hljs.highlightAuto(code).value; highlighted = hljs.highlightAuto(code).value;
} }
} }
}
const wrapped = `<pre><code class="hljs">${highlighted}</code></pre>`; const wrapped = `<pre><code class="hljs">${highlighted}</code></pre>`;
pasteContent = addLineNumbers(wrapped); pasteContent = addLineNumbers(wrapped);
contentRendered = true; contentRendered = true;
@@ -338,6 +363,13 @@
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
if (target.classList.contains('ignore-media-warning-btn')) {
ignoreExternalMediaWarning = true;
setIgnoreExternalMediaWarning(true);
renderPaste();
return;
}
if (target.classList.contains('load-media-btn')) { if (target.classList.contains('load-media-btn')) {
const src = target.getAttribute('data-src'); const src = target.getAttribute('data-src');
const tag = target.getAttribute('data-tag'); const tag = target.getAttribute('data-tag');
@@ -403,6 +435,8 @@
onMount(async () => { onMount(async () => {
try { try {
ignoreExternalMediaWarning = getIgnoreExternalMediaWarning();
if (data?.paste && data.paste.visibility === 2) { if (data?.paste && data.paste.visibility === 2) {
contentRendered = false; contentRendered = false;
decryptStatus = 'Preparing decryption...'; decryptStatus = 'Preparing decryption...';
@@ -460,6 +494,8 @@
$: reportSiteKey = $: reportSiteKey =
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions (data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null; ?.cf_turnstile_site_key ?? null;
$: pasteImageUrl =
data?.paste && data?.url ? `${new URL(data.url).origin}/${data.paste.id}.jpg` : null;
</script> </script>
<svelte:window bind:scrollY /> <svelte:window bind:scrollY />
@@ -483,6 +519,14 @@
<meta property="og:type" content="article" /> <meta property="og:type" content="article" />
<meta property="og:url" content={data.url} /> <meta property="og:url" content={data.url} />
<meta property="og:site_name" content="Sharpbin" /> <meta property="og:site_name" content="Sharpbin" />
{#if pasteImageUrl}
<meta property="og:image" content={pasteImageUrl} />
<meta property="og:image:type" content="image/jpeg" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content={pasteImageUrl} />
{/if}
<meta <meta
property="og:article:published_time" property="og:article:published_time"
content={extractDateFromUUIDv7(data.paste.uuid)?.toISOString() ?? ''} content={extractDateFromUUIDv7(data.paste.uuid)?.toISOString() ?? ''}
@@ -506,8 +550,7 @@
{#if data.paste} {#if data.paste}
<div class="mb-4 w-full text-center"> <div class="mb-4 w-full text-center">
<h1 <h1
class="mx-auto max-w-[90%] min-w-0 truncate text-3xl leading-tight font-bold sm:text-4xl" class="mx-auto max-w-[90%] min-w-0 text-3xl leading-tight font-bold wrap-break-word sm:text-4xl"
use:tooltip={data.paste.title && data.paste.title.length > 40 ? data.paste.title : ''}
> >
{#if !editing} {#if !editing}
{data.paste.title || 'Untitled Paste'} {data.paste.title || 'Untitled Paste'}
@@ -522,14 +565,15 @@
{/if} {/if}
</h1> </h1>
<div class="flex items-center justify-center gap-2 text-sm text-neutral-400"> <div class="flex items-center justify-center gap-2 text-sm text-neutral-400">
<User class="inline-block h-4 w-4 text-neutral-400" />
{#if data.paste.author} {#if data.paste.author}
<User class="inline-block h-4 w-4 text-neutral-400" />
<a <a
href={resolve(`/user/${data.paste.author.username}`)} href={resolve(`/user/${data.paste.author.username}`)}
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500" class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
>{data.paste.author.username}</a >{data.paste.author.username}</a
> >
{:else} {:else}
<HatGlasses class="inline-block h-4 w-4 text-neutral-400" />
<span class="text-neutral-400">Anonymous</span> <span class="text-neutral-400">Anonymous</span>
{/if} {/if}
</div> </div>
@@ -665,7 +709,7 @@
</div> </div>
</div> </div>
<div <div
class="sticky top-0 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row" class="sticky top-15 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row"
> >
{#if !isBinary} {#if !isBinary}
<div class="flex items-center gap-2 text-sm text-neutral-300"> <div class="flex items-center gap-2 text-sm text-neutral-300">
@@ -792,7 +836,7 @@
<span class="text-amber-300">Report</span> <span class="text-amber-300">Report</span>
</button> </button>
{/if} {/if}
{#if $user && ($user.uuid === data.paste?.author?.uuid || $user.roles.some((r) => r === 1 || r === 255))} {#if $user && ($user.uuid === data.paste?.author?.uuid || hasRole($user.roles, 2) || hasRole($user.roles, 4))}
{#if !editing} {#if !editing}
{#if !isBinary} {#if !isBinary}
<button <button
@@ -911,6 +955,7 @@
on:click={handleMarkdownClick} on:click={handleMarkdownClick}
role="presentation" role="presentation"
> >
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html pasteContent} {@html pasteContent}
</div> </div>
{/if} {/if}
@@ -923,6 +968,7 @@
<style> <style>
.hljs { .hljs {
background-color: var(--color-neutral-800) !important; background-color: var(--color-neutral-800) !important;
padding: 0 !important;
} }
.codeblock-with-lines { .codeblock-with-lines {
@@ -950,29 +996,42 @@
display: flex; display: flex;
align-items: flex-start; align-items: flex-start;
min-width: 0; min-width: 0;
padding: 0.1em 0; padding: 0;
border-radius: 0.15em;
} }
.code-row:hover { .code-row:hover {
background-color: rgba(255, 255, 255, 0.05); background-color: rgba(255, 255, 255, 0.05);
} }
.line-number { .line-number {
flex-shrink: 0; display: inline-flex;
align-self: stretch;
align-items: flex-start;
justify-content: flex-end;
flex: 0 0 calc(var(--digits, 1) * 1ch + 1.3em);
width: calc(var(--digits, 1) * 1ch + 1.3em);
box-sizing: border-box;
text-align: right; text-align: right;
color: #888; color: #888;
user-select: none; user-select: none;
margin-right: 1em; margin-right: 0;
font-family:
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',
monospace;
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
padding-top: 0.1em;
padding-bottom: 0.1em;
padding-right: 0.5em; padding-right: 0.5em;
padding-left: 0.25em; padding-left: 0.9em;
background: none; background: none;
border-right: 1px solid var(--color-neutral-700);
} }
.code-line { .code-line {
display: block; display: block;
white-space: pre-wrap; white-space: pre-wrap;
word-break: break-word; word-break: break-word;
overflow-wrap: anywhere; overflow-wrap: anywhere;
padding-left: 0.25em; padding-top: 0.1em;
padding-bottom: 0.1em;
padding-left: 0.9em;
min-width: 0; min-width: 0;
} }
+2 -1
View File
@@ -83,7 +83,8 @@ select {
color: #3b82f6; color: #3b82f6;
text-decoration: underline; text-decoration: underline;
} }
.markdown .load-media-btn:hover { .markdown .load-media-btn:hover,
.markdown .ignore-media-warning-btn:hover {
background-color: #525252 !important; background-color: #525252 !important;
} }
.markdown pre { .markdown pre {
@@ -1,14 +1,19 @@
import type { RequestHandler } from '@sveltejs/kit'; import type { RequestHandler } from '@sveltejs/kit';
import { apiUrl } from '$lib/server/api';
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050'; export const GET: RequestHandler = async ({ params, request }) => {
export const GET: RequestHandler = async ({ params }) => {
const { id } = params; const { id } = params;
const headers = new Headers(request.headers);
const res = await fetch(`${apiUrl}/api/paste/${id}/raw`); const res = await fetch(`${apiUrl}/api/paste/${id}/raw`, {
headers: headers
});
if (res.status === 404) { if (res.status === 404) {
return new Response('Paste not found', { status: 404 }); return new Response(null, {
status: 404,
statusText: 'Not Found'
});
} }
const content = await res.text(); const content = await res.text();
return new Response(content, { return new Response(content, {
@@ -3,9 +3,10 @@ import type { Paste } from '$lib/types/paste';
import { extractError } from '$lib/utils/misc'; import { extractError } from '$lib/utils/misc';
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ fetch }) => { export const load: PageServerLoad = async ({ fetch, request }) => {
try { try {
const res = await fetch('/api/paste/recent'); const headers = new Headers(request.headers);
const res = await fetch('/api/paste/recent', { headers });
if (!res.ok) { if (!res.ok) {
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.'; const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
throw error(res.status, errorMsg); throw error(res.status, errorMsg);
@@ -17,7 +17,7 @@
let passwordFocused = false; let passwordFocused = false;
let showPassword = false; let showPassword = false;
1;
let passwordChecks = { let passwordChecks = {
minLength: false, minLength: false,
maxLength: false, maxLength: false,
@@ -1,33 +1,24 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private'; import { apiUrl } from '$lib/server/api';
import { getServerToken } from '$lib/utils/auth'; import { getServerToken, clearServerTokens, roles, getUserFromToken } from '$lib/utils/auth';
import type { Report } from '$lib/types/report'; import type { Report } from '$lib/types/report';
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050'; export const load: PageServerLoad = async ({ fetch, cookies, params, url, request }) => {
function decodeJwtRoles(token?: string | null): number[] {
try {
if (!token) return [];
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const roles = payload?.role;
if (Array.isArray(roles)) {
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
}
return [];
} catch {
return [];
}
}
export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
const token = getServerToken(cookies); const token = getServerToken(cookies);
if (!token) throw error(401, 'Login required'); if (!token) throw error(401, 'Login required');
const roles = decodeJwtRoles(token);
const canEdit = roles.includes(1) || roles.includes(255);
const res = await fetch(`${API_URL}/api/report/${params.reportId}`, { const user = getUserFromToken(token);
headers: { Authorization: `Bearer ${token}` } if (!user) {
clearServerTokens(cookies);
throw error(401, 'Invalid token');
}
const canEdit = (user.roles & roles.Admin) !== 0 || (user.roles & roles.Moderator) !== 0;
const headers = new Headers(request.headers);
headers.set('Authorization', `Bearer ${token}`);
const res = await fetch(`${apiUrl}/api/report/${params.reportId}`, {
headers: headers
}); });
if (!res.ok) { if (!res.ok) {
@@ -36,7 +27,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
} }
const report = (await res.json()) as Report; const report = (await res.json()) as Report;
const optionsRes = await fetch(`${API_URL}/api/report/options`); const optionsRes = await fetch(`${apiUrl}/api/report/options`);
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] }; const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
return { report, url: url.href, canEdit, options }; return { report, url: url.href, canEdit, options };
@@ -1,37 +1,32 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private'; import { apiUrl } from '$lib/server/api';
import { getServerToken } from '$lib/utils/auth'; import {
getServerToken,
getUserFromToken,
clearServerTokens,
hasRole,
roles
} from '$lib/utils/auth';
import type { ReportListResponse } from '$lib/types/report'; import type { ReportListResponse } from '$lib/types/report';
import { extractError } from '$lib/utils/misc'; import { extractError } from '$lib/utils/misc';
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
function decodeJwtRoles(token?: string | null): number[] {
try {
if (!token) return [];
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const roles = payload?.role;
if (Array.isArray(roles)) {
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
}
return [];
} catch {
return [];
}
}
function normalizeTarget(value: string | null): 'all' | 'pastes' | 'users' { function normalizeTarget(value: string | null): 'all' | 'pastes' | 'users' {
if (value === 'pastes' || value === 'users') return value; if (value === 'pastes' || value === 'users') return value;
return 'all'; return 'all';
} }
export const load: PageServerLoad = async ({ fetch, cookies, url }) => { export const load: PageServerLoad = async ({ fetch, cookies, url, request }) => {
const token = getServerToken(cookies); const token = getServerToken(cookies);
if (!token) throw error(401, 'Login required'); if (!token) throw error(401, 'Login required');
const roles = decodeJwtRoles(token); const user = getUserFromToken(token);
if (!roles.includes(1) && !roles.includes(255)) { if (!user) {
clearServerTokens(cookies);
throw error(401, 'Invalid token');
}
if (!hasRole(user.roles, roles.Admin) && !hasRole(user.roles, roles.Moderator)) {
throw error(403, 'You do not have permission to view reports.'); throw error(403, 'You do not have permission to view reports.');
} }
@@ -49,8 +44,11 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
if ((target === 'pastes' || target === 'all') && pasteId) query.set('pasteId', pasteId); if ((target === 'pastes' || target === 'all') && pasteId) query.set('pasteId', pasteId);
if ((target === 'users' || target === 'all') && userUuid) query.set('userUUID', userUuid); if ((target === 'users' || target === 'all') && userUuid) query.set('userUUID', userUuid);
const reportsRes = await fetch(`${API_URL}/api/report/${target}?${query.toString()}`, { const headers = new Headers(request.headers);
headers: { Authorization: `Bearer ${token}` } headers.set('Authorization', `Bearer ${token}`);
const reportsRes = await fetch(`${apiUrl}/api/report/${target}?${query.toString()}`, {
headers: headers
}); });
if (!reportsRes.ok) { if (!reportsRes.ok) {
@@ -60,7 +58,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
const reports = (await reportsRes.json()) as ReportListResponse; const reports = (await reportsRes.json()) as ReportListResponse;
const optionsRes = await fetch(`${API_URL}/api/report/options`); const optionsRes = await fetch(`${apiUrl}/api/report/options`);
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] }; const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
return { return {
@@ -0,0 +1,21 @@
import type { PageServerLoad } from './$types';
import { apiUrl } from '$lib/server/api';
import { error, isHttpError } from '@sveltejs/kit';
import { extractError } from '$lib/utils/misc';
export const load: PageServerLoad = async ({ fetch }) => {
try {
const res = await fetch(`${apiUrl}/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>
@@ -1,25 +1,25 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit'; import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private'; import { apiUrl } from '$lib/server/api';
import { getServerToken } from '$lib/utils/auth'; import { getServerToken } from '$lib/utils/auth';
import type { User } from '$lib/types/user'; import type { User } from '$lib/types/user';
import type { Paste } from '$lib/types/paste'; import type { Paste } from '$lib/types/paste';
import type { Pagination } from '$lib/types/pagination'; import type { Pagination } from '$lib/types/pagination';
import type { Report, ReportListResponse } from '$lib/types/report'; import type { Report, ReportListResponse } from '$lib/types/report';
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050'; function decodeJwtRoles(token?: string | null): number {
function decodeJwtRoles(token?: string | null): number[] {
try { try {
if (!token) return []; if (!token) return 0;
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString()); const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const roles = payload?.role; const roles = payload?.role;
if (Array.isArray(roles)) { if (typeof roles === 'number') return roles;
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r)); if (typeof roles === 'string') {
const parsed = parseInt(roles, 10);
return isNaN(parsed) ? 0 : parsed;
} }
return []; return 0;
} catch { } catch {
return []; return 0;
} }
} }
@@ -34,14 +34,19 @@ function decodeJwtUuid(token?: string | null): string | null {
} }
} }
export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent }) => { export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent, request }) => {
const token = getServerToken(cookies); const token = getServerToken(cookies);
const { username } = params; const { username } = params;
const { options } = await parent(); const { options } = await parent();
const jwtUuid = decodeJwtUuid(token); const jwtUuid = decodeJwtUuid(token);
const asGuest = url.searchParams.get('guest') === '1';
const headers = new Headers(request.headers);
if (token && !asGuest) {
headers.set('Authorization', `Bearer ${token}`);
}
const res = await fetch(`${API_URL}/api/user/${username}`, { const res = await fetch(`${apiUrl}/api/user/${username}`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined headers: headers
}); });
if (!res.ok) { if (!res.ok) {
@@ -60,8 +65,8 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
const isOwner = jwtUuid ? user.uuid === jwtUuid : false; const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
let reportsTarget: ReportListResponse | null = null; let reportsTarget: ReportListResponse | null = null;
let reportsSubmitted: ReportListResponse | null = null; let reportsSubmitted: ReportListResponse | null = null;
const roles = token ? decodeJwtRoles(token) : []; const roles = token ? decodeJwtRoles(token) : 0;
const canModerate = roles.includes(255) || roles.includes(1); const canModerate = (roles & 4) !== 0 || (roles & 2) !== 0;
if (isOwner && reports && reportsPagination) { if (isOwner && reports && reportsPagination) {
reportsSubmitted = { reportsSubmitted = {
@@ -70,21 +75,21 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
}; };
} }
if (token && canModerate && (!reportsSubmitted || !isOwner)) { if (token && !asGuest && canModerate && (!reportsSubmitted || !isOwner)) {
const submittedRes = await fetch(`${API_URL}/api/user/${user.uuid}/reports/submitted`, { headers.set('Authorization', `Bearer ${token}`);
headers: { Authorization: `Bearer ${token}` } const submittedRes = await fetch(`${apiUrl}/api/user/${user.uuid}/reports/submitted`, {
headers: headers
}); });
if (submittedRes.ok) reportsSubmitted = await submittedRes.json(); if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
} }
if (token && !isOwner) { if (token && !asGuest && !isOwner && canModerate) {
if (canModerate) { headers.set('Authorization', `Bearer ${token}`);
const r = await fetch(`${API_URL}/api/user/${user.uuid}/reports`, { const r = await fetch(`${apiUrl}/api/user/${user.uuid}/reports`, {
headers: { Authorization: `Bearer ${token}` } headers: headers
}); });
if (r.ok) reportsTarget = await r.json(); if (r.ok) reportsTarget = await r.json();
} }
}
return { return {
user, user,
@@ -1,6 +1,7 @@
<script lang="ts"> <script lang="ts">
import { resolve } from '$app/paths'; import { resolve } from '$app/paths';
import { goto } from '$app/navigation'; import { goto, afterNavigate } from '$app/navigation';
import { page } from '$app/state';
import type { PageData } from './$types'; import type { PageData } from './$types';
import type { Pagination } from '$lib/types/pagination'; import type { Pagination } from '$lib/types/pagination';
import { import {
@@ -8,13 +9,17 @@
CalendarDays, CalendarDays,
ShieldUser, ShieldUser,
Ban, Ban,
File,
AtSign, AtSign,
Pencil, Pencil,
Trash2, Trash2,
Clock, Clock,
Hash, Hash,
Flag Flag,
LoaderCircle,
Check,
X,
Plus,
Copy
} from '@lucide/svelte'; } from '@lucide/svelte';
import { import {
extractDateFromUUIDv7, extractDateFromUUIDv7,
@@ -22,14 +27,14 @@
dateToRelativeString, dateToRelativeString,
extractError extractError
} from '$lib/utils/misc'; } from '$lib/utils/misc';
import { roles } from '$lib/consts'; import { getToken, hasRole, roles } from '$lib/utils/auth';
import { getToken } from '$lib/utils/auth';
import { needsAdminTotp } from '$lib/utils/totp'; import { needsAdminTotp } from '$lib/utils/totp';
import { openModal } from '$lib/stores/modal'; import { openModal } from '$lib/stores/modal';
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import Paste from '$lib/components/Paste.svelte'; import Paste from '$lib/components/Paste.svelte';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report'; import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
import { fade } from 'svelte/transition';
export let data: PageData; export let data: PageData;
@@ -47,17 +52,79 @@
let totpEnabled = false; let totpEnabled = false;
let now = new Date(); let now = new Date();
let interval: ReturnType<typeof setInterval> | null = null; let interval: ReturnType<typeof setInterval> | null = null;
let isEditingDisplayName = false;
let editDisplayNameValue = '';
let apiKeys: { uuid: string; name: string; createdAt: string; lastUsedAt: string | null }[] = [];
let successfullyFetchedApiKeys = false;
let newApiKeyName = '';
let newApiKeyValue = '';
let isCreatingApiKey = false;
let apiKeyError = '';
let copiedApiKey = false;
$: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false; $: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false;
$: totpEnabled = Boolean($user?.totpEnabled); $: totpEnabled = Boolean($user?.totpEnabled);
$: reportsSubmitted = data.reportsSubmitted; $: reportsSubmitted = data.reportsSubmitted;
$: reportsTarget = data.reportsTarget; $: reportsTarget = data.reportsTarget;
let activeTab: 'pastes' | 'reportsSubmitted' | 'reportsTarget' | 'settings' = isOwner
? 'settings'
: 'pastes';
async function updateTab(newPageTab: typeof activeTab) {
if (activeTab === newPageTab) return;
activeTab = newPageTab;
const url = new URL(page.url);
url.searchParams.set('tab', newPageTab);
// @ts-expect-error - resolve still works even though it's flagged as an error
// eslint-disable-next-line svelte/no-navigation-without-resolve
await goto(resolve(url.pathname) + url.search, {
replaceState: true,
noScroll: true,
keepFocus: true,
invalidateAll: false
});
if (newPageTab === 'settings' && isOwner && apiKeys.length === 0) {
await fetchApiKeys();
}
}
$: {
const tab = page.url.searchParams.get('tab');
switch (tab) {
case 'pastes':
activeTab = 'pastes';
break;
case 'reportsSubmitted':
if (reportsSubmitted) activeTab = 'reportsSubmitted';
else activeTab = 'pastes';
break;
case 'reportsTarget':
if (reportsTarget) activeTab = 'reportsTarget';
else activeTab = 'pastes';
break;
case 'settings':
if (isOwner || ($user?.roles && (hasRole($user.roles, 2) || hasRole($user.roles, 4)))) {
activeTab = 'settings';
} else activeTab = 'pastes';
break;
default:
if (isOwner) {
activeTab = 'settings';
} else {
activeTab = 'pastes';
}
}
}
const roleOptions = [ const roleOptions = [
{ label: 'Member', value: 0 }, { label: 'Member', value: 1 },
{ label: 'Moderator', value: 1 }, { label: 'Moderator', value: 2 },
{ label: 'Administrator', value: 255 }, { label: 'Administrator', value: 4 }
{ label: 'Banned', value: 403 }
]; ];
async function fetchPage(pageNum: number) { async function fetchPage(pageNum: number) {
@@ -78,11 +145,11 @@
loading = false; loading = false;
} }
async function handleUserUpdate(displayName?: string, selectedRoles?: number[]) { async function handleUserUpdate(displayName?: string, selectedRoles?: number) {
loading = true; loading = true;
modalError = ''; modalError = '';
const token = getToken(); const token = getToken();
const currentRoles = data.user?.roles ?? []; const currentRoles = data.user?.roles ?? 0;
const nextRoles = selectedRoles ?? currentRoles; const nextRoles = selectedRoles ?? currentRoles;
let totpcode = ''; let totpcode = '';
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) { if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) {
@@ -185,31 +252,131 @@
modalError = ''; modalError = '';
} }
async function openEditDisplayName() { async function saveDisplayName() {
const value = String( const value = editDisplayNameValue.trim();
await openModal<string>({
mode: 'prompt',
title: 'Edit Display Name',
maxInputLength: 26,
placeholder: 'New Display Name',
error: modalError,
cancelValue: ''
})
).trim();
if (!value) return; if (!value) return;
await handleUserUpdate(value); await handleUserUpdate(value);
isEditingDisplayName = false;
}
function startEditDisplayName() {
editDisplayNameValue = data.user?.displayName || data.user?.username || '';
isEditingDisplayName = true;
}
function cancelEditDisplayName() {
isEditingDisplayName = false;
editDisplayNameValue = '';
}
async function fetchApiKeys() {
const token = getToken();
if (!token) return;
if (apiKeys.length > 0) return;
if (successfullyFetchedApiKeys) return;
loading = true;
try {
const res = await fetch('/api/auth/apikey/list', {
headers: { Authorization: `Bearer ${token}` }
});
if (res.ok) {
const json = await res.json();
apiKeys = Array.isArray(json.apiKeys) ? json.apiKeys : [];
successfullyFetchedApiKeys = json.successfullyFetchedApiKeys ?? true;
}
} catch (e) {
console.error('Failed to fetch API keys', e);
} finally {
loading = false;
}
}
async function createApiKey() {
if (!newApiKeyName.trim()) return;
loading = true;
apiKeyError = '';
const token = getToken();
try {
const res = await fetch('/api/auth/apikey/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ name: newApiKeyName.trim() })
});
const json = await res.json();
if (res.ok) {
newApiKeyValue = json.apiKey.key;
apiKeys = [
...apiKeys,
{
uuid: json.apiKey.uuid,
name: json.apiKey.name,
createdAt: json.apiKey.createdAt,
lastUsedAt: null
}
];
newApiKeyName = '';
isCreatingApiKey = false;
} else {
apiKeyError = json.message || 'Failed to create API key';
}
} catch {
apiKeyError = 'Network error';
} finally {
loading = false;
}
}
async function deleteApiKey(uuid: string) {
const ok = await openModal<boolean>({
mode: 'confirm',
title: 'Delete API Key',
message: 'Are you sure you want to delete this API key? This action cannot be undone.',
confirmButtonText: 'Delete',
cancelValue: false
});
if (!ok) return;
loading = true;
apiKeyError = '';
const token = getToken();
try {
const res = await fetch(`/api/auth/apikey/${uuid}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${token}` }
});
if (res.ok) {
apiKeys = apiKeys.filter((k) => k.uuid !== uuid);
} else {
const json = await res.json();
apiKeyError = json.message || 'Failed to delete API key';
}
} catch {
apiKeyError = 'Network error';
} finally {
loading = false;
}
} }
async function openEditRoles() { async function openEditRoles() {
const currentRoleBitfield = data.user?.roles ?? 0;
const selectedValues: number[] = [];
if (hasRole(currentRoleBitfield, roles.User)) selectedValues.push(roles.User);
if (hasRole(currentRoleBitfield, roles.Moderator)) selectedValues.push(roles.Moderator);
if (hasRole(currentRoleBitfield, roles.Admin)) selectedValues.push(roles.Admin);
const value = await openModal({ const value = await openModal({
mode: 'multiselect', mode: 'multiselect',
title: 'Edit User Roles', title: 'Edit User Roles',
items: roleOptions, items: roleOptions,
initialValue: data.user?.roles, initialValue: selectedValues,
cancelValue: null cancelValue: null
}); });
if (!Array.isArray(value)) return; if (!Array.isArray(value)) return;
await handleUserUpdate(undefined, value as number[]); const bitfield = value.reduce((acc, val) => acc | val, 0);
await handleUserUpdate(undefined, bitfield);
} }
async function openDeleteAccount() { async function openDeleteAccount() {
@@ -240,11 +407,24 @@
interval = setInterval(() => { interval = setInterval(() => {
now = new Date(); now = new Date();
}, 1000); }, 1000);
const tab = page.url.searchParams.get('tab');
if ((tab === 'settings' || !tab) && isOwner) {
fetchApiKeys();
}
return () => { return () => {
if (interval) clearInterval(interval); if (interval) clearInterval(interval);
}; };
}); });
afterNavigate(() => {
const tab = page.url.searchParams.get('tab');
if ((tab === 'settings' || !tab) && isOwner && apiKeys.length === 0) {
fetchApiKeys();
}
});
$: reportSiteKey = $: reportSiteKey =
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions (data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null; ?.cf_turnstile_site_key ?? null;
@@ -275,20 +455,24 @@
> >
<div class="relative w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6"> <div class="relative w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="flex flex-wrap items-center justify-center gap-4 text-center text-4xl font-bold"> <h1 class="flex flex-wrap items-center justify-center gap-4 text-center text-4xl font-bold">
{#if data.user?.roles?.includes(403)} {#if data.user?.isBanned}
<span <span
class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full" class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full"
use:tooltip={roles[403]} use:tooltip={'Banned'}
> >
<User class="h-8 w-8 text-neutral-500" /> <User class="h-8 w-8 text-neutral-500" />
<Ban class="absolute h-7 w-7 text-red-500" /> <Ban class="absolute h-7 w-7 text-red-500" />
</span> </span>
{:else if data.user?.roles?.includes(1) || data.user?.roles?.includes(255)} {:else if data.user?.roles && (hasRole(data.user.roles, roles.Admin) || hasRole(data.user.roles, roles.Moderator))}
{#if data.user?.roles?.length} <span
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}> use:tooltip={hasRole(data.user.roles, roles.Admin)
? 'Admin'
: hasRole(data.user.roles, roles.Moderator)
? 'Moderator'
: 'User'}
>
<ShieldUser class="h-8 w-8 text-neutral-400" /> <ShieldUser class="h-8 w-8 text-neutral-400" />
</span> </span>
{/if}
{:else} {:else}
<span use:tooltip={'User'}> <span use:tooltip={'User'}>
<User class="h-8 w-8 text-neutral-400" /> <User class="h-8 w-8 text-neutral-400" />
@@ -317,33 +501,7 @@
Joined {extractDateFromUUIDv7(data.user?.uuid)?.toLocaleDateString() ?? 'Unknown'} Joined {extractDateFromUUIDv7(data.user?.uuid)?.toLocaleDateString() ?? 'Unknown'}
</span> </span>
</div> </div>
<div class="flex shrink-0 items-center">
<File class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{pagination.totalCount} paste{pagination.totalCount !== 1 ? 's' : ''}</span
>
</div>
{#if reportsSubmitted}
<div class="flex shrink-0 items-center">
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{reportsSubmitted.pagination.totalCount} submitted report{reportsSubmitted.pagination
.totalCount !== 1
? 's'
: ''}</span
>
</div>
{/if}
{#if reportsTarget}
<div class="flex shrink-0 items-center">
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{reportsTarget.pagination.totalCount} report{reportsTarget.pagination.totalCount !== 1
? 's'
: ''}</span
>
</div>
{/if}
<div class="flex shrink-0 items-center"> <div class="flex shrink-0 items-center">
<Hash class="mr-1 h-6 w-6 text-neutral-400" /> <Hash class="mr-1 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400" use:tooltip={`User #${data.user?.uid}`}> <span class="text-neutral-400" use:tooltip={`User #${data.user?.uid}`}>
@@ -362,7 +520,7 @@
</div> </div>
{/if} {/if}
</div> </div>
{#if !isOwner && !$user?.roles?.some((r) => r === 403)} {#if !isOwner && !$user?.isBanned}
<!-- svelte-ignore a11y_click_events_have_key_events --> <!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions --> <!-- svelte-ignore a11y_no_static_element_interactions -->
<div <div
@@ -381,47 +539,377 @@
<Flag class="m-4 h-6 w-6 cursor-pointer text-neutral-400 hover:text-amber-400" /> <Flag class="m-4 h-6 w-6 cursor-pointer text-neutral-400 hover:text-amber-400" />
</div> </div>
{/if} {/if}
{#if isOwner || $user?.roles?.some((r) => r === 255 || r === 1)} <div class="mt-8 flex w-full border-b border-neutral-800">
<div class="mt-4 flex flex-wrap justify-center gap-2"> {#if isOwner || ($user?.roles && (hasRole($user.roles, roles.Admin) || hasRole($user.roles, roles.Moderator)))}
<button <button
on:click={openEditDisplayName} class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'settings'
? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}"
on:click={() => updateTab('settings')}
>
Settings
</button>
{/if}
<button
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'pastes'
? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}"
on:click={() => updateTab('pastes')}
>
Pastes
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
>{pagination.totalCount}</span
>
</button>
{#if reportsSubmitted}
<button
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'reportsSubmitted'
? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}"
on:click={() => updateTab('reportsSubmitted')}
>
Submitted Reports
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
>{reportsSubmitted.pagination.totalCount}</span
>
</button>
{/if}
{#if reportsTarget}
<button
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
'reportsTarget'
? 'border-neutral-200 text-white'
: 'border-transparent text-neutral-400'}"
on:click={() => updateTab('reportsTarget')}
>
Reports Against User
<span class="ml-2 rounded bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
>{reportsTarget.pagination.totalCount}</span
>
</button>
{/if}
</div>
<div class="relative mt-4 min-h-50 w-full">
{#if loading}
<div
class="absolute inset-0 z-10 flex items-center justify-center bg-neutral-900/50 backdrop-blur-sm"
>
<LoaderCircle class="h-8 w-8 animate-spin text-neutral-200" />
</div>
{/if}
{#if activeTab === 'settings'}
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
<div class="col-span-2">
<div class="rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start">
<div>
<h2 class="text-xl font-semibold text-neutral-100">Display Name</h2>
<p class="mt-1 text-sm text-neutral-400">
{isOwner
? 'Your display name is shown publicly on your profile and pastes.'
: "This user's display name is shown publicly on their profile and pastes."}
</p>
</div>
</div>
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
{#if isEditingDisplayName}
<div class="flex w-full items-center gap-2">
<input
type="text"
bind:value={editDisplayNameValue}
class="w-full border-b border-neutral-600 bg-transparent px-2 py-1 font-mono text-neutral-300 outline-none focus:border-neutral-400"
maxlength="26"
on:keydown={(e) => {
if (e.key === 'Enter') saveDisplayName();
else if (e.key === 'Escape') cancelEditDisplayName();
}}
/>
<button
on:click={saveDisplayName}
class="flex items-center gap-1 rounded bg-green-900/50 px-3 py-2 text-xs font-medium text-green-400 transition-colors hover:bg-green-900"
>
<Check class="h-4 w-4" />
Save
</button>
<button
on:click={cancelEditDisplayName}
class="flex items-center gap-1 rounded bg-neutral-700 px-3 py-2 text-xs font-medium text-neutral-300 transition-colors hover:bg-neutral-600"
>
<X class="h-4 w-4" />
Cancel
</button>
</div>
{:else}
<span class="font-mono text-neutral-300"
>{data.user?.displayName || data.user?.username}</span
>
<button
on:click={startEditDisplayName}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600" class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
> >
<Pencil class="h-4 w-4" /> <Pencil class="h-4 w-4" />
Edit Display Name Edit
</button>
{#if isOwner}
<button
on:click={openTotpSetup}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<ShieldUser class="h-4 w-4" />
{totpEnabled ? 'Manage 2FA' : 'Enable 2FA'}
</button> </button>
{/if} {/if}
{#if $user?.roles?.some((r) => r === 255)} </div>
</div>
</div>
{#if isOwner}
<div class="col-span-2 md:col-span-1">
<div class="h-full rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start">
<div>
<h2 class="text-xl font-semibold text-neutral-100">Security</h2>
<p class="mt-1 text-sm text-neutral-400">
Manage your account security settings.
</p>
</div>
</div>
<div class="space-y-4">
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
<div class="flex flex-col">
<span class="text-sm font-medium text-neutral-200"
>Two-Factor Authentication</span
>
<span class="text-xs text-neutral-500"
>{totpEnabled ? 'Enabled' : 'Disabled'}</span
>
</div>
<button
on:click={openTotpSetup}
class="rounded bg-neutral-700 px-3 py-1.5 text-xs font-medium transition-colors hover:bg-neutral-600"
>
{totpEnabled ? 'Manage' : 'Enable'}
</button>
</div>
</div>
</div>
</div>
{/if}
{#if $user?.roles && hasRole($user.roles, roles.Admin)}
<div class="col-span-2 {isOwner ? 'md:col-span-1' : ''}">
<div class="h-full rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start">
<div>
<h2 class="text-xl font-semibold text-neutral-100">Administration</h2>
<p class="mt-1 text-sm text-neutral-400">Manage user roles and permissions.</p>
</div>
</div>
<div class="space-y-4">
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
<div class="flex flex-col">
<span class="text-sm font-medium text-neutral-200">User Roles</span>
<span class="text-xs text-neutral-500"
>{(() => {
let count = 0;
if (data.user?.roles) {
if (hasRole(data.user.roles, roles.User)) count++;
if (hasRole(data.user.roles, roles.Moderator)) count++;
if (hasRole(data.user.roles, roles.Admin)) count++;
}
return count;
})()} roles assigned</span
>
</div>
<button <button
on:click={openEditRoles} on:click={openEditRoles}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600" class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
> >
<ShieldUser class="h-4 w-4" /> Edit
Edit Roles
</button> </button>
</div>
</div>
</div>
</div>
{/if} {/if}
{#if isOwner || $user?.roles?.some((r) => r === 255)}
<button {#if isOwner}
on:click={openDeleteAccount} <div class="col-span-2">
class="flex items-center gap-2 rounded bg-red-900 px-4 py-2 text-sm font-medium transition-colors hover:bg-red-800" <div class="rounded border border-neutral-800 bg-neutral-900/50 p-6">
<div class="mb-6 flex items-start justify-between">
<div>
<h2 class="text-xl font-semibold text-neutral-100">
API Keys ({apiKeys.length}/10)
</h2>
<p class="mt-1 text-sm text-neutral-400">
Manage API keys for accessing Sharpbin programmatically.
</p>
</div>
</div>
{#if apiKeyError}
<div
class="mb-4 rounded border border-red-900/50 bg-red-900/10 p-3 text-sm text-red-200"
> >
<Trash2 class="h-4 w-4" /> {apiKeyError}
Delete Account </div>
{/if}
<div class="mb-6">
{#if isCreatingApiKey}
<div class="flex items-center gap-2">
<input
type="text"
placeholder="Key Name"
bind:value={newApiKeyName}
class="flex-1 border-b border-neutral-600 bg-transparent px-3 py-2 font-mono text-neutral-300 outline-none focus:border-neutral-400"
maxlength="26"
/>
<button
on:click={createApiKey}
disabled={loading || !newApiKeyName}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-50"
>
{#if loading}
<LoaderCircle class="h-4 w-4 animate-spin" />
{:else}
<Plus class="h-4 w-4" />
{/if}
Create
</button>
<button
on:click={() => {
isCreatingApiKey = false;
newApiKeyName = '';
}}
class="flex items-center gap-2 rounded bg-neutral-800 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-700"
>
Cancel
</button>
</div>
{:else}
<button
on:click={() => (isCreatingApiKey = true)}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<Plus class="h-4 w-4" />
Create New Key
</button> </button>
{/if} {/if}
</div> </div>
{#if newApiKeyValue}
<div class="mb-6 rounded border border-green-900/50 bg-green-900/10 p-4">
<div class="mb-2 flex items-center justify-between">
<span class="text-sm font-medium text-green-400">API Key Created</span>
<button
on:click={() => (newApiKeyValue = '')}
class="text-green-400/70 hover:text-green-400"
>
<X class="h-4 w-4" />
</button>
</div>
<p class="mb-3 text-xs text-green-200/70">
Please copy your API key now. You won't be able to see it again.
</p>
<div class="flex items-center gap-2 rounded bg-neutral-900/50 p-2">
<code class="flex-1 font-mono text-sm break-all text-green-300"
>{newApiKeyValue}</code
>
<button
class="p-1 text-neutral-400 hover:text-white"
on:click={() => {
navigator.clipboard.writeText(newApiKeyValue);
copiedApiKey = true;
setTimeout(() => (copiedApiKey = false), 1000);
}}
use:tooltip={'Copy to clipboard'}
>
<div class="relative mr-1 h-5 w-5">
{#if copiedApiKey}
<span
transition:fade={{ duration: 200 }}
class="absolute inset-0 flex items-center justify-center"
><Check class="h-4 w-4 text-green-400" /></span
>
{:else}
<span
transition:fade={{ duration: 200 }}
class="absolute inset-0 flex items-center justify-center"
><Copy class="h-4 w-4 text-neutral-400" /></span
>
{/if} {/if}
</div>
</button>
</div>
</div>
{/if}
<div class="space-y-2">
{#if apiKeys.length !== 0}
{#each apiKeys as key (key.uuid)}
<div class="flex items-center justify-between rounded bg-neutral-800/50 p-3">
<div class="flex flex-col gap-1">
<span class="font-medium text-neutral-200">{key.name}</span>
<div class="flex gap-3 text-xs text-neutral-500">
<span>Created: {new Date(key.createdAt).toLocaleDateString()}</span>
<span
>Last used: {key.lastUsedAt
? dateToRelativeString(new Date(key.lastUsedAt), true, false, now)
: 'Never'}</span
>
</div>
</div>
<button
on:click={() => deleteApiKey(key.uuid)}
disabled={loading}
class="p-2 text-neutral-500 transition-colors hover:text-red-400"
title="Revoke Key"
>
<Trash2 class="h-4 w-4" />
</button>
</div>
{/each}
{/if}
</div>
</div>
</div>
{/if}
{#if isOwner || ($user?.roles && hasRole($user.roles, roles.Admin))}
<div class="col-span-2">
<div class="rounded border border-red-900/30 bg-red-900/10 p-6">
<div class="flex items-start">
<div>
<h2 class="text-xl font-semibold text-red-400">Danger Zone</h2>
<p class="mt-1 text-sm text-red-200/70">
Irreversible actions related to this account.
</p>
</div>
</div>
<div class="mt-6 flex items-center justify-between rounded bg-red-900/20 p-4">
<div>
<h3 class="font-medium text-red-200">Delete Account</h3>
<p class="pr-0.5 text-sm text-red-200/60">
Permanently delete this account and all associated data.
</p>
</div>
<button
on:click={openDeleteAccount}
class="rounded border border-red-500/50 bg-red-500/10 px-4 py-2 text-sm font-medium whitespace-nowrap text-red-400 transition-colors hover:bg-red-500 hover:text-white"
>
Delete Account
</button>
</div>
</div>
</div>
{/if}
</div>
{:else if activeTab === 'pastes'}
<div class="mt-6 max-h-[60vh] space-y-4 overflow-y-auto"> <div class="mt-6 max-h-[60vh] space-y-4 overflow-y-auto">
{#if pastes && pastes.length > 0} {#if pastes && pastes.length > 0}
{#each pastes.slice().sort((a, b) => b.uuid.localeCompare(a.uuid)) as paste (paste.uuid)} {#each pastes
.slice()
.sort((a, b) => b.uuid.localeCompare(a.uuid)) as paste (paste.uuid)}
<Paste {paste} {now} showUser={false} compact={true} /> <Paste {paste} {now} showUser={false} compact={true} />
{/each} {/each}
{:else} {:else}
@@ -430,12 +918,29 @@
</p> </p>
{/if} {/if}
</div> </div>
{#if reportsSubmitted || reportsTarget} {#if pagination.totalPages && pagination.totalPages > 1}
<div class="mt-6 space-y-6"> <div class="mt-4 flex items-center justify-center gap-4">
{#if reportsSubmitted && reportsSubmitted.reports.length > 0} <button
<div class="rounded border border-neutral-800 bg-neutral-900/60 p-4"> class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
<h2 class="mb-3 text-xl font-semibold text-neutral-200">Submitted Reports</h2> on:click={() => fetchPage(currentPage - 1)}
<div class="space-y-3"> disabled={currentPage === 1 || loading}
>
Prev
</button>
<span class="text-neutral-400">
Page {currentPage} of {pagination.totalPages}
</span>
<button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => fetchPage(currentPage + 1)}
disabled={currentPage === pagination.totalPages || loading}
>
Next
</button>
</div>
{/if}
{:else if activeTab === 'reportsSubmitted' && reportsSubmitted && reportsSubmitted.reports.length > 0}
<div class="mt-6 space-y-3">
{#each reportsSubmitted.reports as report (report.reportID)} {#each reportsSubmitted.reports as report (report.reportID)}
<div <div
class="flex cursor-pointer flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none" class="flex cursor-pointer flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
@@ -493,12 +998,8 @@
</div> </div>
{/each} {/each}
</div> </div>
</div> {:else if activeTab === 'reportsTarget' && reportsTarget && reportsTarget.reports.length > 0}
{/if} <div class="mt-6 space-y-3">
{#if reportsTarget && reportsTarget.reports.length > 0}
<div class="rounded border border-neutral-800 bg-neutral-900/60 p-4">
<h2 class="mb-3 text-xl font-semibold text-neutral-200">Reports About This User</h2>
<div class="space-y-3">
{#each reportsTarget.reports as report (report.reportID)} {#each reportsTarget.reports as report (report.reportID)}
<div <div
class="flex cursor-pointer flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none" class="flex cursor-pointer flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
@@ -568,31 +1069,18 @@
</div> </div>
{/each} {/each}
</div> </div>
</div> {:else}
<p class="mt-6 text-center text-neutral-400">
{#if activeTab === 'reportsSubmitted'}
{isOwner ? 'You have' : 'This user has'} not submitted any reports.
{:else if activeTab === 'reportsTarget'}
{isOwner ? 'You have' : 'This user has'} not been reported.
{:else}
No reports found.
{/if}
</p>
{/if} {/if}
</div> </div>
{/if}
{#if pagination.totalPages && pagination.totalPages > 1}
<div class="mt-4 flex items-center justify-center gap-4">
<button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => fetchPage(currentPage - 1)}
disabled={currentPage === 1 || loading}
>
Prev
</button>
<span class="text-neutral-400">
Page {currentPage} of {pagination.totalPages}
</span>
<button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => fetchPage(currentPage + 1)}
disabled={currentPage === pagination.totalPages || loading}
>
Next
</button>
</div>
{/if}
</div> </div>
</main> </main>
@@ -0,0 +1,23 @@
import type { RequestEvent } from '@sveltejs/kit';
import { error, redirect } from '@sveltejs/kit';
import { apiUrl } from '$lib/server/api';
import { getServerToken } from '$lib/utils/auth';
export const load = async ({ params, fetch, cookies }: RequestEvent) => {
const token = getServerToken(cookies);
const uuid = (params as Record<string, string | undefined>).uuid;
if (!uuid) throw error(404, 'User not found');
const res = await fetch(`${apiUrl}/api/user/uuid/${uuid}`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined
});
if (!res.ok) {
const { message } = await res.json().catch(() => ({}));
throw error(res.status, message ?? 'Request failed');
}
const { user } = (await res.json()) as { user: { username: string } };
throw redirect(302, `/user/${encodeURIComponent(user.username)}`);
};
@@ -0,0 +1,16 @@
import { apiUrl } from '$lib/server/api';
import { extractError } from '$lib/utils/misc';
import { error } from '@sveltejs/kit';
export const load = async ({ url, request }) => {
const token = url.searchParams.get('token');
if (token) {
const headers = new Headers(request.headers);
const res = await fetch(`${apiUrl}/api/auth/verify-email?token=${token}`, { headers });
if (!res.ok) {
const json = await res.json().catch();
const message = extractError(json);
throw error(res.status, message ?? 'Request failed');
}
}
};
@@ -0,0 +1,11 @@
<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 text-center"
>
<h1 class="mb-4 text-4xl font-bold">Email verified.</h1>
<p class="mb-2 text-lg">You may close this page.</p>
</div>
</main>
+4 -2
View File
@@ -16,12 +16,14 @@ const allowedHosts = process.env.VITE_ALLOWED_HOSTS
export default defineConfig({ export default defineConfig({
plugins: [tailwindcss(), sveltekit()], plugins: [tailwindcss(), sveltekit()],
define: { define: {
__APP_VERSION__: JSON.stringify(pkg.version) __APP_VERSION__: JSON.stringify(pkg.version),
COMMIT_HASH: JSON.stringify(process.env.GIT_COMMIT_HASH || 'unknown')
}, },
server: { server: {
host: true, host: true,
proxy: { proxy: {
'/api': apiUrl '/api': apiUrl,
'/openapi': apiUrl
}, },
allowedHosts: allowedHosts 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,49 @@
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()),
new("roles", ((int)apiKey.User.Roles).ToString()),
new("is_banned", apiKey.User.IsBanned.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 namespace SharpbinV3.Server.Authorization
{ {
@@ -7,18 +8,31 @@ namespace SharpbinV3.Server.Authorization
{ {
private readonly bool _requireAuth = requireAuth; private readonly bool _requireAuth = requireAuth;
protected override Task HandleRequirementAsync( protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
AuthorizationHandlerContext context,
NotBannedRequirement requirement)
{ {
var httpContext = context.Resource as HttpContext;
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false; var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
if (!isAuthenticated && httpContext != null)
{
var apiKey = httpContext.GetApiKeyFromContext();
if (apiKey != null)
{
isAuthenticated = true;
}
}
if (_requireAuth && !isAuthenticated) if (_requireAuth && !isAuthenticated)
return Task.CompletedTask; return Task.CompletedTask;
var isBanned = context.User.Claims.Any(c => var isBanned =
(c.Type == ClaimTypes.Role || c.Type == "role") && bool.TryParse(context.User.Claims.FirstOrDefault(c => c.Type == "is_banned")?.Value, out var parsedIsBanned) && parsedIsBanned;
c.Value == "403");
if (!isBanned && httpContext?.GetJwtUser()?.IsBanned == true)
isBanned = true;
if (httpContext?.GetApiKeyFromContext()?.User?.IsBanned == true)
isBanned = true;
if (!isBanned) if (!isBanned)
context.Succeed(requirement); context.Succeed(requirement);
@@ -2,7 +2,5 @@
namespace SharpbinV3.Server.Authorization namespace SharpbinV3.Server.Authorization
{ {
public class NotBannedRequirement : IAuthorizationRequirement public class NotBannedRequirement : IAuthorizationRequirement { }
{
}
} }
+155 -50
View File
@@ -6,6 +6,7 @@ using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.ApiKey;
using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.DTOs.User; using SharpbinV3.Server.DTOs.User;
using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Extensions;
@@ -19,11 +20,19 @@ namespace SharpbinV3.Server.Controllers
{ {
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options, public class AuthController(
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase UserService userService,
AuthService authService,
ApiKeyService apiKeyService,
IOptions<AuthSettings> options,
VerificationService verification,
TotpVerificationProvider totp,
AppDbContext db
) : ControllerBase
{ {
private readonly AuthService _authService = authService; private readonly AuthService _authService = authService;
private readonly UserService _userService = userService; private readonly UserService _userService = userService;
private readonly ApiKeyService _apiKeyService = apiKeyService;
private readonly VerificationService _verification = verification; private readonly VerificationService _verification = verification;
private readonly TotpVerificationProvider _totp = totp; private readonly TotpVerificationProvider _totp = totp;
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
@@ -37,11 +46,7 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { success = false, message = "Registration is disabled." }); return BadRequest(new { success = false, message = "Registration is disabled." });
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(ModelState); return BadRequest(ModelState);
if (!await _verification.VerifyAsync(new VerificationContext if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { success = false, message = "Verification failed." }); return BadRequest(new { success = false, message = "Verification failed." });
var existingUser = await _userService.GetByUsername(request.Username); var existingUser = await _userService.GetByUsername(request.Username);
@@ -57,7 +62,11 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { success = false, message = "Display name should not exceed 26 characters." }); 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); var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
return Ok(new if (!string.IsNullOrWhiteSpace(user.Email))
await _authService.SendEmailVerification(user);
return Ok(
new
{ {
message = "User registered successfully.", message = "User registered successfully.",
user = new UserResponseDto user = new UserResponseDto
@@ -68,9 +77,10 @@ namespace SharpbinV3.Server.Controllers
DisplayName = user.DisplayName, DisplayName = user.DisplayName,
Email = user.Email, Email = user.Email,
Roles = user.Roles, Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility, Visibility = user.Visibility,
LastLogin = user.LastLogin LastLogin = user.LastLogin,
} },
} }
); );
} }
@@ -83,11 +93,7 @@ namespace SharpbinV3.Server.Controllers
if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email)) if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email))
return BadRequest(new { success = false, message = "Username or email is required." }); return BadRequest(new { success = false, message = "Username or email is required." });
if (!await _verification.VerifyAsync(new VerificationContext if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { success = false, message = "Verification failed." }); return BadRequest(new { success = false, message = "Verification failed." });
User? user = null; User? user = null;
@@ -104,24 +110,25 @@ namespace SharpbinV3.Server.Controllers
{ {
if (string.IsNullOrWhiteSpace(request.TotpCode)) if (string.IsNullOrWhiteSpace(request.TotpCode))
return BadRequest(new { success = false, message = "TOTP code is required." }); return BadRequest(new { success = false, message = "TOTP code is required." });
var totpValid = await _totp.VerifyAsync(new VerificationContext
{ var totpValid = await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode });
UserUUID = user.UUID,
Code = request.TotpCode
});
if (!totpValid) if (!totpValid)
return BadRequest(new { success = false, message = "Invalid TOTP code." }); return BadRequest(new { success = false, message = "Invalid TOTP code." });
} }
var token = _authService.GenerateJWTToken(user); var token = _authService.GenerateJWTToken(user);
await _authService.UpdateLoginTime(user); await _authService.UpdateLoginTime(user);
var result = await token; var result = await token;
return Ok(new LoginResponseDto return Ok(
new LoginResponseDto
{ {
Success = true, Success = true,
Token = result.Token ?? string.Empty, Token = result.Token ?? string.Empty,
RefreshToken = result.RefreshToken ?? string.Empty RefreshToken = result.RefreshToken ?? string.Empty,
});
} }
);
}
[HttpPost] [HttpPost]
[Route("refresh")] [Route("refresh")]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
@@ -130,16 +137,17 @@ namespace SharpbinV3.Server.Controllers
try try
{ {
var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken); var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken);
return Ok(new TokenRefreshResponseDto return Ok(
new TokenRefreshResponseDto
{ {
Success = jwtResult?.Success ?? false, Success = jwtResult?.Success ?? false,
Message = jwtResult?.Errors != null && jwtResult.Errors.Count > 0 ? string.Join("; ", jwtResult.Errors) : "Token refreshed successfully.", Message =
Token = jwtResult != null ? new TokenData jwtResult?.Errors != null && jwtResult.Errors.Count > 0
{ ? string.Join("; ", jwtResult.Errors)
Token = jwtResult.Token, : "Token refreshed successfully.",
RefreshToken = jwtResult.RefreshToken Token = jwtResult != null ? new TokenData { Token = jwtResult.Token, RefreshToken = jwtResult.RefreshToken } : null,
} : null }
}); );
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -153,39 +161,45 @@ namespace SharpbinV3.Server.Controllers
public IActionResult GetSiteInfo() public IActionResult GetSiteInfo()
{ {
var authSettings = options.Value; var authSettings = options.Value;
return Ok(new return Ok(
new
{ {
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey, cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
registration_enabled = authSettings.Registration_Enabled registration_enabled = authSettings.Registration_Enabled,
}); }
);
} }
[HttpGet] [HttpGet]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("totp/enroll")] [Route("totp/enroll")]
public async Task<IActionResult> StartTotpEnrollment() public async Task<IActionResult> StartTotpEnrollment()
{ {
var user = await _authService.GetUserFromHttpContext(HttpContext); 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 secret = _totp.GenerateSecret();
var secretBase32 = _totp.ToBase32(secret); var secretBase32 = _totp.ToBase32(secret);
var account = string.IsNullOrWhiteSpace(user.Email) ? user.Username : user.Email!; var account = string.IsNullOrWhiteSpace(user.Email) ? user.Username : user.Email!;
var uri = _totp.BuildOtpAuthUri("SharpbinV3", account, secretBase32); 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] [HttpPost]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("totp/enable")] [Route("totp/enable")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request) public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
{ {
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value; var uuid = Guid.Parse(User.FindFirst("uuid")!.Value);
if (string.IsNullOrEmpty(uuidClaim))
return Unauthorized(new { success = false, message = "Invalid token." });
var uuid = Guid.Parse(uuidClaim);
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code)) if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new { success = false, message = "Secret and code are required." }); return BadRequest(new { success = false, message = "Secret and code are required." });
@@ -210,27 +224,118 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpPost] [HttpPost]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("totp/disable")] [Route("totp/disable")]
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto) public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
{ {
var user = await _authService.GetUserFromHttpContext(HttpContext); 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)) if (string.IsNullOrWhiteSpace(dto.Code))
return BadRequest(new { success = false, message = "TOTP code is required." }); return BadRequest(new { success = false, message = "TOTP code is required." });
var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == user.UUID); var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == user.UUID);
if (existing is null) if (existing is null)
return BadRequest(new { success = false, message = "TOTP is not enabled." }); return BadRequest(new { success = false, message = "TOTP is not enabled." });
if (!_totp.VerifyAsync(new VerificationContext if (!_totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = dto.Code }).Result)
{
UserUUID = user.UUID,
Code = dto.Code
}).Result)
return BadRequest(new { success = false, message = "Invalid TOTP code." }); return BadRequest(new { success = false, message = "Invalid TOTP code." });
_db.UserTotps.Remove(existing); _db.UserTotps.Remove(existing);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return Ok(new { success = true, message = "TOTP disabled." }); 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." });
}
[HttpGet]
[Route("verify-email")]
public async Task<IActionResult> VerifyEmail(string token)
{
(bool verifiedEmail, string message) = await _authService.VerifyEmailVerificationToken(token);
if (verifiedEmail)
return Ok(new { success = true, message });
else
return BadRequest(new { success = false, message });
}
} }
} }
+119 -87
View File
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.Paste; using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.DTOs.Report; using SharpbinV3.Server.DTOs.Report;
using SharpbinV3.Server.DTOs.User; using SharpbinV3.Server.DTOs.User;
@@ -15,8 +16,14 @@ namespace SharpbinV3.Server.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
[ApiController] [ApiController]
public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService, public class PasteController(
ReportService reportService, IOptions<PasteSettings> options, IOptions<AuthSettings> authSettings) : ControllerBase PasteService pasteService,
VerificationService verificationService,
AuthService authService,
ReportService reportService,
IOptions<PasteSettings> options,
IOptions<AuthSettings> authSettings
) : ControllerBase
{ {
private readonly PasteService _pasteService = pasteService; private readonly PasteService _pasteService = pasteService;
private readonly VerificationService _verificationService = verificationService; private readonly VerificationService _verificationService = verificationService;
@@ -29,7 +36,13 @@ namespace SharpbinV3.Server.Controllers
[Route("create")] [Route("create")]
[Authorize(Policy = "NotBanned")] [Authorize(Policy = "NotBanned")]
[EnableRateLimiting("Strict")] [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",
Visibility visibility = Visibility.Public,
long expiresAt = 0,
string? verificationToken = null
)
{ {
if (!_pasteService.ValidateExpiresAt(expiresAt)) if (!_pasteService.ValidateExpiresAt(expiresAt))
return BadRequest(new { success = false, message = "Invalid expiration time." }); return BadRequest(new { success = false, message = "Invalid expiration time." });
@@ -44,18 +57,27 @@ namespace SharpbinV3.Server.Controllers
if (content.Length == 0) if (content.Length == 0)
return BadRequest(new { success = false, message = "Paste content cannot be empty." }); return BadRequest(new { success = false, message = "Paste content cannot be empty." });
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes) 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, var providedApiKey = HttpContext.GetApiKey();
Ip = HttpContext.GetRequestIP() 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." }); return BadRequest(new { success = false, message = "Verification failed." });
}
var user = await _authService.GetUserFromHttpContext(HttpContext); var user = await _authService.GetUserFromHttpContext(HttpContext);
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression); Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
return Ok(new PasteCreatedResponseDto return Ok(
new PasteCreatedResponseDto
{ {
ID = paste.ID, ID = paste.ID,
UUID = paste.UUID, UUID = paste.UUID,
@@ -63,30 +85,32 @@ namespace SharpbinV3.Server.Controllers
IsCompressed = paste.IsCompressed, IsCompressed = paste.IsCompressed,
Size = paste.Size, Size = paste.Size,
TrueSize = paste.TrueSize, TrueSize = paste.TrueSize,
ExpiresAt = paste.ExpiresAt ExpiresAt = paste.ExpiresAt,
}); Visibility = paste.Visibility,
}
);
} }
[HttpGet] [HttpGet]
[EnableRateLimiting("NoLimit")]
[Route("{id}")] [Route("{id}")]
public async Task<IActionResult> GetPasteByID(string id) public async Task<IActionResult> GetPasteByID(string id)
{ {
var paste = await _pasteService.Get(id); var paste = await _pasteService.Get(id);
if (paste == null) if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
return NotFound(new { success = false, message = "Paste not found" }); return NotFound(new { success = false, message = "Paste not found" });
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser();
int? reportCount = null; int? reportCount = null;
if (jwtUser != null && jwtUser.Roles.Any(r => r == 1 || r == 255)) if (jwtUser != null && (jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator)))
{ {
var query = new ReportQuery var query = new ReportQuery { PastePID = paste.PID };
{
PastePID = paste.PID
};
reportCount = await _reportService.GetReportCount(query); reportCount = await _reportService.GetReportCount(query);
} }
return Ok(new return Ok(
new
{ {
success = true, success = true,
paste = new PasteResponseDto paste = new PasteResponseDto
@@ -104,25 +128,32 @@ namespace SharpbinV3.Server.Controllers
ExpiresAt = paste.ExpiresAt, ExpiresAt = paste.ExpiresAt,
EditedAt = paste.EditedAt, EditedAt = paste.EditedAt,
ReportCount = reportCount, ReportCount = reportCount,
Author = paste.User != null && paste.User.Visibility == 0 ? new UserSimpleDto Author =
paste.User != null && paste.User.Visibility == 0
? new UserSimpleDto
{ {
UID = paste.User.UID, UID = paste.User.UID,
UUID = paste.User.UUID, UUID = paste.User.UUID,
Username = paste.User.Username, Username = paste.User.Username,
DisplayName = paste.User.DisplayName, DisplayName = paste.User.DisplayName,
Visibility = paste.User.Visibility, Visibility = paste.User.Visibility,
Roles = paste.User.Roles Roles = paste.User.Roles,
} : null IsBanned = paste.User.IsBanned,
} }
}); : null,
},
}
);
} }
[HttpGet] [HttpGet]
[EnableRateLimiting("NoLimit")]
[Route("{id}/raw")] [Route("{id}/raw")]
public async Task<IActionResult> GetRawPasteByID(string id) public async Task<IActionResult> GetRawPasteByID(string id)
{ {
var paste = await _pasteService.Get(id); var paste = await _pasteService.Get(id);
if (paste == null) return NotFound(); if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
return NotFound();
if (paste.IsCompressed) if (paste.IsCompressed)
Response.Headers.Append("Content-Encoding", "gzip"); Response.Headers.Append("Content-Encoding", "gzip");
@@ -131,7 +162,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPut] [HttpPut]
[Route("{id}")] [Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> EditPaste(string id) public async Task<IActionResult> EditPaste(string id)
{ {
string content = await new StreamReader(Request.Body).ReadToEndAsync(); string content = await new StreamReader(Request.Body).ReadToEndAsync();
@@ -142,40 +173,34 @@ namespace SharpbinV3.Server.Controllers
if (paste == null) if (paste == null)
return StatusCode(404, new { success = false, message = "Paste not found." }); return StatusCode(404, new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." }); return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _pasteService.EditText(paste, content); 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." }); return Ok(new { message = "Paste edited successfully." });
} }
[HttpPatch] [HttpPatch]
[Route("{id}")] [Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request) public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
{ {
var paste = await _pasteService.Get(id); var paste = await _pasteService.Get(id);
if (paste == null) if (paste == null)
return NotFound(new { success = false, message = "Paste not found." }); return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this paste." }); return StatusCode(403, new { success = false, message = "You do not have permission to modify this paste." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
if (request.Title != null) if (request.Title != null)
paste.Title = request.Title; paste.Title = request.Title;
if (request.Syntax != null) if (request.Syntax != null)
@@ -195,7 +220,8 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { success = false, message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." }); return BadRequest(new { success = false, message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
var newPaste = await _pasteService.Edit(paste); var newPaste = await _pasteService.Edit(paste);
return Ok(new return Ok(
new
{ {
success = true, success = true,
message = "Paste metadata updated successfully.", message = "Paste metadata updated successfully.",
@@ -211,31 +237,30 @@ namespace SharpbinV3.Server.Controllers
Views = newPaste.Views, Views = newPaste.Views,
Syntax = newPaste.Syntax, Syntax = newPaste.Syntax,
Visibility = newPaste.Visibility, Visibility = newPaste.Visibility,
ExpiresAt = newPaste.ExpiresAt ExpiresAt = newPaste.ExpiresAt,
},
} }
}); );
} }
[HttpDelete] [HttpDelete]
[Route("{id}")] [Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> DeletePaste(string id) public async Task<IActionResult> DeletePaste(string id)
{ {
var paste = await _pasteService.Get(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(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole) if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this paste." }); return StatusCode(403, new { success = false, message = "You do not have permission to delete this paste." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _pasteService.Delete(paste); 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." }); return Ok(new { success = true, message = "Paste deleted successfully." });
} }
@@ -250,10 +275,17 @@ namespace SharpbinV3.Server.Controllers
if (_pasteSettings.View_HMAC_Secret == null) if (_pasteSettings.View_HMAC_Secret == null)
return StatusCode(500, new { success = false, message = "View recording is not configured properly." }); return StatusCode(500, new { success = false, message = "View recording is not configured properly." });
if (!string.IsNullOrWhiteSpace(_pasteSettings.View_Internal_API_Key) if (
&& _pasteSettings.View_Internal_API_Key != Request.Headers["X-Internal-API-Key"]) !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." }); return Unauthorized(new { success = false, message = "Invalid API key." });
if (paste.AuthorUUID != HttpContext.GetJwtUser()?.UUID)
return Ok(new { success = true, message = "View not recorded for author's own paste." });
if (paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && paste.Visibility != 0)
return Ok(new { success = true, message = "View not recorded for expired paste." });
var result = await _pasteService.RecordView(paste, HttpContext); var result = await _pasteService.RecordView(paste, HttpContext);
if (result.paste is null && !result.alreadyExists) if (result.paste is null && !result.alreadyExists)
@@ -266,34 +298,32 @@ namespace SharpbinV3.Server.Controllers
[HttpPost] [HttpPost]
[Route("{id}/report")] [Route("{id}/report")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request) public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
{ {
var paste = await _pasteService.Get(id); var paste = await _pasteService.Get(id);
if (paste == null) if (paste == null)
return NotFound(new { success = false, message = "Paste not found." }); return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType); Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType)) if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." }); return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext if (
{ !await _verificationService.VerifyAsync(
Token = request.VerificationToken, new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
Ip = HttpContext.GetRequestIP() )
})) )
return BadRequest(new { success = false, message = "Verification failed." }); return BadRequest(new { success = false, message = "Verification failed." });
Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description); Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description);
if (report == null) if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." }); return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
return Ok(new return Ok(
new
{ {
success = true, success = true,
message = "Paste reported successfully.", message = "Paste reported successfully.",
@@ -307,14 +337,15 @@ namespace SharpbinV3.Server.Controllers
UpdatedAt = report.UpdatedAt, UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID, ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType, TargetType = report.TargetType,
UserUUID = report.UserUUID UserUUID = report.UserUUID,
},
} }
}); );
} }
[HttpPatch] [HttpPatch]
[Route("{id}/report/{reportId}")] [Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request) public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
{ {
@@ -326,11 +357,9 @@ namespace SharpbinV3.Server.Controllers
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." }); return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." }); return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." });
@@ -350,7 +379,7 @@ namespace SharpbinV3.Server.Controllers
[HttpDelete] [HttpDelete]
[Route("{id}/report/{reportId}")] [Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeletePasteReport(string id, int reportId) public async Task<IActionResult> DeletePasteReport(string id, int reportId)
{ {
@@ -362,17 +391,12 @@ namespace SharpbinV3.Server.Controllers
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID) if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." }); return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole) if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." }); return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." });
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
bool result = await _reportService.DeleteReport(report); bool result = await _reportService.DeleteReport(report);
if (!result) if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." }); return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
@@ -385,7 +409,8 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> GetRecentPastes() public async Task<IActionResult> GetRecentPastes()
{ {
var results = await _pasteService.GetList(0, 50, true); var results = await _pasteService.GetList(0, 50, true);
return Ok(results.Select(p => new PasteResponseDto return Ok(
results.Select(p => new PasteResponseDto
{ {
ID = p.ID, ID = p.ID,
UUID = p.UUID, UUID = p.UUID,
@@ -399,16 +424,21 @@ namespace SharpbinV3.Server.Controllers
Visibility = p.Visibility, Visibility = p.Visibility,
ExpiresAt = p.ExpiresAt, ExpiresAt = p.ExpiresAt,
EditedAt = p.EditedAt, EditedAt = p.EditedAt,
Author = p.User != null && p.User.Visibility == 0 ? new UserSimpleDto Author =
p.User != null && p.User.Visibility == 0
? new UserSimpleDto
{ {
UID = p.User.UID, UID = p.User.UID,
UUID = p.User.UUID, UUID = p.User.UUID,
Username = p.User.Username, Username = p.User.Username,
DisplayName = p.User.DisplayName, DisplayName = p.User.DisplayName,
Visibility = p.User.Visibility, Visibility = p.User.Visibility,
Roles = p.User.Roles Roles = p.User.Roles,
} : null IsBanned = p.User.IsBanned,
})); }
: null,
})
);
} }
[HttpGet] [HttpGet]
@@ -416,19 +446,21 @@ namespace SharpbinV3.Server.Controllers
[Route("info")] [Route("info")]
public IActionResult GetCreatePasteOptions() public IActionResult GetCreatePasteOptions()
{ {
return Ok(new PasteOptionsDto return Ok(
new PasteOptionsDto
{ {
Syntaxes = [.. _pasteSettings.ValidSyntaxLanguages], Syntaxes = [.. _pasteSettings.ValidSyntaxLanguages],
Visibilities = Visibilities =
[ [
new() { Value = 0, DisplayName = "Public" }, new() { Value = 0, DisplayName = "Public" },
new() { Value = 1, DisplayName = "Unlisted" }, new() { Value = 1, DisplayName = "Unlisted" },
new() { Value = 2, DisplayName = "Private" } new() { Value = 2, DisplayName = "Private" },
], ],
MaxTitleLength = _pasteSettings.MaxTitleLength, MaxTitleLength = _pasteSettings.MaxTitleLength,
MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes, MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes,
RequiresVerification = _pasteSettings.RequiresVerfication RequiresVerification = _pasteSettings.RequiresVerification,
}); }
);
} }
} }
} }
@@ -15,24 +15,23 @@ namespace SharpbinV3.Server.Controllers
[Route("{reportId:int}")] [Route("{reportId:int}")]
[HttpGet] [HttpGet]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportById(int reportId) public async Task<IActionResult> GetReportById(int reportId)
{ {
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
var report = await reportService.GetReportByID(reportId); var report = await reportService.GetReportByID(reportId);
if (report is null) if (report is null)
return NotFound(new { success = false, message = "Report not found." }); return NotFound(new { success = false, message = "Report not found." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (!hasPrivilegedRole && report.ReporterUUID != user.UUID) if (!hasPrivilegedRole && report.ReporterUUID != user.UUID)
return StatusCode(403, new { success = false, message = "You do not have permission to view this report." }); return StatusCode(403, new { success = false, message = "You do not have permission to view this report." });
var (Username, DisplayName) = await reportService.GetReporterInfo(report.ReporterUUID); var (Username, DisplayName) = await reportService.GetReporterInfo(report.ReporterUUID);
return Ok(new ReportResponseDto return Ok(
new ReportResponseDto
{ {
ReportID = report.ReportID, ReportID = report.ReportID,
Type = report.Type, Type = report.Type,
@@ -48,20 +47,19 @@ namespace SharpbinV3.Server.Controllers
PasteTitle = report.Paste?.Title, PasteTitle = report.Paste?.Title,
UserUUID = report.UserUUID, UserUUID = report.UserUUID,
TargetUsername = report.User?.Username, TargetUsername = report.User?.Username,
TargetDisplayName = report.User?.DisplayName TargetDisplayName = report.User?.DisplayName,
}); }
);
} }
[Route("{reportId:int}")] [Route("{reportId:int}")]
[HttpPatch] [HttpPatch]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request) public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
{ {
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user is null) if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return Unauthorized(new { success = false, message = "You must be logged in to update reports." });
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
var report = await reportService.GetReportByID(reportId); var report = await reportService.GetReportByID(reportId);
@@ -91,7 +89,8 @@ namespace SharpbinV3.Server.Controllers
var updated = await reportService.UpdateReport(report); var updated = await reportService.UpdateReport(report);
var (Username, DisplayName) = await reportService.GetReporterInfo(updated.ReporterUUID); var (Username, DisplayName) = await reportService.GetReporterInfo(updated.ReporterUUID);
return Ok(new ReportResponseDto return Ok(
new ReportResponseDto
{ {
ReportID = updated.ReportID, ReportID = updated.ReportID,
Type = updated.Type, Type = updated.Type,
@@ -107,8 +106,9 @@ namespace SharpbinV3.Server.Controllers
PasteTitle = updated.Paste?.Title, PasteTitle = updated.Paste?.Title,
UserUUID = updated.UserUUID, UserUUID = updated.UserUUID,
TargetUsername = updated.User?.Username, TargetUsername = updated.User?.Username,
TargetDisplayName = updated.User?.DisplayName TargetDisplayName = updated.User?.DisplayName,
}); }
);
} }
[Route("options")] [Route("options")]
@@ -123,26 +123,20 @@ namespace SharpbinV3.Server.Controllers
[Route("pastes")] [Route("pastes")]
[HttpGet] [HttpGet]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request) public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
{ {
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user is null) if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." }); return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
var query = request with var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null };
{
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100),
UserUUID = null
};
var reports = await reportService.GetPasteReports(query); var reports = await reportService.GetPasteReports(query);
var totalCount = await reportService.GetReportCount(query); var totalCount = await reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new return Ok(
new
{ {
Reports = reports, Reports = reports,
Pagination = new Pagination = new
@@ -150,21 +144,20 @@ namespace SharpbinV3.Server.Controllers
query.Page, query.Page,
query.PageSize, query.PageSize,
TotalCount = totalCount, TotalCount = totalCount,
TotalPages = totalPages TotalPages = totalPages,
},
} }
}); );
} }
[Route("users")] [Route("users")]
[HttpGet] [HttpGet]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request) public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
{ {
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user is null) if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view users." }); return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
var query = request with var query = request with
@@ -172,13 +165,14 @@ namespace SharpbinV3.Server.Controllers
Page = Math.Max(request.Page, 1), Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100), PageSize = Math.Clamp(request.PageSize, 1, 100),
PastePID = null, PastePID = null,
PasteId = null PasteId = null,
}; };
var reports = await reportService.GetUserReports(query); var reports = await reportService.GetUserReports(query);
var totalCount = await reportService.GetReportCount(query); var totalCount = await reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new return Ok(
new
{ {
Reports = reports, Reports = reports,
Pagination = new Pagination = new
@@ -186,27 +180,27 @@ namespace SharpbinV3.Server.Controllers
query.Page, query.Page,
query.PageSize, query.PageSize,
TotalCount = totalCount, TotalCount = totalCount,
TotalPages = totalPages TotalPages = totalPages,
},
} }
}); );
} }
[Route("all")] [Route("all")]
[HttpGet] [HttpGet]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetAllReports( public async Task<IActionResult> GetAllReports(
[FromQuery] Guid? reporterUuid, [FromQuery] Guid? reporterUuid,
[FromQuery] ReportTargetType? targetType, [FromQuery] ReportTargetType? targetType,
[FromQuery] ReportType? type, [FromQuery] ReportType? type,
[FromQuery] ReportStatus? status, [FromQuery] ReportStatus? status,
[FromQuery] int page = 1, [FromQuery] int page = 1,
[FromQuery] int pageSize = 20) [FromQuery] int pageSize = 20
)
{ {
var user = HttpContext.GetJwtUser(); var user = HttpContext.GetJwtUser()!;
if (user is null) if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
var query = new ReportQuery var query = new ReportQuery
@@ -216,13 +210,14 @@ namespace SharpbinV3.Server.Controllers
Type = type, Type = type,
Status = status, Status = status,
Page = Math.Max(page, 1), Page = Math.Max(page, 1),
PageSize = Math.Clamp(pageSize, 1, 100) PageSize = Math.Clamp(pageSize, 1, 100),
}; };
var reports = await reportService.GetReports(query); var reports = await reportService.GetReports(query);
var totalCount = await reportService.GetReportCount(query); var totalCount = await reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new return Ok(
new
{ {
Reports = reports, Reports = reports,
Pagination = new Pagination = new
@@ -230,9 +225,10 @@ namespace SharpbinV3.Server.Controllers
query.Page, query.Page,
query.PageSize, query.PageSize,
TotalCount = totalCount, TotalCount = totalCount,
TotalPages = totalPages TotalPages = totalPages,
},
} }
}); );
} }
} }
} }
+97 -101
View File
@@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Paste; using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.DTOs.Report; using SharpbinV3.Server.DTOs.Report;
@@ -19,8 +20,14 @@ namespace SharpbinV3.Server.Controllers
{ {
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp, public class UserController(
VerificationService verificationService, ReportService reportServer, IOptions<AuthSettings> authSettings) : ControllerBase UserService userService,
AppDbContext db,
TotpVerificationProvider totp,
VerificationService verificationService,
ReportService reportServer,
IOptions<AuthSettings> authSettings
) : ControllerBase
{ {
private readonly UserService _userService = userService; private readonly UserService _userService = userService;
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
@@ -47,57 +54,55 @@ namespace SharpbinV3.Server.Controllers
[Authorize] [Authorize]
public async Task<IActionResult> GetMe([FromQuery] int page = 1) public async Task<IActionResult> GetMe([FromQuery] int page = 1)
{ {
var userUUID = HttpContext.User?.FindFirst("uuid")?.Value; var userUUID = HttpContext.User.FindFirst("uuid")!.Value;
if (userUUID is null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true); 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); return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
} }
[HttpPatch("uuid/{uuid}")] [HttpPatch("uuid/{uuid}")]
[Authorize] [Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Strict")] [EnableRateLimiting("Strict")]
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser) public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
{ {
Console.WriteLine($"{ModelState.IsValid}");
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(ModelState); return BadRequest(ModelState);
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
return NotFound(new { success = false, message = "User not found." }); 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.HasFlag(Role.Admin) && !jwtUser.Roles.HasFlag(Role.Admin))
|| (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." }); 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) if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName; user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self if (jwtUser.Roles.HasFlag(Role.Admin) || user.UUID == jwtUser.UUID) // only admins or self
{ {
user.Email = updatedUser.Email ?? user.Email; user.Email = updatedUser.Email ?? user.Email;
user.Visibility = updatedUser.Visibility ?? user.Visibility; user.Visibility = updatedUser.Visibility ?? user.Visibility;
} }
if (jwtUser.Roles.Contains(255)) if (jwtUser.Roles.HasFlag(Role.Admin))
{ {
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled) if (jwtUser.TotpEnabled)
{ {
if (string.IsNullOrEmpty(updatedUser.TotpCode) || !await _totp.VerifyAsync(new VerificationContext if (
{ string.IsNullOrEmpty(updatedUser.TotpCode)
UserUUID = jwtUser.UUID, || !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = updatedUser.TotpCode })
Code = updatedUser.TotpCode )
}))
{ {
return Unauthorized(new { message = "Invalid TOTP code." }); return Unauthorized(new { message = "Invalid TOTP code." });
} }
} }
user.Roles = updatedUser.Roles ?? user.Roles; user.Roles = updatedUser.Roles ?? user.Roles;
user.IsBanned = updatedUser.IsBanned ?? user.IsBanned;
} }
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
@@ -105,41 +110,37 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpDelete("uuid/{uuid}")] [HttpDelete("uuid/{uuid}")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto) public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
return NotFound(new { success = false, message = "User not found." }); return NotFound(new { success = false, message = "User not found." });
if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID) if (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." }); return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA) if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." }); return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
if (jwtUser.TotpEnabled) if (jwtUser.TotpEnabled)
{ {
if (string.IsNullOrEmpty(dto.TotpCode) || !await _totp.VerifyAsync(new VerificationContext if (
{ string.IsNullOrEmpty(dto.TotpCode)
UserUUID = jwtUser.UUID, || !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = dto.TotpCode })
Code = dto.TotpCode )
}))
{ {
return Unauthorized(new { message = "Invalid TOTP code." }); return Unauthorized(new { message = "Invalid TOTP code." });
} }
} }
else else
{ {
if (string.IsNullOrEmpty(dto.Token) || !await _verificationService.VerifyAsync(new VerificationContext if (
{ string.IsNullOrEmpty(dto.Token)
Token = dto.Token, || !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() })
Ip = HttpContext.GetRequestIP() )
}))
{ {
return Unauthorized(new { message = "Invalid verification token." }); return Unauthorized(new { message = "Invalid verification token." });
} }
@@ -153,12 +154,10 @@ namespace SharpbinV3.Server.Controllers
[HttpPost] [HttpPost]
[Route("{uuid}/report")] [Route("{uuid}/report")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request) public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
{ {
var reporter = HttpContext.GetJwtUser(); var reporter = HttpContext.GetJwtUser()!;
if (reporter == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var reportedUser = await _userService.GetByUUID(uuid); var reportedUser = await _userService.GetByUUID(uuid);
if (reportedUser == null) if (reportedUser == null)
@@ -169,18 +168,19 @@ namespace SharpbinV3.Server.Controllers
if (!Enum.IsDefined(reportType)) if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." }); return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext if (
{ !await _verificationService.VerifyAsync(
Token = request.VerificationToken, new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
Ip = HttpContext.GetRequestIP() )
})) )
return Unauthorized(new { success = false, message = "Invalid verification token." }); return Unauthorized(new { success = false, message = "Invalid verification token." });
Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description); Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description);
if (report == null) if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while creating the report." }); return StatusCode(500, new { success = false, message = "An error occurred while creating the report." });
return Ok(new return Ok(
new
{ {
success = true, success = true,
message = "User reported successfully.", message = "User reported successfully.",
@@ -194,20 +194,19 @@ namespace SharpbinV3.Server.Controllers
UpdatedAt = report.UpdatedAt, UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID, ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType, TargetType = report.TargetType,
UserUUID = report.UserUUID UserUUID = report.UserUUID,
},
} }
}); );
} }
[HttpPatch] [HttpPatch]
[Route("{uuid}/report/{reportId}")] [Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request) public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
@@ -231,12 +230,10 @@ namespace SharpbinV3.Server.Controllers
[HttpDelete] [HttpDelete]
[Route("{uuid}/report/{reportId}")] [Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")] [EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")] [Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId) public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
@@ -254,31 +251,25 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpGet] [HttpGet]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("{uuid}/reports")] [Route("{uuid}/reports")]
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request) public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
return NotFound(new { success = false, message = "User not found." }); return NotFound(new { success = false, message = "User not found." });
if (!jwtUser.Roles.Any(r => r == 1 || r == 255)) if (!jwtUser.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
var query = request with var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
{
UserUUID = user.UUID,
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100)
};
var reports = await _reportService.GetUserReports(query); var reports = await _reportService.GetUserReports(query);
var totalCount = await _reportService.GetReportCount(query); var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new return Ok(
new
{ {
Reports = reports, Reports = reports,
Pagination = new Pagination = new
@@ -286,41 +277,36 @@ namespace SharpbinV3.Server.Controllers
query.Page, query.Page,
query.PageSize, query.PageSize,
TotalCount = totalCount, TotalCount = totalCount,
TotalPages = totalPages TotalPages = totalPages,
},
} }
}); );
} }
[HttpGet] [HttpGet]
[Authorize] [Authorize(Policy = "JwtOnly")]
[Route("{uuid}/reports/submitted")] [Route("{uuid}/reports/submitted")]
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request) public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
{ {
var jwtUser = HttpContext.GetJwtUser(); var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
return NotFound(new { success = false, message = "User not found." }); return NotFound(new { success = false, message = "User not found." });
var isOwner = user.UUID == jwtUser.UUID; var isOwner = user.UUID == jwtUser.UUID;
var hasPrivilegedRole = jwtUser.Roles.Any(r => r == 1 || r == 255); var hasPrivilegedRole = jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator);
if (!isOwner && !hasPrivilegedRole) if (!isOwner && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." }); return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
var query = request with var query = request with { ReporterUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
{
ReporterUUID = user.UUID,
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100)
};
var reports = await _reportService.GetReports(query); var reports = await _reportService.GetReports(query);
var totalCount = await _reportService.GetReportCount(query); var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize); var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new return Ok(
new
{ {
Reports = reports, Reports = reports,
Pagination = new Pagination = new
@@ -328,9 +314,10 @@ namespace SharpbinV3.Server.Controllers
query.Page, query.Page,
query.PageSize, query.PageSize,
TotalCount = totalCount, TotalCount = totalCount,
TotalPages = totalPages TotalPages = totalPages,
},
} }
}); );
} }
private async Task<IActionResult> BuildUserResponse(User user, int page = 1) private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
@@ -339,10 +326,10 @@ namespace SharpbinV3.Server.Controllers
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID); var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isAuthenticatedUser) if (!isAuthenticatedUser)
{ {
if (user.Visibility == 2) if (user.Visibility == Visibility.Private && (!user.Roles.HasFlag(Role.Admin) || !user.Roles.HasFlag(Role.Moderator)))
return NotFound(); return NotFound();
else if (user.Visibility != 1) else if (user.Visibility != Visibility.Unlisted)
pasteQuery = pasteQuery.Where(p => p.Visibility == 0); pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
} }
if (page < 1) if (page < 1)
@@ -369,7 +356,7 @@ namespace SharpbinV3.Server.Controllers
Views = p.Views, Views = p.Views,
Visibility = p.Visibility, Visibility = p.Visibility,
EditedAt = p.EditedAt, EditedAt = p.EditedAt,
ExpiresAt = p.ExpiresAt ExpiresAt = p.ExpiresAt,
}) })
.ToListAsync(); .ToListAsync();
@@ -378,20 +365,23 @@ namespace SharpbinV3.Server.Controllers
Page = page, Page = page,
PageSize = pageSize, PageSize = pageSize,
TotalCount = totalCount, TotalCount = totalCount,
TotalPages = totalPages TotalPages = totalPages,
}; };
if (isAuthenticatedUser) if (isAuthenticatedUser)
{ {
var reports = await _reportService.GetReports(new ReportQuery var reports = await _reportService.GetReports(
new ReportQuery
{ {
ReporterUUID = user.UUID, ReporterUUID = user.UUID,
Page = page, Page = page,
PageSize = pageSize PageSize = pageSize,
}); }
);
var reportsCount = await _reportService.GetReportCountByReporter(user.UUID); var reportsCount = await _reportService.GetReportCountByReporter(user.UUID);
return Ok(new return Ok(
new
{ {
User = new UserResponseDto User = new UserResponseDto
{ {
@@ -401,9 +391,11 @@ namespace SharpbinV3.Server.Controllers
CreatedAt = user.CreatedAt, CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName, DisplayName = user.DisplayName,
Email = user.Email, Email = user.Email,
EmailVerified = user.EmailVerified,
LastLogin = user.LastLogin, LastLogin = user.LastLogin,
Roles = user.Roles, Roles = user.Roles,
Visibility = user.Visibility IsBanned = user.IsBanned,
Visibility = user.Visibility,
}, },
Pastes = pastes, Pastes = pastes,
Reports = reports, Reports = reports,
@@ -413,12 +405,14 @@ namespace SharpbinV3.Server.Controllers
Page = page, Page = page,
PageSize = pageSize, PageSize = pageSize,
TotalCount = reportsCount, TotalCount = reportsCount,
TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize) TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize),
},
} }
}); );
} }
return Ok(new return Ok(
new
{ {
User = new UserSimpleDto User = new UserSimpleDto
{ {
@@ -428,11 +422,13 @@ namespace SharpbinV3.Server.Controllers
CreatedAt = user.CreatedAt, CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName, DisplayName = user.DisplayName,
Roles = user.Roles, Roles = user.Roles,
Visibility = user.Visibility IsBanned = user.IsBanned,
Visibility = user.Visibility,
}, },
Pastes = pastes, Pastes = pastes,
Pagination = pagination 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] [Required]
public required string Token { get; set; } public required string Token { get; set; }
[Required] [Required]
public required string RefreshToken { get; set; } public required string RefreshToken { get; set; }
} }
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Auth
{ {
[JsonPropertyName("success")] [JsonPropertyName("success")]
public bool Success { get; set; } public bool Success { get; set; }
[JsonPropertyName("error-codes")] [JsonPropertyName("error-codes")]
public string[]? ErrorCodes { get; set; } public string[]? ErrorCodes { get; set; }
} }
@@ -1,3 +1,4 @@
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.User; using SharpbinV3.Server.DTOs.User;
namespace SharpbinV3.Server.DTOs.Paste namespace SharpbinV3.Server.DTOs.Paste
@@ -13,7 +14,7 @@ namespace SharpbinV3.Server.DTOs.Paste
public long TrueSize { get; set; } public long TrueSize { get; set; }
public bool IsCompressed { get; set; } public bool IsCompressed { get; set; }
public int Views { get; set; } public int Views { get; set; }
public int Visibility { get; set; } public Visibility Visibility { get; set; }
public long? EditedAt { get; set; } public long? EditedAt { get; set; }
public long ExpiresAt { get; set; } public long ExpiresAt { get; set; }
public int? ReportCount { get; set; } public int? ReportCount { get; set; }
@@ -29,6 +30,7 @@ namespace SharpbinV3.Server.DTOs.Paste
public long Size { get; set; } public long Size { get; set; }
public long TrueSize { get; set; } public long TrueSize { get; set; }
public long ExpiresAt { get; set; } public long ExpiresAt { get; set; }
public Visibility Visibility { get; set; }
} }
public class PasteOptionsDto public class PasteOptionsDto
@@ -1,10 +1,12 @@
namespace SharpbinV3.Server.DTOs.Paste using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs.Paste
{ {
public class UpdatePasteDto public class UpdatePasteDto
{ {
public string? Title { get; set; } public string? Title { get; set; }
public string? Syntax { get; set; } public string? Syntax { get; set; }
public int? Visibility { get; set; } public Visibility? Visibility { get; set; }
public long? ExpiresAt { get; set; } public long? ExpiresAt { get; set; }
} }
} }
+2 -1
View File
@@ -7,8 +7,9 @@ namespace SharpbinV3.Server.DTOs.Report
[Required] [Required]
[MinLength(12), MaxLength(1000)] [MinLength(12), MaxLength(1000)]
public string Description { get; set; } = string.Empty; public string Description { get; set; } = string.Empty;
[Required] [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 ReportStatus { get; set; } = "Open";
public string? VerificationToken { get; set; } public string? VerificationToken { get; set; }
} }
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Report
{ {
public string? Status { get; set; } public string? Status { get; set; }
public string? Type { get; set; } public string? Type { get; set; }
[MaxLength(1000)] [MaxLength(1000)]
public string? Description { get; set; } public string? Description { get; set; }
} }
@@ -7,6 +7,7 @@ namespace SharpbinV3.Server.DTOs.User
[StringLength(50, MinimumLength = 3)] [StringLength(50, MinimumLength = 3)]
public string? Username { get; set; } public string? Username { get; set; }
public string? Email { get; set; } public string? Email { get; set; }
[StringLength(128, MinimumLength = 6)] [StringLength(128, MinimumLength = 6)]
public string? Password { get; set; } public string? Password { get; set; }
public string? Token { get; set; } public string? Token { get; set; }
+19 -5
View File
@@ -24,16 +24,26 @@ namespace SharpbinV3.Server.DTOs
if (!ValidateUsername().IsMatch(Username)) if (!ValidateUsername().IsMatch(Username))
results.Add(new ValidationResult("Username can only contain letters, numbers, underscores, and dots.", [nameof(Username)])); results.Add(new ValidationResult("Username can only contain letters, numbers, underscores, and dots.", [nameof(Username)]));
if (!ValidatePassword().IsMatch(Password)) 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) if (DisplayName.Length < 3 || DisplayName.Length > 26)
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)])); results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)]));
if (!ValidateUsername().IsMatch(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(); var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(Email)) if (!emailAttribute.IsValid(Email))
@@ -44,6 +54,10 @@ namespace SharpbinV3.Server.DTOs
[GeneratedRegex("^[A-Za-z0-9_.]+$")] [GeneratedRegex("^[A-Za-z0-9_.]+$")]
private static partial Regex ValidateUsername(); 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,}$")] [GeneratedRegex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")]
public static partial Regex ValidatePassword(); public static partial Regex ValidatePassword();
} }
+21 -19
View File
@@ -1,5 +1,7 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs
{ {
@@ -7,47 +9,47 @@ namespace SharpbinV3.Server.DTOs
{ {
public string? DisplayName { get; set; } public string? DisplayName { get; set; }
public string? Email { get; set; } public string? Email { get; set; }
public int? Visibility { get; set; } = 0; public Visibility? Visibility { get; set; } = Data.Enums.Visibility.Public;
public int[]? Roles { get; set; } public Role? Roles { get; set; }
public bool? IsBanned { get; set; }
public string? TotpCode { get; set; } public string? TotpCode { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{ {
var results = new List<ValidationResult>(); var results = new List<ValidationResult>();
if (DisplayName != null) if (DisplayName != null && DisplayName.Length > 0)
{ {
if (DisplayName.Length < 3 || DisplayName.Length > 26) if (DisplayName.Length < 3 || DisplayName.Length > 26)
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)])); results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)]));
if (!ValidateDisplayname().IsMatch(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(); var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(Email)) if (!emailAttribute.IsValid(Email))
results.Add(new ValidationResult("Invalid email format.", [nameof(Email)])); results.Add(new ValidationResult("Invalid email format.", [nameof(Email)]));
} }
if (Visibility != null) if (Visibility != null && Visibility.HasValue)
{ {
if (Visibility < 0 || Visibility > 2) if (!Enum.IsDefined(typeof(Visibility), Visibility.Value))
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)])); results.Add(new ValidationResult($"Invalid visibility: {Visibility.Value}.", [nameof(Visibility)]));
} }
if (Roles != null) if (Roles != null && Roles.HasValue)
{ {
if (Roles.Length == 0) int validBits = Enum.GetValues(typeof(Role)).Cast<Role>().Aggregate(0, (acc, role) => acc | (int)role);
results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)])); if ((((int)Roles.Value) & validBits) != (int)Roles.Value || Roles.Value == 0)
int[] validRoles = [0, 1, 255, 403]; results.Add(new ValidationResult($"Invalid role: {Roles.Value}.", [nameof(Roles)]));
foreach (var role in Roles)
{
if (!validRoles.Contains(role))
results.Add(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)]));
}
} }
return results; return results;
} }
[GeneratedRegex("^[A-Za-z0-9_.]+$")] [GeneratedRegex("^[A-Za-z0-9_.]+(?: [A-Za-z0-9_.]+)*$")]
private static partial Regex ValidateDisplayname(); private static partial Regex ValidateDisplayname();
} }
} }
@@ -1,3 +1,6 @@
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs.User namespace SharpbinV3.Server.DTOs.User
{ {
public class UserSimpleDto public class UserSimpleDto
@@ -7,13 +10,15 @@ namespace SharpbinV3.Server.DTOs.User
public long CreatedAt { get; set; } public long CreatedAt { get; set; }
public string Username { get; set; } = string.Empty; public string Username { get; set; } = string.Empty;
public string? DisplayName { get; set; } public string? DisplayName { get; set; }
public int[] Roles { get; set; } = []; public Role Roles { get; set; } = Role.User;
public int Visibility { get; set; } public bool IsBanned { get; set; } = false;
public Visibility Visibility { get; set; }
} }
public class UserResponseDto : UserSimpleDto public class UserResponseDto : UserSimpleDto
{ {
public string? Email { get; set; } public string? Email { get; set; }
public bool EmailVerified { get; set; } = false;
public long? LastLogin { get; set; } public long? LastLogin { get; set; }
} }
} }
+14
View File
@@ -11,6 +11,8 @@ namespace SharpbinV3.Server.Data
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>(); public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<UserTotp> UserTotps => Set<UserTotp>(); public DbSet<UserTotp> UserTotps => Set<UserTotp>();
public DbSet<Report> Reports => Set<Report>(); public DbSet<Report> Reports => Set<Report>();
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
public DbSet<EmailVerificationToken> EmailVerificationTokens => Set<EmailVerificationToken>();
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
@@ -56,6 +58,18 @@ namespace SharpbinV3.Server.Data
.WithMany(u => u.Reports) .WithMany(u => u.Reports)
.HasForeignKey(r => r.UserUUID) .HasForeignKey(r => r.UserUUID)
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<ApiKey>()
.HasOne(a => a.User)
.WithMany(u => u.ApiKeys)
.HasForeignKey(a => a.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<EmailVerificationToken>()
.HasOne(a => a.User)
.WithMany(u => u.EmailVerificationTokens)
.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; }
}
}
@@ -0,0 +1,25 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
public enum EmailTokenType
{
VerifyEmail,
ResetPassword,
ChangeEmail,
DeleteAccount,
}
public sealed class EmailVerificationToken
{
[Key]
public Guid UUID { get; set; } = Guid.CreateVersion7();
public required Guid UserUUID { get; set; }
public User User { get; set; } = null!;
public required string TokenHash { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public long ExpiresAt { get; set; }
public required EmailTokenType Type { get; set; }
public bool Used { get; set; } = false;
}
}
+2 -1
View File
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data.Enums;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities namespace SharpbinV3.Server.Data.Entities
@@ -33,7 +34,7 @@ namespace SharpbinV3.Server.Data.Entities
public int Views { get; set; } public int Views { get; set; }
public string? Syntax { get; set; } public string? Syntax { get; set; }
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private (encrypted pastes handled on frontend) public Visibility Visibility { get; set; } = Visibility.Public;
public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never
+1 -5
View File
@@ -36,16 +36,12 @@ namespace SharpbinV3.Server.Data.Entities
public enum ReportStatus public enum ReportStatus
{ {
Open, Open,
InProgress,
Resolved,
Closed Closed
} }
public enum ReportType public enum ReportType
{ {
Spam,
Abuse,
InappropriateContent,
CopyrightViolation, CopyrightViolation,
IllegalContent,
Fraud, Fraud,
Other Other
} }
+18 -2
View File
@@ -1,8 +1,18 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data.Enums;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities namespace SharpbinV3.Server.Data.Entities
{ {
[Flags]
public enum Role
{
User = 1,
Moderator = 2,
Admin = 4
}
[Index(nameof(UID))] [Index(nameof(UID))]
[Index(nameof(UUID), IsUnique = true)] [Index(nameof(UUID), IsUnique = true)]
public sealed class User public sealed class User
@@ -15,14 +25,20 @@ namespace SharpbinV3.Server.Data.Entities
public required string PasswordHash { get; set; } public required string PasswordHash { get; set; }
public string? Email { get; set; } public string? Email { get; set; }
public bool EmailVerified { get; set; } = false;
public string? DisplayName { get; set; } public string? DisplayName { get; set; }
public long? LastLogin { get; set; } public long? LastLogin { get; set; }
public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin public Role Roles { get; set; } = Role.User;
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private public bool IsBanned { get; set; } = false;
public Visibility Visibility { get; set; } = Visibility.Public;
public List<Paste> Pastes { get; set; } = []; public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = []; public List<RefreshToken> RefreshTokens { get; set; } = [];
public List<Report> Reports { get; set; } = []; public List<Report> Reports { get; set; } = [];
public List<ApiKey> ApiKeys { get; set; } = [];
public List<EmailVerificationToken> EmailVerificationTokens { get; set; } = [];
public UserTotp? Totp { get; set; } public UserTotp? Totp { get; set; }
} }
} }
@@ -0,0 +1,9 @@
namespace SharpbinV3.Server.Data.Enums
{
public enum Visibility
{
Public = 0,
Unlisted = 1,
Private = 2
}
}
+26
View File
@@ -0,0 +1,26 @@
namespace SharpbinV3.Server
{
/// <summary>
/// https://dusted.codes/dotenv-in-dotnet
/// </summary>
public static class DotEnv
{
public static void Load(string filePath)
{
if (!File.Exists(filePath))
return;
foreach (var line in File.ReadAllLines(filePath))
{
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#"))
continue;
var parts = line.Split('=', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
continue;
Environment.SetEnvironmentVariable(parts[0], parts[1]);
}
}
}
}
+108
View File
@@ -0,0 +1,108 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{TITLE}}</title>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
body {
margin: 0;
padding: 0;
font-family: 'IBM Plex Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background-color: #0a0a0a;
color: #ffffff;
}
.container {
max-width: 600px;
margin: 40px auto;
background-color: #171717;
border: 2px solid #262626;
border-radius: 8px;
overflow: hidden;
}
.header {
background-color: #171717;
padding: 32px 30px;
border-bottom: 1px solid #262626;
}
.header h1 {
margin: 0;
font-size: 24px;
font-weight: 700;
color: #ffffff;
}
.content {
padding: 32px 30px;
}
.content h2 {
margin: 0 0 20px 0;
font-size: 20px;
font-weight: 600;
color: #ffffff;
}
.content p {
margin: 0 0 16px 0;
font-size: 15px;
line-height: 1.6;
color: #d4d4d4;
}
.button {
display: inline-block;
padding: 12px 24px;
background-color: #404040;
color: #ffffff !important;
text-decoration: none;
border-radius: 6px;
font-weight: 500;
font-size: 15px;
margin: 12px 0;
}
.button:hover {
background-color: #525252;
}
.link-box {
background-color: #262626;
padding: 16px;
border-radius: 6px;
margin: 16px 0;
word-break: break-all;
}
.link-box a {
color: #3b82f6;
text-decoration: underline;
font-size: 14px;
}
.footer {
padding: 24px 30px;
text-align: center;
background-color: #0a0a0a;
border-top: 1px solid #262626;
}
.footer p {
margin: 0 0 8px 0;
font-size: 13px;
color: #737373;
}
.footer .brand {
font-weight: 600;
color: #ffffff;
font-size: 15px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Sharpbin</h1>
</div>
<div class="content">
{{CONTENT}}
</div>
<div class="footer">
<p class="brand">Sharpbin</p>
<p>This is an automated email. Please do not reply to this message.</p>
</div>
</div>
</body>
</html>
@@ -0,0 +1,12 @@
<h2>Verify Your Email Address</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Thank you for signing up for Sharpbin. To complete your registration, please verify your email address by clicking the button below.</p>
<p style="text-align: center;">
<a href="{{VERIFICATION_URL}}" class="button">Verify Email Address</a>
</p>
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
<div class="link-box">
<a href="{{VERIFICATION_URL}}">{{VERIFICATION_URL}}</a>
</div>
<p><strong>This link will expire in 24 hours.</strong></p>
<p>If you didn't create an account with Sharpbin, you can safely ignore this email.</p>
@@ -1,42 +1,87 @@
using SharpbinV3.Server.Services; using System.IdentityModel.Tokens.Jwt;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Services;
namespace SharpbinV3.Server.Extensions namespace SharpbinV3.Server.Extensions
{ {
public static class HttpContextExtensions public static class HttpContextExtensions
{ {
public readonly static string[] ipHeaders = public static readonly string[] ipHeaders =
[ [
"X-Forwarded-For", "X-Forwarded-For",
"X-Real-IP", "X-Real-IP",
"CF-Connecting-IP", "CF-Connecting-IP",
"True-Client-IP", "True-Client-IP",
"X-Cluster-Client-IP", "X-Cluster-Client-IP",
"X-ProxyUser-IP" "X-ProxyUser-IP",
]; ];
private const string ApiKeyContextKey = "ApiKey";
private static string? GetClaimValue(IEnumerable<Claim> claims, params string[] claimTypes)
{
foreach (var claimType in claimTypes)
{
var value = claims.FirstOrDefault(c => c.Type == claimType)?.Value;
if (!string.IsNullOrEmpty(value))
return value;
}
return null;
}
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) public static JwtUser? GetJwtUser(this HttpContext context)
{ {
if (context.User == null || !context.User.Identity?.IsAuthenticated == true) if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
return null; return null;
var claims = context.User.Claims; var claims = context.User.Claims.ToArray();
var uuidClaim = claims.FirstOrDefault(c => c.Type == "uuid")?.Value; var uuidClaim = GetClaimValue(claims, "uuid");
if (string.IsNullOrEmpty(uuidClaim) || !Guid.TryParse(uuidClaim, out var uuid)) if (string.IsNullOrEmpty(uuidClaim) || !Guid.TryParse(uuidClaim, out var uuid))
return null; return null;
var username = claims.FirstOrDefault(c => c.Type == "username")?.Value ?? ""; var username = GetClaimValue(claims, "username") ?? "";
var displayName = claims.FirstOrDefault(c => c.Type == "displayname")?.Value ?? ""; var displayName = GetClaimValue(claims, "displayname") ?? "";
var totpEnabled = claims.FirstOrDefault(c => c.Type == "totp_enabled")?.Value == "True"; var totpEnabled = bool.TryParse(GetClaimValue(claims, "totp_enabled"), out var parsedTotpEnabled) && parsedTotpEnabled;
var isBanned = bool.TryParse(GetClaimValue(claims, "is_banned"), out var parsedIsBanned) && parsedIsBanned;
var rolesClaim = GetClaimValue(claims, "roles", "role", ClaimTypes.Role);
var roles = int.TryParse(rolesClaim, out var roleInt) ? (Role)roleInt : Role.User;
var roles = claims var expClaim = GetClaimValue(claims, JwtRegisteredClaimNames.Exp, ClaimTypes.Expiration, "exp");
.Where(c => c.Type == ClaimTypes.Role) var expires =
.Select(c => int.TryParse(c.Value, out var r) ? r : 0) expClaim != null && long.TryParse(expClaim, out var expUnix)
.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 ? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime
: DateTime.UtcNow.AddMinutes(15); : DateTime.UtcNow.AddMinutes(15);
@@ -46,8 +91,9 @@ namespace SharpbinV3.Server.Extensions
Username = username, Username = username,
DisplayName = displayName, DisplayName = displayName,
TotpEnabled = totpEnabled, TotpEnabled = totpEnabled,
Roles = roles.Length > 0 ? roles : [0], Roles = roles,
Expires = expires IsBanned = isBanned,
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");
}
}
}
@@ -0,0 +1,453 @@
// <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("20260221080317_EmailVerificationToken")]
partial class EmailVerificationToken
{
/// <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.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
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<bool>("EmailVerified")
.HasColumnType("INTEGER");
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.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.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("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,61 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class EmailVerificationToken : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "EmailVerified",
table: "Users",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "EmailVerificationTokens",
columns: table => new
{
UUID = table.Column<Guid>(type: "TEXT", nullable: false),
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
TokenHash = table.Column<string>(type: "TEXT", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
ExpiresAt = table.Column<long>(type: "INTEGER", nullable: false),
Type = table.Column<int>(type: "INTEGER", nullable: false),
Used = table.Column<bool>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_EmailVerificationTokens", x => x.UUID);
table.ForeignKey(
name: "FK_EmailVerificationTokens_Users_UserUUID",
column: x => x.UserUUID,
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_EmailVerificationTokens_UserUUID",
table: "EmailVerificationTokens",
column: "UserUUID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "EmailVerificationTokens");
migrationBuilder.DropColumn(
name: "EmailVerified",
table: "Users");
}
}
}
@@ -0,0 +1,455 @@
// <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("20260310055909_FlaggedRolesEnumVisiblity")]
partial class FlaggedRolesEnumVisiblity
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.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.Enums.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.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.Enums.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.Enums.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.Enums.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.Enums.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<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
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.Enums.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.Enums.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Enums.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
{
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class FlaggedRolesEnumVisiblity : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "Roles",
table: "Users",
type: "INTEGER",
nullable: false,
oldClrType: typeof(string),
oldType: "TEXT");
migrationBuilder.AddColumn<bool>(
name: "IsBanned",
table: "Users",
type: "INTEGER",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsBanned",
table: "Users");
migrationBuilder.AlterColumn<string>(
name: "Roles",
table: "Users",
type: "TEXT",
nullable: false,
oldClrType: typeof(int),
oldType: "INTEGER");
}
}
}
@@ -0,0 +1,455 @@
// <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("20260310072309_CorrectNamespaceRename")]
partial class CorrectNamespaceRename
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
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.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
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<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
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.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.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("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class CorrectNamespaceRename : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
@@ -15,7 +15,69 @@ namespace SharpbinV3.Server.Migrations
protected override void BuildModel(ModelBuilder modelBuilder) protected override void BuildModel(ModelBuilder modelBuilder)
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1"); modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
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.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{ {
@@ -228,6 +290,12 @@ namespace SharpbinV3.Server.Migrations
b.Property<string>("Email") b.Property<string>("Email")
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin") b.Property<long?>("LastLogin")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -235,9 +303,8 @@ namespace SharpbinV3.Server.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.PrimitiveCollection<string>("Roles") b.Property<int>("Roles")
.IsRequired() .HasColumnType("INTEGER");
.HasColumnType("TEXT");
b.Property<int?>("UID") b.Property<int?>("UID")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
@@ -276,6 +343,28 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("UserTotps"); 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.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
@@ -345,6 +434,10 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{ {
b.Navigation("ApiKeys");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes"); b.Navigation("Pastes");
b.Navigation("RefreshTokens"); b.Navigation("RefreshTokens");
+188 -66
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.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using SharpbinV3.Server.Authentication;
using SharpbinV3.Server.Authorization; using SharpbinV3.Server.Authorization;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Extensions;
@@ -11,9 +17,6 @@ using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification; using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers; using SharpbinV3.Server.Services.Verification.Providers;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
namespace SharpbinV3.Server namespace SharpbinV3.Server
{ {
@@ -21,18 +24,44 @@ namespace SharpbinV3.Server
{ {
public static void Main(string[] args) public static void Main(string[] args)
{ {
DotEnv.Load(".env");
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
builder.Services.AddControllers() builder
.Services.AddControllers()
.AddJsonOptions(options => .AddJsonOptions(options =>
{ {
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
}); });
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi // 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 => builder.Services.AddDbContext<AppDbContext>(opt =>
{ {
opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")); opt.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
@@ -40,33 +69,68 @@ namespace SharpbinV3.Server
builder.Services.AddSingleton<ICompressionService, CompressionService>(); builder.Services.AddSingleton<ICompressionService, CompressionService>();
builder.Services.AddSingleton<IHostedService, PasteCleanUpService>(); builder.Services.AddSingleton<IHostedService, PasteCleanUpService>();
builder.Services.AddSingleton<IHostedService, PasteViewCleanUpService>(); builder.Services.AddSingleton<IHostedService, PasteViewCleanUpService>();
builder.Services.AddSingleton<EmailService>();
builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<EmailService>());
builder.Services.AddScoped<UserService>(); builder.Services.AddScoped<UserService>();
builder.Services.AddScoped<AuthService>(); builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<PasteService>(); builder.Services.AddScoped<PasteService>();
builder.Services.AddScoped<ApiKeyService>();
builder.Services.AddScoped<VerificationService>(); builder.Services.AddScoped<VerificationService>();
builder.Services.AddScoped<TotpVerificationProvider>(); builder.Services.AddScoped<TotpVerificationProvider>();
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>(); builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
builder.Services.AddScoped<ReportService>(); builder.Services.AddScoped<ReportService>();
builder.Services.AddMemoryCache(); builder.Services.AddMemoryCache();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddHealthChecks() builder.Services.AddHealthChecks().AddDbContextCheck<AppDbContext>("Database");
.AddDbContextCheck<AppDbContext>("Database");
builder.Services.AddOptions<PasteSettings>() builder
.Services.AddOptions<PasteSettings>()
.Bind(builder.Configuration.GetSection("PasteSettings")) .Bind(builder.Configuration.GetSection("PasteSettings"))
.ValidateDataAnnotations() .ValidateDataAnnotations()
.ValidateOnStart(); .ValidateOnStart();
builder.Services.AddOptions<JWTSettings>() builder
.Services.AddOptions<JWTSettings>()
.Bind(builder.Configuration.GetSection("JwtSettings")) .Bind(builder.Configuration.GetSection("JwtSettings"))
.ValidateDataAnnotations() .ValidateDataAnnotations()
.ValidateOnStart(); .ValidateOnStart();
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings")); builder.Services.AddOptions<AppSettings>().Bind(builder.Configuration).ValidateDataAnnotations().ValidateOnStart();
builder.Services.AddOptions<AuthSettings>().Bind(builder.Configuration.GetSection("AuthSettings")).ValidateDataAnnotations();
builder.Services.AddOptions<EmailSettings>().Bind(builder.Configuration.GetSection("EmailSettings")).ValidateDataAnnotations();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) builder
.AddJwtBearer(); .Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = AuthSchemes.Combined;
options.DefaultScheme = AuthSchemes.Combined;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddPolicyScheme(
AuthSchemes.Combined,
AuthSchemes.Combined,
options =>
{
options.ForwardDefaultSelector = context =>
{
var apiKeyHeader = context.Request.Headers["X-API-Key"].ToString();
if (!string.IsNullOrEmpty(apiKeyHeader))
return AuthSchemes.ApiKey;
builder.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme) var authHeader = context.Request.Headers.Authorization.ToString();
.Configure<IOptions<JWTSettings>>((options, jwtSettings) => if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
return JwtBearerDefaults.AuthenticationScheme;
return JwtBearerDefaults.AuthenticationScheme;
};
}
)
.AddJwtBearer()
.AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>(AuthSchemes.ApiKey, _ => { });
builder
.Services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<JWTSettings>>(
(options, jwtSettings) =>
{ {
var settings = jwtSettings.Value; var settings = jwtSettings.Value;
var key = Encoding.UTF8.GetBytes(settings.Secret); var key = Encoding.UTF8.GetBytes(settings.Secret);
@@ -88,24 +152,45 @@ namespace SharpbinV3.Server
ClockSkew = TimeSpan.Zero, ClockSkew = TimeSpan.Zero,
RequireSignedTokens = true, RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256] ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
}; };
}); }
);
builder.Services.AddAuthorizationBuilder() builder.Services.AddAuthorizationBuilder().AddPolicy("NotBanned", policy => policy.Requirements.Add(new NotBannedRequirement()));
.AddPolicy("NotBanned", policy => builder.Services.AddAuthorizationBuilder().AddPolicy("AuthAndNotBanned", policy => policy.Requirements.Add(new NotBannedRequirement()));
policy.Requirements.Add(new NotBannedRequirement())); builder
builder.Services.AddAuthorizationBuilder() .Services.AddAuthorizationBuilder()
.AddPolicy("AuthAndNotBanned", policy => .AddPolicy(
policy.Requirements.Add(new NotBannedRequirement())); "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(false));
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true)); builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true));
builder.Services.AddRateLimiter(options => builder.Services.AddRateLimiter(options =>
{ {
options.AddPolicy("Sliding", httpContext => options.AddPolicy(
RateLimitPartition.GetSlidingWindowLimiter(httpContext.GetRequestIP(), _ => new SlidingWindowRateLimiterOptions "Sliding",
httpContext =>
RateLimitPartition.GetSlidingWindowLimiter(
httpContext.GetRequestIP(),
_ => new SlidingWindowRateLimiterOptions
{ {
Window = TimeSpan.FromSeconds(10), Window = TimeSpan.FromSeconds(10),
PermitLimit = 10, PermitLimit = 10,
@@ -113,10 +198,15 @@ namespace SharpbinV3.Server
SegmentsPerWindow = 5, SegmentsPerWindow = 5,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
} }
)); )
);
options.AddPolicy("Strict", httpContext => options.AddPolicy(
RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions "Strict",
httpContext =>
RateLimitPartition.GetTokenBucketLimiter(
httpContext.GetRequestIP(),
_ => new TokenBucketRateLimiterOptions
{ {
TokenLimit = 5, TokenLimit = 5,
QueueLimit = 0, QueueLimit = 0,
@@ -125,10 +215,15 @@ namespace SharpbinV3.Server
AutoReplenishment = true, AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
} }
)); )
);
options.AddPolicy("Sensitive", httpContext => options.AddPolicy(
RateLimitPartition.GetTokenBucketLimiter(httpContext.GetRequestIP(), _ => new TokenBucketRateLimiterOptions "Sensitive",
httpContext =>
RateLimitPartition.GetTokenBucketLimiter(
httpContext.GetRequestIP(),
_ => new TokenBucketRateLimiterOptions
{ {
TokenLimit = 3, TokenLimit = 3,
QueueLimit = 0, QueueLimit = 0,
@@ -137,7 +232,8 @@ namespace SharpbinV3.Server
AutoReplenishment = true, AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
} }
)); )
);
options.AddPolicy("NoLimit", _ => RateLimitPartition.GetNoLimiter(0)); options.AddPolicy("NoLimit", _ => RateLimitPartition.GetNoLimiter(0));
@@ -145,53 +241,52 @@ namespace SharpbinV3.Server
{ {
var remoteIp = httpContext.GetRequestIP(); var remoteIp = httpContext.GetRequestIP();
return RateLimitPartition.GetFixedWindowLimiter(remoteIp, _ => new FixedWindowRateLimiterOptions return RateLimitPartition.GetFixedWindowLimiter(
remoteIp,
_ => new FixedWindowRateLimiterOptions
{ {
PermitLimit = 100, PermitLimit = 100,
Window = TimeSpan.FromMinutes(1), Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst, QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0 QueueLimit = 0,
}); }
);
}); });
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) => options.OnRejected = async (context, cancellationToken) =>
{ {
await context.HttpContext.Response.WriteAsJsonAsync(new await context.HttpContext.Response.WriteAsJsonAsync(
{ new { success = false, Message = "Too many requests. Please try again later." },
success = false, cancellationToken: cancellationToken
Message = "Too many requests. Please try again later." );
}, cancellationToken: cancellationToken);
}; };
}); });
builder.Services.AddOutputCache(options => builder.Services.AddOutputCache(options =>
{ {
options.AddPolicy("1Day", builder => options.AddPolicy(
"1Day",
builder =>
{ {
builder.Expire(TimeSpan.FromDays(1)); builder.Expire(TimeSpan.FromDays(1));
}); }
);
}); });
builder.Services.AddCors(o => builder.Services.AddCors(o =>
{ {
o.AddDefaultPolicy(p => o.AddDefaultPolicy(p => p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod());
p.WithOrigins("http://localhost:5173")
.AllowAnyHeader()
.AllowAnyMethod());
}); });
builder.Services.AddDataProtection() builder
.Services.AddDataProtection()
.PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment)) .PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment))
.SetApplicationName("SharpbinV3"); .SetApplicationName("SharpbinV3");
var app = builder.Build(); var app = builder.Build();
app.UseRateLimiter(); app.UseRateLimiter();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi(); app.MapOpenApi();
}
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseCors(); app.UseCors();
@@ -209,7 +304,8 @@ namespace SharpbinV3.Server
db.Database.Migrate(); db.Database.Migrate();
// this is temporary since the migration doesnt seem to work properly // 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 CREATE TRIGGER IF NOT EXISTS Users_UID_AutoIncrement
AFTER INSERT ON Users AFTER INSERT ON Users
BEGIN BEGIN
@@ -219,20 +315,45 @@ namespace SharpbinV3.Server
) )
WHERE rowid = NEW.rowid AND NEW.UID IS NULL; WHERE rowid = NEW.rowid AND NEW.UID IS NULL;
END; END;
"""); """
);
} }
app.MapHealthChecks("/health"); app.MapHealthChecks("/health");
app.MapGet("/api/stats", async (AppDbContext db) => app.MapGet(
"/api/stats",
async (AppDbContext db) =>
{ {
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 pasteCount = await db.Pastes.CountAsync();
var userCount = await db.Users.CountAsync(); var userCount = await db.Users.CountAsync();
var totalPasteSize = await db.Pastes.SumAsync(p => p.Size); var totalPasteSize = await db.Pastes.SumAsync(p => p.Size);
var pastSevenDays = DateTimeOffset.UtcNow.AddDays(-7).ToUnixTimeMilliseconds(); var trueTotalPasteSize = await db.Pastes.SumAsync(p => p.TrueSize);
var pasteCountWeek = await db.Pastes.CountAsync(p => p.CreatedAt >= pastSevenDays);
return Results.Ok(new 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--)
{
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, success = true,
stats = new stats = new
@@ -241,27 +362,28 @@ namespace SharpbinV3.Server
{ {
total = pasteCount, total = pasteCount,
past7Days = pasteCountWeek, past7Days = pasteCountWeek,
totalSizeInBytes = totalPasteSize totalSizeInBytes = totalPasteSize,
trueTotalSizeInBytes = trueTotalPasteSize,
daily = dailyStats,
}, },
users = new users = new { total = userCount },
{
total = userCount
}, },
} }
}); );
}).CacheOutput(policy => policy.Expire(TimeSpan.FromDays(1)).Tag("stats")); }
)
.CacheOutput(policy => policy.Expire(TimeSpan.FromHours(6)).Tag("stats"));
app.Run(); app.Run();
} }
static DirectoryInfo GetDataProtectionKeyDirectory(IHostEnvironment env) static DirectoryInfo GetDataProtectionKeyDirectory(IHostEnvironment env)
{ {
var overridepath = Environment.GetEnvironmentVariable("DATA_PROTECTION_KEY_PATH"); var overridepath = Environment.GetEnvironmentVariable("DATA_PROTECTION_KEY_PATH");
if (!string.IsNullOrEmpty(overridepath)) if (!string.IsNullOrEmpty(overridepath))
return new DirectoryInfo(overridepath); return new DirectoryInfo(overridepath);
var basePath = env.IsDevelopment() var basePath = env.IsDevelopment() ? Environment.CurrentDirectory : Environment.SpecialFolder.ApplicationData.ToString();
? Environment.CurrentDirectory
: Environment.SpecialFolder.ApplicationData.ToString();
var path = Path.Combine(basePath, "SharpbinV3", "DataProtectionKeys"); 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`). - `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=/app/data/sharpbin.db`).
- `JwtSettings__Secret`: A secure string used for signing JWT tokens. - `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_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. - `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 dotnet watch run
``` ```
The API will be accessible at http://localhost:8080 by default (check `Properties/launchSettings.json` or your specific configuration). The API will be accessible at http://localhost:5050 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
@@ -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();
}
}
}
+111 -48
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.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs.Auth; using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Bcrypt = BCrypt.Net.BCrypt; using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.Services namespace SharpbinV3.Server.Services
@@ -18,15 +19,29 @@ namespace SharpbinV3.Server.Services
public string Username { get; set; } = string.Empty; public string Username { get; set; } = string.Empty;
public string DisplayName { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty;
public bool TotpEnabled { get; set; } public bool TotpEnabled { get; set; }
public int[] Roles { get; set; } = []; public Role Roles { get; set; }
public bool IsBanned { get; set; }
public DateTime Expires { 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,
EmailService email,
IOptions<JWTSettings> jwtOptions,
IOptions<AuthSettings> authOptions,
IOptions<AppSettings> appSettings,
IOptions<EmailSettings> emailSettings,
ILogger<AuthService> logger
)
{ {
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
private readonly EmailService _email = email;
private readonly JWTSettings _jwtSettings = jwtOptions.Value; private readonly JWTSettings _jwtSettings = jwtOptions.Value;
private readonly AuthSettings _authSettings = authOptions.Value; private readonly AuthSettings _authSettings = authOptions.Value;
private readonly AppSettings _appSettings = appSettings.Value;
private readonly EmailSettings _emailSettings = emailSettings.Value;
private readonly ILogger _logger = logger; private readonly ILogger _logger = logger;
private const int EmailVerificationTokenLength = 64;
public async Task<User> CreateUser(string username, string password, string? email, string? displayName) public async Task<User> CreateUser(string username, string password, string? email, string? displayName)
{ {
@@ -36,16 +51,17 @@ namespace SharpbinV3.Server.Services
PasswordHash = Bcrypt.HashPassword(password), PasswordHash = Bcrypt.HashPassword(password),
Email = email, Email = email,
DisplayName = displayName, DisplayName = displayName,
UUID = Guid.CreateVersion7() UUID = Guid.CreateVersion7(),
}; };
if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync()) if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync())
user.Roles = [0, 1, 255]; user.Roles = Role.User | Role.Admin;
_db.Users.Add(user); _db.Users.Add(user);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return user; return user;
} }
public async Task<CreateJWT> GenerateJWTToken(User user) public async Task<CreateJWT> GenerateJWTToken(User user)
{ {
var jwtHandler = new JwtSecurityTokenHandler(); var jwtHandler = new JwtSecurityTokenHandler();
@@ -58,36 +74,25 @@ namespace SharpbinV3.Server.Services
new("username", user.Username), new("username", user.Username),
new("displayname", user.DisplayName ?? ""), new("displayname", user.DisplayName ?? ""),
new("totp_enabled", totpEnabled.ToString()), new("totp_enabled", totpEnabled.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) new("roles", ((int)user.Roles).ToString()),
new("is_banned", user.IsBanned.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
}; };
if (user.Roles != null)
{
foreach (var role in user.Roles)
claims.Add(new Claim(ClaimTypes.Role, role.ToString()));
}
else
{
claims.Add(new Claim(ClaimTypes.Role, "0"));
}
var descriptor = new SecurityTokenDescriptor var descriptor = new SecurityTokenDescriptor
{ {
Subject = new ClaimsIdentity(claims), Subject = new ClaimsIdentity(claims),
Issuer = _jwtSettings.Issuer, Issuer = _jwtSettings.Issuer,
Audience = _jwtSettings.Audience, Audience = _jwtSettings.Audience,
Expires = DateTime.UtcNow.AddMinutes(15), Expires = DateTime.UtcNow.AddMinutes(15),
SigningCredentials = new SigningCredentials( SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature
)
}; };
var token = jwtHandler.CreateToken(descriptor); var token = jwtHandler.CreateToken(descriptor);
var jwtToken = jwtHandler.WriteToken(token); var jwtToken = jwtHandler.WriteToken(token);
var jti = claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value; 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 var refreshToken = new RefreshToken
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
@@ -97,7 +102,7 @@ namespace SharpbinV3.Server.Services
CreatedAt = DateTimeOffset.UtcNow, CreatedAt = DateTimeOffset.UtcNow,
ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6), ExpiresAt = DateTimeOffset.UtcNow.AddMonths(6),
Used = false, Used = false,
Revoked = false Revoked = false,
}; };
await _db.RefreshTokens.AddAsync(refreshToken); await _db.RefreshTokens.AddAsync(refreshToken);
@@ -107,7 +112,7 @@ namespace SharpbinV3.Server.Services
{ {
Token = jwtToken, Token = jwtToken,
Success = true, Success = true,
RefreshToken = rawRefreshToken RefreshToken = rawRefreshToken,
}; };
} }
@@ -118,7 +123,9 @@ namespace SharpbinV3.Server.Services
try try
{ {
var principal = jwtHandler.ValidateToken(token, new TokenValidationParameters var principal = jwtHandler.ValidateToken(
token,
new TokenValidationParameters
{ {
ValidateIssuerSigningKey = true, ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key), IssuerSigningKey = new SymmetricSecurityKey(key),
@@ -129,41 +136,42 @@ namespace SharpbinV3.Server.Services
ClockSkew = TimeSpan.Zero, ClockSkew = TimeSpan.Zero,
ValidateLifetime = false, ValidateLifetime = false,
RequireSignedTokens = true, RequireSignedTokens = true,
ValidAlgorithms = [SecurityAlgorithms.HmacSha256] ValidAlgorithms = [SecurityAlgorithms.HmacSha256],
}, out SecurityToken validatedToken); },
out SecurityToken validatedToken
);
var jti = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value; var jti = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value;
var userUUID = principal.Claims.First(c => c.Type == "uuid").Value;
var tokenHash = Utilities.ComputeSha256(refreshToken); var tokenHash = Utilities.ComputeSha256(refreshToken);
var storedToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash);
var storedToken = await _db.RefreshTokens if (
.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash); storedToken == null
if (storedToken == null
|| storedToken.Used || storedToken.Used
|| storedToken.Revoked || storedToken.Revoked
|| storedToken.ExpiresAt < DateTimeOffset.UtcNow || storedToken.ExpiresAt < DateTimeOffset.UtcNow
|| storedToken.JwtId != jti) || storedToken.JwtId != jti
|| storedToken.UserUUID != Guid.Parse(userUUID)
)
{ {
return new CreateJWT return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] };
{
Success = false,
Errors = ["Invalid or expired refresh token."]
};
} }
var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID == Guid.Parse(userUUID));
if (user == null)
return new CreateJWT { Success = false, Errors = ["Invalid token."] };
var newTokenResult = await GenerateJWTToken(user);
if (!newTokenResult.Success)
return newTokenResult;
storedToken.Used = true; storedToken.Used = true;
storedToken.Revoked = true; storedToken.Revoked = true;
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
var userUUID = principal.Claims.First(c => c.Type == "uuid").Value; return newTokenResult;
var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID == Guid.Parse(userUUID));
if (user == null || storedToken.UserUUID != Guid.Parse(userUUID))
return new CreateJWT { Success = false, Errors = ["Invalid token."] };
return await GenerateJWTToken(user);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -172,7 +180,6 @@ namespace SharpbinV3.Server.Services
} }
} }
public async Task<User> UpdateUser(User user) public async Task<User> UpdateUser(User user)
{ {
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found"); var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
@@ -186,6 +193,7 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return user; return user;
} }
public async Task UpdateLoginTime(User user) public async Task UpdateLoginTime(User user)
{ {
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found"); var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
@@ -196,11 +204,66 @@ namespace SharpbinV3.Server.Services
public async Task<User?> GetUserFromHttpContext(HttpContext context) 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; var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "uuid")?.Value;
if (uuidClaim == null) if (uuidClaim == null)
return null; return null;
var userUUID = Guid.Parse(uuidClaim); var userUUID = Guid.Parse(uuidClaim);
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID); return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID);
} }
public async Task SendEmailVerification(User user)
{
if (string.IsNullOrWhiteSpace(user.Email))
return;
string token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
string tokenHash = Utilities.ComputeSha256(token);
string verificationUrl = $"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}";
string emailBody = EmailTemplates.VerifyEmail(verificationUrl, user.Username);
await _email.SendAsync(user.Email, "Verify Your Email - Sharpbin", emailBody);
var verificationToken = new EmailVerificationToken
{
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
ExpiresAt = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(),
Type = EmailTokenType.VerifyEmail,
};
await _db.EmailVerificationTokens.AddAsync(verificationToken);
await _db.SaveChangesAsync();
}
public async Task<(bool success, string message)> VerifyEmailVerificationToken(string token)
{
if (token.Length != EmailVerificationTokenLength)
return (false, "Invalid token.");
string tokenHash = Utilities.ComputeSha256(token);
var verificationToken = await _db.EmailVerificationTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.TokenHash == tokenHash);
if (
verificationToken == null
|| verificationToken.User == null
|| verificationToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|| verificationToken.Used
)
return (false, "Token is expired or already used.");
if (verificationToken != null && !verificationToken.Used)
{
verificationToken.Used = true;
verificationToken.User.EmailVerified = true;
await _db.SaveChangesAsync();
}
await _db.SaveChangesAsync();
return (true, "Email successfully verified.");
}
} }
} }
@@ -1,6 +1,5 @@
using System.IO.Compression; using System.IO.Compression;
namespace SharpbinV3.Server.Services namespace SharpbinV3.Server.Services
{ {
public class CompressionService : ICompressionService public class CompressionService : ICompressionService
@@ -21,11 +20,13 @@ namespace SharpbinV3.Server.Services
return data; return data;
} }
public byte[] Compress(string data) public byte[] Compress(string data)
{ {
ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(data);
return Compress(System.Text.Encoding.UTF8.GetBytes(data)); return Compress(System.Text.Encoding.UTF8.GetBytes(data));
} }
public byte[] Decompress(byte[] compressedData) public byte[] Decompress(byte[] compressedData)
{ {
ArgumentNullException.ThrowIfNull(compressedData); ArgumentNullException.ThrowIfNull(compressedData);
@@ -0,0 +1,76 @@
using System.Threading.Channels;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;
using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Services
{
public class EmailService(IOptions<EmailSettings> emailSettings, ILogger<EmailService> logger) : BackgroundService
{
private readonly EmailSettings settings = emailSettings.Value;
private readonly Channel<QueuedEmail> queue = Channel.CreateUnbounded<QueuedEmail>(
new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }
);
public async Task SendAsync(string to, string subject, string body)
{
if (
string.IsNullOrWhiteSpace(settings.Host)
|| string.IsNullOrWhiteSpace(settings.User)
|| string.IsNullOrWhiteSpace(settings.Password)
|| string.IsNullOrWhiteSpace(settings.From)
)
{
logger.LogWarning($"Email settings are not fully configured. Skipping sending email to {to}");
return;
}
var email = new QueuedEmail(to, subject, body);
if (queue.Writer.TryWrite(email))
return;
await queue.Writer.WriteAsync(email);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var email in queue.Reader.ReadAllAsync(stoppingToken))
{
try
{
await SendNowAsync(email, stoppingToken);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to send email to {EmailTo}", email.To);
}
}
}
private async Task SendNowAsync(QueuedEmail email, CancellationToken cancellationToken)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Sharpbin", settings.From!));
message.To.Add(MailboxAddress.Parse(email.To));
message.Subject = email.Subject;
message.Body = new TextPart("html") { Text = email.Body };
using var smtp = new SmtpClient();
await smtp.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.StartTls, cancellationToken);
await smtp.AuthenticateAsync(settings.User, settings.Password, cancellationToken);
await smtp.SendAsync(message, cancellationToken);
await smtp.DisconnectAsync(true, cancellationToken);
}
private readonly record struct QueuedEmail(string To, string Subject, string Body);
}
}
@@ -0,0 +1,41 @@
using System.Reflection;
namespace SharpbinV3.Server.Services
{
public static class EmailTemplates
{
private static readonly Assembly Assembly = Assembly.GetExecutingAssembly();
private static readonly string BaseTemplateName = "SharpbinV3.Server.EmailTemplates.Base.html";
private static string LoadEmbeddedResource(string resourceName)
{
using var stream = Assembly.GetManifestResourceStream(resourceName);
if (stream == null)
throw new FileNotFoundException($"Embedded resource not found: {resourceName}");
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
private static string RenderTemplate(string title, string contentTemplate, Dictionary<string, string> replacements)
{
var baseTemplate = LoadEmbeddedResource(BaseTemplateName);
var content = contentTemplate;
foreach (var (key, value) in replacements)
{
content = content.Replace($"{{{{{key}}}}}", value);
}
return baseTemplate.Replace("{{TITLE}}", title).Replace("{{CONTENT}}", content);
}
public static string VerifyEmail(string verificationUrl, string username)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.VerifyEmail.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "VERIFICATION_URL", verificationUrl } };
return RenderTemplate("Verify Your Email", contentTemplate, replacements);
}
}
}
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.Services
public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger<PasteCleanUpService> logger) : BackgroundService public class PasteCleanUpService(IServiceProvider serviceProvider, ILogger<PasteCleanUpService> logger) : BackgroundService
{ {
private readonly TimeSpan _period = TimeSpan.FromMinutes(5); private readonly TimeSpan _period = TimeSpan.FromMinutes(5);
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
using var timer = new PeriodicTimer(_period); using var timer = new PeriodicTimer(_period);
+12 -36
View File
@@ -4,17 +4,13 @@ using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.Extensions; using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Services namespace SharpbinV3.Server.Services
{ {
public sealed class PasteService( public sealed class PasteService(AppDbContext db, ICompressionService cs, IMemoryCache cache, IOptions<PasteSettings> options)
AppDbContext db,
ICompressionService cs,
IMemoryCache cache,
IOptions<PasteSettings> options
)
{ {
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs; private readonly ICompressionService _cs = cs;
@@ -28,7 +24,7 @@ namespace SharpbinV3.Server.Services
string content, string content,
string title, string title,
string syntax, string syntax,
int visibility, Visibility visibility,
long expiresAt, long expiresAt,
bool shouldCompress bool shouldCompress
) )
@@ -40,7 +36,7 @@ namespace SharpbinV3.Server.Services
var paste = new Paste var paste = new Paste
{ {
UUID = Guid.CreateVersion7(), UUID = Guid.CreateVersion7(),
ID = Utilities.GenerateRandomString(8), ID = Utilities.GenerateSecureRandomString(8),
Title = title, Title = title,
AuthorUUID = author?.UUID, AuthorUUID = author?.UUID,
User = author, User = author,
@@ -114,10 +110,7 @@ namespace SharpbinV3.Server.Services
return result > 0; return result > 0;
} }
public async Task<(Paste? paste, bool alreadyExists)> RecordView( public async Task<(Paste? paste, bool alreadyExists)> RecordView(Paste paste, HttpContext context)
Paste paste,
HttpContext context
)
{ {
if (paste == null) if (paste == null)
return (null, false); return (null, false);
@@ -132,21 +125,11 @@ namespace SharpbinV3.Server.Services
string viewerHash; string viewerHash;
if (viewerUser != null) if (viewerUser != null)
viewerHash = Utilities.ComputeHmacSha256( viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerUser.UUID.ToString());
_pasteSettings.View_HMAC_Secret,
viewerUser.UUID.ToString()
);
else else
viewerHash = Utilities.ComputeHmacSha256( viewerHash = Utilities.ComputeHmacSha256(_pasteSettings.View_HMAC_Secret, viewerIp + viewerUserAgent);
_pasteSettings.View_HMAC_Secret,
viewerIp + viewerUserAgent
);
if ( if (await _db.PasteViews.AnyAsync(pv => pv.PastePID == paste.PID && pv.ViewerHash == viewerHash))
await _db.PasteViews.AnyAsync(pv =>
pv.PastePID == paste.PID && pv.ViewerHash == viewerHash
)
)
return (null, true); return (null, true);
_db.PasteViews.Add( _db.PasteViews.Add(
@@ -176,9 +159,7 @@ namespace SharpbinV3.Server.Services
async entry => async entry =>
{ {
entry.SetSlidingExpiration(TimeSpan.FromMinutes(10)); entry.SetSlidingExpiration(TimeSpan.FromMinutes(10));
return await _db return await _db.Pastes.Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
.Pastes.Include(p => p.User)
.FirstOrDefaultAsync(p => p.ID == id);
} }
); );
return paste ?? null; return paste ?? null;
@@ -201,12 +182,7 @@ namespace SharpbinV3.Server.Services
if (publicOnly) if (publicOnly)
query = query.Where(p => p.Visibility == 0); query = query.Where(p => p.Visibility == 0);
return await query return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync();
.OrderByDescending(p => p.PID)
.Skip(offset)
.Take(count)
.Include(p => p.User)
.ToListAsync();
} }
); );
@@ -223,9 +199,9 @@ namespace SharpbinV3.Server.Services
return title.Length <= _pasteSettings.MaxTitleLength; return title.Length <= _pasteSettings.MaxTitleLength;
} }
public bool ValidateVisibility(int visibility) public bool ValidateVisibility(Visibility visibility)
{ {
return visibility >= 0 && visibility <= 2; return Enum.IsDefined(typeof(Visibility), visibility);
} }
public bool ValidateExpiresAt(long expiresAt) public bool ValidateExpiresAt(long expiresAt)
@@ -3,21 +3,16 @@ using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services namespace SharpbinV3.Server.Services
{ {
public sealed class PasteViewCleanUpService( public sealed class PasteViewCleanUpService(IServiceProvider serviceProvider, ILogger<PasteViewCleanUpService> logger) : BackgroundService
IServiceProvider serviceProvider,
ILogger<PasteViewCleanUpService> logger
) : BackgroundService
{ {
private static readonly TimeSpan Period = TimeSpan.FromHours(1); private static readonly TimeSpan Period = TimeSpan.FromHours(1);
private static readonly long RetentionMs = private static readonly long RetentionMs = (long)TimeSpan.FromDays(7).TotalMilliseconds;
(long)TimeSpan.FromDays(7).TotalMilliseconds;
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
using var timer = new PeriodicTimer(Period); using var timer = new PeriodicTimer(Period);
while (!stoppingToken.IsCancellationRequested && while (!stoppingToken.IsCancellationRequested && await timer.WaitForNextTickAsync(stoppingToken))
await timer.WaitForNextTickAsync(stoppingToken))
{ {
try try
{ {
@@ -35,16 +30,12 @@ namespace SharpbinV3.Server.Services
using var scope = serviceProvider.CreateScope(); using var scope = serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>(); var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var cutoff = var cutoff = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - RetentionMs;
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - RetentionMs;
var deleted = await db.PasteViews var deleted = await db.PasteViews.Where(v => v.ViewedAt < cutoff).ExecuteDeleteAsync(token);
.Where(v => v.ViewedAt < cutoff)
.ExecuteDeleteAsync(token);
if (deleted > 0) if (deleted > 0)
logger.LogInformation("Deleted {Count} stale paste views", deleted); logger.LogInformation("Deleted {Count} stale paste views", deleted);
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More