Compare commits

...
Author SHA1 Message Date
dependabot[bot] 0d551b887f chore(deps): bump esbuild
Bumps the npm_and_yarn group with 1 update in the /SharpbinV3.Client directory: [esbuild](https://github.com/evanw/esbuild).


Updates `esbuild` from 0.27.2 to 0.27.7
- [Release notes](https://github.com/evanw/esbuild/releases)
- [Changelog](https://github.com/evanw/esbuild/blob/main/CHANGELOG-2025.md)
- [Commits](https://github.com/evanw/esbuild/compare/v0.27.2...v0.27.7)

---
updated-dependencies:
- dependency-name: esbuild
  dependency-version: 0.27.7
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-14 11:59:50 +00:00
whoswhip c6ba7b2ea9 Merge branch 'SharpbinV3' of github.com:whoswhip/Sharpbin into SharpbinV3 2026-06-13 20:15:44 -04:00
whoswhip f5a7aabf42 fix: handle username conflict during user creation 2026-06-13 20:15:41 -04:00
whoswhip 18c20cdf64 fix!: normalize and make usernames unique 2026-06-13 20:10:01 -04:00
whoswhip 69aef92b09 Create FUNDING.yml 2026-06-08 18:58:38 -04:00
whoswhip a2a030936c Merge pull request #18 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-e5a46ec0e1
chore(deps): bump ws from 8.19.0 to 8.20.1 in /SharpbinV3.Client in the npm_and_yarn group across 1 directory
2026-05-22 16:32:44 -04:00
dependabot[bot] 77b4c11a9f chore(deps): bump ws
Bumps the npm_and_yarn group with 1 update in the /SharpbinV3.Client directory: [ws](https://github.com/websockets/ws).


Updates `ws` from 8.19.0 to 8.20.1
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.19.0...8.20.1)

---
updated-dependencies:
- dependency-name: ws
  dependency-version: 8.20.1
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-21 19:36:35 +00:00
whoswhip c2383ff892 Merge pull request #17 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-ec84fab188
chore(deps-dev): bump @sveltejs/kit from 2.57.1 to 2.60.1 in /SharpbinV3.Client in the npm_and_yarn group across 1 directory
2026-05-21 15:35:17 -04:00
dependabot[bot] de58bc732c chore(deps-dev): bump @sveltejs/kit
Bumps the npm_and_yarn group with 1 update in the /SharpbinV3.Client directory: [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit).


Updates `@sveltejs/kit` from 2.57.1 to 2.60.1
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.60.1/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.60.1
  dependency-type: direct:development
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-21 18:08:51 +00:00
whoswhip c2ec839f0a Merge pull request #16 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-ef85f29010
chore(deps): bump the npm_and_yarn group across 1 directory with 2 updates
2026-05-14 20:45:51 -04:00
dependabot[bot] 090d9ed533 chore(deps): bump the npm_and_yarn group across 1 directory with 2 updates
Bumps the npm_and_yarn group with 2 updates in the /SharpbinV3.Client directory: [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) and [postcss](https://github.com/postcss/postcss).


Updates `svelte` from 5.53.5 to 5.55.7
- [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.55.7/packages/svelte)

Updates `postcss` from 8.5.6 to 8.5.14
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.5.6...8.5.14)

---
updated-dependencies:
- dependency-name: svelte
  dependency-version: 5.55.7
  dependency-type: direct:development
  dependency-group: npm_and_yarn
- dependency-name: postcss
  dependency-version: 8.5.14
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-15 00:43:26 +00:00
whoswhip aa5de648d7 Merge pull request #15 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-e4e91a86d1
chore(deps): bump devalue from 5.6.4 to 5.8.1 in /SharpbinV3.Client in the npm_and_yarn group across 1 directory
2026-05-14 20:42:15 -04:00
dependabot[bot] dac67df266 chore(deps): bump devalue
Bumps the npm_and_yarn group with 1 update in the /SharpbinV3.Client directory: [devalue](https://github.com/sveltejs/devalue).


Updates `devalue` from 5.6.4 to 5.8.1
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.6.4...v5.8.1)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.8.1
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-14 21:33:53 +00:00
whoswhip e8cd93e7bd fix: compact paste smaller; better edited display 2026-04-28 10:24:17 -04:00
whoswhip 41d441135c feat: add bot detection to skip recording views for known bots 2026-04-26 05:36:28 -04:00
whoswhip 52dd251e14 chore: increase global rate limiter to 120 requests within a minute 2026-04-25 06:06:49 -04:00
whoswhip 20473da0ba fix: allow null display name when saving display name
this lets you remove display names
2026-04-25 05:47:20 -04:00
whoswhip 99169305c7 fix: make cursor-not-allowed !important 2026-04-25 05:45:59 -04:00
whoswhip a55268afdc fix: enforce 2fa only on certain update actions
prevent newer admins from demoting older admins, and also prevent deletion of all admins
2026-04-25 05:02:31 -04:00
whoswhip e20a6200dd feat: add sub tab to the settings tab 2026-04-25 05:00:52 -04:00
whoswhip 70e637b281 feat: add /@username redirect to /user/username 2026-04-25 03:12:12 -04:00
whoswhip 6c65a52ee0 fix: sizeStored -> StoredSize in typescript paste type 2026-04-25 02:54:05 -04:00
whoswhip 40c6ac663f fix: only show report button if logged in
also switched to roles enum instead of directly using numbers in has role for paste comments
2026-04-25 02:23:22 -04:00
whoswhip c98e5e53b0 fix: add tooltip to comment timestamp for better context 2026-04-25 02:23:22 -04:00
whoswhip 23f0c92aed fix: disable styles on comment reactions 2026-04-25 02:23:22 -04:00
whoswhip e239bf2ae5 fix: always underline users in comments 2026-04-25 02:23:22 -04:00
whoswhip 95a5c18dc5 fix: disabled:cursor-not-allowed on like buttons 2026-04-25 02:23:15 -04:00
whoswhip 3da7f99feb fix: prevent authors from reacting to their pas6te 2026-04-24 22:01:56 -04:00
whoswhip 77f6623fcf fix: disable but show buttons for author or anon users 2026-04-24 21:33:17 -04:00
whoswhip 8d3caf5375 feat(comments): implement recursive comment deletion in HardDeleteComment method 2026-04-24 19:17:26 -04:00
whoswhip 95ca811d42 feat(comments): implement delete comment functionality with confirmation modal 2026-04-24 09:26:53 -04:00
whoswhip 63b77bece9 feat: comments & paste/comment reactions; renames/refactors
this is a LOT, i should've commited in stages but oh well, from what i can remember:
- paste interactions (reactions)
- comments
- comment interactions (reactions)
- rich text editor
- move all report apis into report controller
- rename size to sizeStored
- rename trueSize to originalSize
- fixed compression on paste compression
    - implemented compression threshold
- use longs instead of ints where possible in the entities
- improve record view + remove redundant check for existing view
2026-04-24 08:52:33 -04:00
whoswhip f82d314d80 feat(modal): refactor modal types and integrate security action requirements 2026-04-24 08:52:22 -04:00
whoswhip 38dd017dcd refactor: remove duplicate escape functions; improve escapeHtml function 2026-04-24 08:52:14 -04:00
whoswhip 9064aecedb refactor: migrate to props and runes
this was done using sv migrate and a bit of ai to fully migrate
2026-04-24 01:12:33 -04:00
whoswhip 2864c81f83 feat(auth): enhance token management and synchronization with user data 2026-04-23 19:50:00 -04:00
whoswhip df8b1456af Merge branch 'SharpbinV3' of github.com:whoswhip/Sharpbin into SharpbinV3 2026-04-21 14:37:28 -04:00
whoswhip b65d3f8726 fix: remove recipient information from warning log when email settings are incomplete 2026-04-21 14:37:26 -04:00
whoswhip ac08f5e32e Merge pull request #14 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/dompurify-3.4.0
chore(deps): bump dompurify from 3.3.2 to 3.4.0 in /SharpbinV3.Client
2026-04-20 22:23:00 -04:00
dependabot[bot] 6201369342 chore(deps): bump dompurify from 3.3.2 to 3.4.0 in /SharpbinV3.Client
Bumps [dompurify](https://github.com/cure53/DOMPurify) from 3.3.2 to 3.4.0.
- [Release notes](https://github.com/cure53/DOMPurify/releases)
- [Commits](https://github.com/cure53/DOMPurify/compare/3.3.2...3.4.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-21 02:22:20 +00:00
whoswhip fbf21b9d6e Merge pull request #13 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/flatted-3.4.2
chore(deps-dev): bump flatted from 3.3.3 to 3.4.2 in /SharpbinV3.Client
2026-04-20 22:21:07 -04:00
dependabot[bot] 245f07bf64 chore(deps-dev): bump flatted from 3.3.3 to 3.4.2 in /SharpbinV3.Client
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.2.
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

---
updated-dependencies:
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-21 02:20:39 +00:00
whoswhip 7c9c4026f0 Merge pull request #12 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/vite-7.3.2
chore(deps-dev): bump vite from 7.3.0 to 7.3.2 in /SharpbinV3.Client
2026-04-20 22:19:16 -04:00
dependabot[bot] 3f17a41285 chore(deps-dev): bump vite from 7.3.0 to 7.3.2 in /SharpbinV3.Client
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 7.3.0 to 7.3.2.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v7.3.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 7.3.2
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-21 02:18:55 +00:00
whoswhip f6dd45a87b Merge pull request #11 from whoswhip/dependabot/nuget/SharpbinV3.Server/MailKit-4.16.0
Bump MailKit from 4.15.1 to 4.16.0
2026-04-20 22:16:44 -04:00
dependabot[bot] 0b4939ab17 Bump MailKit from 4.15.1 to 4.16.0
---
updated-dependencies:
- dependency-name: MailKit
  dependency-version: 4.16.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-21 02:13:12 +00:00
whoswhip ad693b28ea fix: normalize canonical URL to prevent duplicate content issues 2026-04-20 22:04:20 -04:00
whoswhip b962ed9f67 style: format via prettier 2026-04-18 19:09:13 -04:00
whoswhip 60796a85fb fix: improve paste description 2026-04-18 19:08:57 -04:00
whoswhip edffd5490f feat: enhance SEO for home, recent, and paste pages 2026-04-18 18:41:23 -04:00
whoswhip ea634fd851 fix: update robots.txt to specify allowed and disallowed paths for web crawlers 2026-04-18 18:39:54 -04:00
whoswhip 2b272f2e93 Merge pull request #10 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/sveltejs/kit-2.57.1
chore(deps-dev): bump @sveltejs/kit from 2.50.0 to 2.57.1 in /SharpbinV3.Client
2026-04-12 14:22:26 -04:00
dependabot[bot] 9999b90305 chore(deps-dev): bump @sveltejs/kit in /SharpbinV3.Client
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.50.0 to 2.57.1.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.57.1/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.57.1
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-11 15:51:18 +00:00
whoswhip ee6a6d5e6d fix: include '.' before extension on paste download 2026-03-31 21:06:56 -04:00
whoswhip 13260ffc0f Merge pull request #9 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/devalue-5.6.4
chore(deps): bump devalue from 5.6.3 to 5.6.4 in /SharpbinV3.Client
2026-03-31 15:08:31 -04:00
dependabot[bot] ddb0bb80de chore(deps): bump devalue from 5.6.3 to 5.6.4 in /SharpbinV3.Client
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.6.3 to 5.6.4.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.6.3...v5.6.4)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-31 19:08:02 +00:00
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
whoswhip 4b01d801eb chore: update version to 3.0.2 in package-lock.json 2026-01-31 11:45:44 -05:00
whoswhip a76213b397 chore: bump version to 3.0.2 2026-01-31 11:45:25 -05:00
whoswhip e4cf98af09 feat: add conventional-changelog and conventional-changelog-angular dependencies 2026-01-31 11:44:48 -05:00
whoswhip 8b3f397837 style(frontend): format via prettier 2026-01-31 11:41:50 -05:00
whoswhip a6ffa982a4 fix: improve error handling and update user display name modal 2026-01-31 11:41:22 -05:00
whoswhip 005cb5de23 feat: add inputMaxLength property to Modal component for better input control 2026-01-31 11:41:15 -05:00
whoswhip 05cd024110 chore: disable admins_require_2fa in dev 2026-01-31 11:23:48 -05:00
whoswhip 270360a32f fix: add IValidateableObject interface to required DTO's ensuring model validation 2026-01-31 11:23:23 -05:00
whoswhip 79ca6ffa80 refactor: implement renderPaste to call per syntax rendering functions 2026-01-30 17:15:32 -05:00
whoswhip 15f0be5a2f fix: update version to 3.0.1 in package-lock.json 2026-01-30 17:14:41 -05:00
whoswhip c52ad8ba9b fix: enable AllowMissingPrunePackageData in project configuration 2026-01-30 17:14:29 -05:00
whoswhip 5375e1caa6 feat: enhance PasteService with caching and cache invalidation methods 2026-01-28 09:13:32 -05:00
whoswhip 81f85defb0 style: format via prettier 2026-01-28 08:53:56 -05:00
whoswhip 2cc2379e10 refactor: make unnecessary asynchronous methods synchronous 2026-01-28 08:53:32 -05:00
whoswhip adcaaadd7e refactor: change ValidSyntaxLanguages from string array to HashSet for improved performance 2026-01-28 08:47:49 -05:00
whoswhip 1af3c095c4 refactor: use inline cache with tag on stats 2026-01-28 08:47:06 -05:00
whoswhip ca210c5ea3 feat: add output caching and stats endpoint to track pastes and users
i plan to implement caching for all other endpoints but output cache doesn't have what i need right now
2026-01-28 07:53:58 -05:00
whoswhip 854e50fe78 feat: include createdAt in user responses 2026-01-28 05:17:03 -05:00
whoswhip 500f457f97 feat: user createdAt property 2026-01-28 05:16:37 -05:00
whoswhip 8aa1543296 feat: include paste createdAt in responses 2026-01-28 04:40:59 -05:00
whoswhip 9d0cc54db4 feat: createdAt paste property 2026-01-28 04:40:38 -05:00
whoswhip 3101f83e3f chore: index syntax, views, and size on pastes 2026-01-28 04:31:28 -05:00
whoswhip d2486b9f6e fix: adjust input margin for title field in paste creation 2026-01-28 00:45:05 -05:00
whoswhip 5b6498746b chore: change-log script 2026-01-27 03:53:24 -05:00
whoswhip 15b9109ee5 chore: generate changelog via conventional-changelog 2026-01-27 03:51:18 -05:00
whoswhip 44e6b3e423 chore: bump version 2026-01-27 03:49:58 -05:00
whoswhip a7481b5852 fix: adjust tooltip formatting for decrypted size display 2026-01-26 23:15:25 -05:00
whoswhip ca79582693 Merge branch 'SharpbinV3' of https://github.com/whoswhip/Sharpbin into SharpbinV3 2026-01-26 22:41:25 -05:00
whoswhip 16f5bff317 fix: update resize function call to use previewMode ensuring resize when switched to code 2026-01-26 22:17:23 -05:00
whoswhip b0a774afbb chore(deps-dev): bump svelte from 5.46.1 to 5.48.3 in /SharpbinV3.Client
Merge pull request #2 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/svelte-5.48.3
2026-01-26 19:46:52 -05:00
dependabot[bot] 78c94e9195 chore(deps-dev): bump svelte from 5.46.1 to 5.48.3 in /SharpbinV3.Client
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 5.46.1 to 5.48.3.
- [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.48.3/packages/svelte)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-27 00:45:25 +00:00
whoswhip 4d0352b4e4 refactor: size(decrypted) -> Decrypted Size 2026-01-26 19:42:02 -05:00
whoswhip c940fc5207 feat: enhance CSV rendering with header support and improved styling 2026-01-26 19:41:33 -05:00
whoswhip 7082fc4534 feat: include decrypted size in paste size tooltip 2026-01-26 19:21:20 -05:00
whoswhip bfad18bb05 feat: add CSV rendering functionality with PapaParse 2026-01-26 19:09:38 -05:00
whoswhip 147e43cd8a feat: add CSV to syntax lists 2026-01-26 19:09:32 -05:00
whoswhip 95316f5a84 feat: add papaparse and its type definitions 2026-01-26 19:08:59 -05:00
whoswhip 091c6d895e feat: style dropdown scrollbar 2026-01-26 03:42:36 -05:00
whoswhip 43f9a25915 feat: add tailwind-scrollbar npm package 2026-01-26 03:41:27 -05:00
whoswhip 6e59fbe627 style: format via prettier 2026-01-26 03:33:48 -05:00
whoswhip ec62e3be75 fix: enhance password validation and add show/hide functionality 2026-01-25 23:08:06 -05:00
whoswhip 3681f586dc fix: allow flexible display on cf turnstile 2026-01-25 23:07:56 -05:00
whoswhip a06021f0cd fix: update Open Graph description to use syntax name from consts 2026-01-25 23:07:28 -05:00
whoswhip 5ecb6a9714 chore: only show reports if length > 0 2026-01-25 22:31:35 -05:00
whoswhip 75010d3034 fix: render all turnstiles as flexible and interaction-only 2026-01-25 22:29:03 -05:00
whoswhip 71fb5b1616 fix: resolve lint issue svelte/no-at-html-tags
the html has already been sanitized by dompurify
2026-01-25 10:14:47 -05:00
whoswhip 6c8cdccbbf fix: update visibility icons in Paste component 2026-01-25 10:14:06 -05:00
whoswhip 4db986715c fix: enhance Paste component layout and user information display 2026-01-25 10:13:56 -05:00
whoswhip c9aa0d9a16 fix: include author data in recent paste data 2026-01-25 09:41:59 -05:00
whoswhip 51449abe6e fix: resize markdown preview as well 2026-01-25 08:38:32 -05:00
whoswhip 9c49c21e62 fix: update Turnstile configuration and improve layout for verification 2026-01-25 05:24:28 -05:00
whoswhip c1784f626a style(docs): format via prettier 2026-01-25 05:11:08 -05:00
whoswhip c95b2fe0c3 docs: reorganize project structure section in README 2026-01-25 05:10:49 -05:00
whoswhip 9d0bf7e5af docs: update description to include link for pastebin reference 2026-01-25 05:10:41 -05:00
whoswhip 3f4201b12c docs: add live instance link to README 2026-01-25 05:10:32 -05:00
whoswhip 33dce1ef17 style: format via prettier 2026-01-25 04:25:23 -05:00
whoswhip 2d01e726a9 fix: adjust dropdown max height dynamically and improve search input positioning 2026-01-25 04:24:54 -05:00
whoswhip a6b98a97f8 refactor: move expiration options into consts.ts 2026-01-25 04:24:39 -05:00
whoswhip 01efa399cf fix: adjust height properties for paste creation info 2026-01-24 23:11:50 -05:00
whoswhip 590f0c3da9 fix: disable pointer events on menu icons 2026-01-24 06:26:37 -05:00
whoswhip 1937307ae7 feat: close hamburger menu when clicked outside 2026-01-24 06:26:29 -05:00
158 changed files with 16807 additions and 2769 deletions
+2
View File
@@ -0,0 +1,2 @@
# These are supported funding model platforms
ko_fi: whoswhip
+3 -1
View File
@@ -323,4 +323,6 @@ FodyWeavers.xsd
Data
!SharpbinV3.Server/Data
.idea
.idea
**/.env
+309
View File
@@ -0,0 +1,309 @@
## [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)
### Bug Fixes
* adjust dropdown max height dynamically and improve search input positioning ([2d01e72](https://github.com/whoswhip/Sharpbin/commit/2d01e726a97b99a35017df9f477fa1304213bc9e))
* adjust height properties for paste creation info ([01efa39](https://github.com/whoswhip/Sharpbin/commit/01efa399cf7d7aa1d38af1bc29017a8873f97dca))
* adjust tooltip formatting for decrypted size display ([a7481b5](https://github.com/whoswhip/Sharpbin/commit/a7481b5852532d42697e723f8f49cfa126ce8212))
* allow flexible display on cf turnstile ([3681f58](https://github.com/whoswhip/Sharpbin/commit/3681f586dc0a01fcfd197db3961386d4ac7fe371))
* disable pointer events on menu icons ([590f0c3](https://github.com/whoswhip/Sharpbin/commit/590f0c3da9c4bd6f9db43a5866dddfb9a2859326))
* enhance password validation and add show/hide functionality ([ec62e3b](https://github.com/whoswhip/Sharpbin/commit/ec62e3be7556f083ef8380dd4eece4f5e5b4f148))
* enhance Paste component layout and user information display ([4db9867](https://github.com/whoswhip/Sharpbin/commit/4db986715cfd36d300677b7e527ff8e2de827791))
* include author data in recent paste data ([c9aa0d9](https://github.com/whoswhip/Sharpbin/commit/c9aa0d9a16f9135be7be4b100c6c0966f3285e6a))
* render all turnstiles as flexible and interaction-only ([75010d3](https://github.com/whoswhip/Sharpbin/commit/75010d303424a45d9435571b45e4d0d29ade23a9))
* resize markdown preview as well ([51449ab](https://github.com/whoswhip/Sharpbin/commit/51449abe6e894d289374ec7ffcef21ff3d1e71c9))
* resolve lint issue svelte/no-at-html-tags ([71fb5b1](https://github.com/whoswhip/Sharpbin/commit/71fb5b16160aa986ca577c25373dcc382ff96ba3))
* update Open Graph description to use syntax name from consts ([a06021f](https://github.com/whoswhip/Sharpbin/commit/a06021f0cd67162446d9393a854ddc4f7f3a74b0))
* update resize function call to use `previewMode` ensuring resize when switched to code ([16f5bff](https://github.com/whoswhip/Sharpbin/commit/16f5bff317a6620e3a7e5a0fd99ac6b56599dd8e))
* update Turnstile configuration and improve layout for verification ([9c49c21](https://github.com/whoswhip/Sharpbin/commit/9c49c21e62118d277670677e51a685150194a2b6))
* update visibility icons in Paste component ([6c8cdcc](https://github.com/whoswhip/Sharpbin/commit/6c8cdccbbfd3becdd5fae4674909c788f00edab7))
### Features
* add CSV rendering functionality with PapaParse ([bfad18b](https://github.com/whoswhip/Sharpbin/commit/bfad18bb0551ddc2eb03f934ecedd2b7b89ddbf2))
* add CSV to syntax lists ([147e43c](https://github.com/whoswhip/Sharpbin/commit/147e43cd8ab32da538e6ff76a68cdb7441e469e2))
* add papaparse and its type definitions ([95316f5](https://github.com/whoswhip/Sharpbin/commit/95316f5a846c03a5e2b014717c26bea9005f933d))
* add tailwind-scrollbar npm package ([43f9a25](https://github.com/whoswhip/Sharpbin/commit/43f9a25915ac32076636ab86781aa7efb5240b41))
* close hamburger menu when clicked outside ([1937307](https://github.com/whoswhip/Sharpbin/commit/1937307ae728f0d77c9ee572adf1ba688648e0aa))
* enhance CSV rendering with header support and improved styling ([c940fc5](https://github.com/whoswhip/Sharpbin/commit/c940fc5207a80563a620b37c9aeebce395c659e9))
* include decrypted size in paste size tooltip ([7082fc4](https://github.com/whoswhip/Sharpbin/commit/7082fc45346824f14d6f8fe85743f73eca6a35c1))
* style dropdown scrollbar ([091c6d8](https://github.com/whoswhip/Sharpbin/commit/091c6d895e638fc13b68207e3ae765664dfc80b6))
# [3.0.0](https://github.com/whoswhip/Sharpbin/compare/050f0bc935937b8b80500a59bc6ac5513fd7af93...v3.0.0) (2026-01-24)
### Bug Fixes
* add ASPNETCORE_URLS environment variable for backend service in docker-compose.yml ([c4f606e](https://github.com/whoswhip/Sharpbin/commit/c4f606ecf265678495b616a11c0fab1aa4ca9331))
* add cursor pointer to the submit button for better UX ([f5de211](https://github.com/whoswhip/Sharpbin/commit/f5de211611c8142c0825286c0f514b1edc161d51))
* add validation for display name length in user creation and update requests ([9bb620a](https://github.com/whoswhip/Sharpbin/commit/9bb620a4a31473385af6ffd32d2b7d7c5affd415))
* adjust password hint display logic in registration form ([361cf76](https://github.com/whoswhip/Sharpbin/commit/361cf76f46598c1d797c745e44f2de5d960682bc))
* center-align text in login and registration links in navbar ([4dafde7](https://github.com/whoswhip/Sharpbin/commit/4dafde739aaf04d4a7b0e08ee15415518bcf2e7b))
* change to non-reactive statements ([55bee20](https://github.com/whoswhip/Sharpbin/commit/55bee20e5de3d4c155f2eaa0f7999110a86aa535))
* correct conditional logic for user role checks in component rendering ([7298982](https://github.com/whoswhip/Sharpbin/commit/729898296b4e09fa8cada5feb524f1d3774a2d7c))
* correct environment variable key for Turnstile Site Key in docker-compose ([2773813](https://github.com/whoswhip/Sharpbin/commit/2773813c263d59a20ceabd02ebabd763a3832ebc))
* correct property name for TOTP enabled flag in parseTotpEnabled function ([9e56c4e](https://github.com/whoswhip/Sharpbin/commit/9e56c4eee1d97227b821d643640d2d1db593aba7))
* correct syntax selection logic for file drag and drop handling ([62b5dce](https://github.com/whoswhip/Sharpbin/commit/62b5dcef00e6230ec8674d3de65617216e760e51))
* display 2FA status only for the account owner ([4de6a6a](https://github.com/whoswhip/Sharpbin/commit/4de6a6a1186e97a7063d5e55008f9acc5043b912))
* dont disabled login button when registrations are disabled ([bbfa9ff](https://github.com/whoswhip/Sharpbin/commit/bbfa9ffc560a87bcc8441fddc6d78496819a9144))
* enhance paste size validation logic ([f467a2a](https://github.com/whoswhip/Sharpbin/commit/f467a2a89966e6025d7ac0a60eb89c99956e4d28))
* enhance textarea styling and display content metrics ([fabef95](https://github.com/whoswhip/Sharpbin/commit/fabef95159e469abcf6316362f18de25aab0a0c6))
* enhance tooltip functionality and update last login display ([d3c2efd](https://github.com/whoswhip/Sharpbin/commit/d3c2efd2108026b5e49f1a199c6f2afdeb0a06a0))
* ensure JSDOM is only loaded in server-side environments ([7789ab6](https://github.com/whoswhip/Sharpbin/commit/7789ab6cb2822ca338186573c010047a3c5b0f48))
* improve error handling and display for login failures ([ce66fe1](https://github.com/whoswhip/Sharpbin/commit/ce66fe13e8718b8abbf67adca9fa1775c932401f))
* improve error handling and response messages in EditPaste method ([284c5e9](https://github.com/whoswhip/Sharpbin/commit/284c5e927e1ef796026ca1b1a078adadc1986721))
* improve error handling for registration response ([d514e45](https://github.com/whoswhip/Sharpbin/commit/d514e456bf364b1dbdbd7e67938ca609c2362468))
* improve error handling in paste fetching and add error page ([5e4afaf](https://github.com/whoswhip/Sharpbin/commit/5e4afafac0e57a24316761c555892fee5dc8394a))
* improve error logging for view count increment failure ([8b84a2d](https://github.com/whoswhip/Sharpbin/commit/8b84a2d8a3dbcfa0909a9ba7ac79531244c268f2))
* improve formatBytes function and display byte size in textarea ([2a9a4b9](https://github.com/whoswhip/Sharpbin/commit/2a9a4b9eefaef513df5437a9d548e1941583fc1e))
* include url queries in resolve ([7857c32](https://github.com/whoswhip/Sharpbin/commit/7857c327eac1a2371552bedc1571650bffb29c0d))
* increase max height ([7650fd7](https://github.com/whoswhip/Sharpbin/commit/7650fd786dbcffb9cba6aba9c073d9ec5e19c737))
* inline is expired calculation ([2b60ee8](https://github.com/whoswhip/Sharpbin/commit/2b60ee86369731ebc98deaf007c725a544382b2a))
* lint issues resolved ([21b6f95](https://github.com/whoswhip/Sharpbin/commit/21b6f95edc1ff34a3ee66f32083b4f99d9bbf2ac))
* load turnstile script in layout and explicitly render ([2c24af5](https://github.com/whoswhip/Sharpbin/commit/2c24af5ac98dd4959e353571d3186fb98b459bf4))
* null user/paste fk in reports on delete ([f8a1490](https://github.com/whoswhip/Sharpbin/commit/f8a149058295ebc56fc43cecf03b76792fc62529))
* prevent moderators from modifiying higher roles(admin) ([3711885](https://github.com/whoswhip/Sharpbin/commit/3711885a38e18ddf6e478e17c671c4c7774c0d3e))
* properly set limiter ([6f99036](https://github.com/whoswhip/Sharpbin/commit/6f990364a59b0a9801a6dbd715c70c2f29e63e9c))
* refresh token ([19f439a](https://github.com/whoswhip/Sharpbin/commit/19f439a4052d16a3bddba36dc15822906ca92e11))
* remove dependency condition for backend service health check in docker-compose.yml ([095df2f](https://github.com/whoswhip/Sharpbin/commit/095df2f3f3aff1eccf4f023ca1a77bc11d66bbea))
* remove quotes from DATA_PROTECTION_KEY_PATH in docker-compose ([f96396b](https://github.com/whoswhip/Sharpbin/commit/f96396b586f5f0b5da66227c08767be348f5cbab))
* remove quotes from default connection string in docker-compose ([d5565f9](https://github.com/whoswhip/Sharpbin/commit/d5565f9a68bf38035d994002812c3411427f563e))
* remove unused nuget package ([4bd6a18](https://github.com/whoswhip/Sharpbin/commit/4bd6a18e31970f4568f0d405454c30b56e06c895))
* reset Turnstile on login and registration error handling ([5a630d2](https://github.com/whoswhip/Sharpbin/commit/5a630d2a715acc851add8f82b19dba111d98c2bd))
* reset turnstile on login error handling ([1da88db](https://github.com/whoswhip/Sharpbin/commit/1da88dba4ed500baf6dc57b6eeb02b115c0fd000))
* resolve lint issues ([1f4fda1](https://github.com/whoswhip/Sharpbin/commit/1f4fda1a16f92cebae716642482d959ad300c5a7))
* ssr request to user; navbar positioning ([bffc4e2](https://github.com/whoswhip/Sharpbin/commit/bffc4e2bf41fe1a3dd93f3042be0e796b6f986d2))
* **style:** update Navbar styling for improved layout and consistency ([6c3caaf](https://github.com/whoswhip/Sharpbin/commit/6c3caaf2ecaa6dc9e616d7f5a7f65ee1a15c091c))
* **styling:** add table styling for markdown elements ([825d384](https://github.com/whoswhip/Sharpbin/commit/825d384db4c906f373ea92ae3e4b46efd741e862))
* **styling:** adjust margin and padding for first child in markdown elements ([8f5499a](https://github.com/whoswhip/Sharpbin/commit/8f5499ae05f69c131447fef6188680d448ed895e))
* **styling:** enforce max width on recent pastes titles ([8accfa2](https://github.com/whoswhip/Sharpbin/commit/8accfa2dc525f528337e2cbd79ab6a6a2c2b748f))
* token refreshing using wrong object path ([e45785e](https://github.com/whoswhip/Sharpbin/commit/e45785e1b8bb64a0834cf420db4866307146132d))
* update API fetch calls to use dynamic apiUrl ([6072f7f](https://github.com/whoswhip/Sharpbin/commit/6072f7f674bc3def903815de35536ed933cff7fd))
* update API routes for fetching raw paste content and deleting pastes ([48543c7](https://github.com/whoswhip/Sharpbin/commit/48543c7ff03b1ff4b3efa96de56097fb9ada2f02))
* update database connection string configuration in Program.cs and docker-compose.yml ([011b523](https://github.com/whoswhip/Sharpbin/commit/011b523fd321e0834c73790b2553adee37a022f6))
* update docker-compose to reflect correct backend directory structure ([113ad49](https://github.com/whoswhip/Sharpbin/commit/113ad499d9806a7a237f6afdb9a6bf02ebc238aa))
* update environment variables in docker-compose for backend and frontend services ([5e8d7be](https://github.com/whoswhip/Sharpbin/commit/5e8d7be86423247e63a350d440bc52cf3428d312))
* update Navbar and layout server to improve structure and data handling ([a912d04](https://github.com/whoswhip/Sharpbin/commit/a912d0463b1e8517f055f596c2cb033b88db6b9b))
* update paste view count display in metadata ([f9b63ed](https://github.com/whoswhip/Sharpbin/commit/f9b63edf776e2715b09de2d408aab4ba85ccd50f))
* update profile link to direct to user page instead of dashboard ([ff52498](https://github.com/whoswhip/Sharpbin/commit/ff52498cf99a74936d47d73369c7fdd7b771f0df))
* update SQLite connection string retrieval in Program.cs ([6178888](https://github.com/whoswhip/Sharpbin/commit/6178888246871f38ab8373bacbb2a61fba6d4046))
* update TOTP API request payload to use 'code' instead of 'totpcode' ([6bcc62a](https://github.com/whoswhip/Sharpbin/commit/6bcc62a7e7b77c1129c16d9a8c979e003b6481e5))
* update version number to 3.0.0 and remove beta check from footer ([8252d58](https://github.com/whoswhip/Sharpbin/commit/8252d58f47d503a0c40f95bde9ee277341e801b9))
* use $app/state ([b44f0bc](https://github.com/whoswhip/Sharpbin/commit/b44f0bce0ab5f7fcedf9c206362a31947215eef9))
* use margin-bottom instead of margin-top for elements ([bd7d115](https://github.com/whoswhip/Sharpbin/commit/bd7d1154eaf57e310a82cb43c09baf15c499a489))
### Features
* /raw/{id} endpoint ([ca87b1a](https://github.com/whoswhip/Sharpbin/commit/ca87b1a5f220a6f3b8857cf00602abf867c9a7d9))
* account deletion; auto incremental uids; display name renaming UI + account deletion UI; enhanced username validation ([fe54ff1](https://github.com/whoswhip/Sharpbin/commit/fe54ff15ce7122373643eece9981eb05a1d7c7d0))
* add application version definition to Vite config ([eca6867](https://github.com/whoswhip/Sharpbin/commit/eca6867fcab5c1ba4d1d327c76f18fd21290abd6))
* add delete functionality for pastes with authorization check ([3015f97](https://github.com/whoswhip/Sharpbin/commit/3015f97ff977fbfd9b23a11aad016ac7408be752))
* add Dockerfile and docker-compose for backend and frontend services ([31142e0](https://github.com/whoswhip/Sharpbin/commit/31142e0cf96d2ff868fadf1ecac192a07ebc5c2d))
* add editedAt field to Paste interface and enhance paste editing functionality ([86b74a1](https://github.com/whoswhip/Sharpbin/commit/86b74a140a546651d301079b71531468d0b1d52d))
* add Footer component to layout for improved user navigation ([e093550](https://github.com/whoswhip/Sharpbin/commit/e0935505ea01c286cb802337461b1ebbb4eb6f2d))
* add health check endpoint returning status ok ([dfdce51](https://github.com/whoswhip/Sharpbin/commit/dfdce51c6e648b601880a16644d7790b41550129))
* add health checks for backend and frontend services in docker-compose.yml ([08c4be4](https://github.com/whoswhip/Sharpbin/commit/08c4be4f7eb8e985114d1f87a8bd69a7bad0a9ee))
* add health checks for backend and frontend services in docker-compose.yml ([57dad56](https://github.com/whoswhip/Sharpbin/commit/57dad564a6df35ea488fab40fa9798511036d4ac))
* add health checks for database connectivity ([cab1b17](https://github.com/whoswhip/Sharpbin/commit/cab1b170c1218c47c5c4f366425731c3fdb5d67a))
* add isBinaryData utility function and integrate it into paste handling; add drag and drop functionality when creating a paste ([bf0eac9](https://github.com/whoswhip/Sharpbin/commit/bf0eac9ed8aa00cf4d82236cf8257f87bc6b8588))
* add markdown parsing and rendering support ([406381f](https://github.com/whoswhip/Sharpbin/commit/406381fbfe724249b41477f64ef42116882a671d))
* add Pagination interface and integrate it into User type ([a9e1e82](https://github.com/whoswhip/Sharpbin/commit/a9e1e823591c01be4dc960bf5427131480dfa413))
* add pagination to user retrieval endpoints; enhance BuildUserResponse to include pagination details ([93df14e](https://github.com/whoswhip/Sharpbin/commit/93df14e59ce876c877d34d28a9f0a0cf3d53eb28))
* add PasteCleanUpService as a hosted service ([f578b58](https://github.com/whoswhip/Sharpbin/commit/f578b58780930d253837d4e1c795f46c6b27b9df))
* add PasteSettings environment variables for internal API key and HMAC secret ([a6fa65c](https://github.com/whoswhip/Sharpbin/commit/a6fa65c3bd67fbb1133737d738626c345304f503))
* add recent pastes page with data fetching and display logic ([8a6ab29](https://github.com/whoswhip/Sharpbin/commit/8a6ab29f52ddd6e05c211569323d0d4d48b4938b))
* add registration status check and disable form elements when registration is disabled ([b1d2d3f](https://github.com/whoswhip/Sharpbin/commit/b1d2d3f5bba5e7f0bab38448fc25baa8a4551317))
* add variant support for dropdown component styling ([1950dc4](https://github.com/whoswhip/Sharpbin/commit/1950dc47ae8c5ca721851999afb2ce32b7c5c4cb))
* admins can change user's roles ([99feb27](https://github.com/whoswhip/Sharpbin/commit/99feb2795a17b43724985cbf1722088fde0ac281))
* auth, compression, jwt, paste wip, roles, ratelimiting ([6ec1a7f](https://github.com/whoswhip/Sharpbin/commit/6ec1a7fa7b3254e6ab09aaed8943534b79dac9cd))
* auto detect syntax from file extension on drag and drop; syntax from extension function ([9e05600](https://github.com/whoswhip/Sharpbin/commit/9e056009e3858d9a56bd71638cd32db3ce122a60))
* bypass user confirmation when loading external assets in markdown for trusted domains ([35d891b](https://github.com/whoswhip/Sharpbin/commit/35d891bed7bd7fb2415a14e74f45eb5b7d4e3453))
* create Paste component for displaying paste details ([753d28f](https://github.com/whoswhip/Sharpbin/commit/753d28f720c9f7f6a3b7d787ca19a8149d592ee7))
* declare application version constant in app.d.ts ([72206e9](https://github.com/whoswhip/Sharpbin/commit/72206e9ba214b602cafd2836d880ac06debb69de))
* enable registration toggle and update Navbar to reflect registration status ([159fcc2](https://github.com/whoswhip/Sharpbin/commit/159fcc2a890480cfad0cc19dd153c84aa1af88d0))
* enhance AuthService to support admin role assignment for the first user ([c934c85](https://github.com/whoswhip/Sharpbin/commit/c934c85b130d2c0086146110f3211f612387b8d3))
* enhance code highlighting for plaintext in syntax highlighter ([5cb30a9](https://github.com/whoswhip/Sharpbin/commit/5cb30a90a760874d54cc18e0adc63cfe6812d1c7))
* enhance decryption process with status updates and improved user feedback ([7b3af77](https://github.com/whoswhip/Sharpbin/commit/7b3af774494c31f8fcd829d20f9bb5f46242320a))
* enhance paste creation with dynamic textarea resizing and improved password handling; generate random password button in paste creation; show password in paste creation; ([5410a89](https://github.com/whoswhip/Sharpbin/commit/5410a8973a81dc6a854f1c685e3a3546de985486))
* enhance tooltip functionality and improve date formatting ([8ab66f5](https://github.com/whoswhip/Sharpbin/commit/8ab66f5f159c1c34d29c456fef9a4c626548c6aa))
* enhance tooltip functionality; prevent empty tooltips for paste titles ([7eb0204](https://github.com/whoswhip/Sharpbin/commit/7eb0204e6751df148b6520c6ccd665289e31341b))
* enhance user experience with tooltips; implement return URL handling on login and registration; add user roles; improve paste visibility checks ([5fca207](https://github.com/whoswhip/Sharpbin/commit/5fca207ad61acf0dca4c9fd13ab5a598d89ba890))
* implement decryptAes function; moved to encryption.ts ([f61f31d](https://github.com/whoswhip/Sharpbin/commit/f61f31de0e9a3c97a347d38783cddb4c0d7f83fe))
* implement mobile support for navbar ([63f55d2](https://github.com/whoswhip/Sharpbin/commit/63f55d2bdac475bd7d981d87475fa4e8cddb6b72))
* implement modal component for password input and confirmation actions ([b6e020f](https://github.com/whoswhip/Sharpbin/commit/b6e020fa6987b5ecad5ca78d24ce87e41799c177))
* implement pagination for user pastes; enhance fetchPage function and update display logic ([49b9673](https://github.com/whoswhip/Sharpbin/commit/49b9673d48d50a5ca2adea9b4c2055ae2c88f001))
* implement paste decryption ([3a54951](https://github.com/whoswhip/Sharpbin/commit/3a549511f93d7001d246c318545e6edb307e2f99))
* implement rate limiting policy for site info endpoints in Auth and Paste controllers ([3895bd9](https://github.com/whoswhip/Sharpbin/commit/3895bd968136071cc09bba686107f693f7e47dc3))
* implement registration page with Turnstile verification and loading state ([24b25c2](https://github.com/whoswhip/Sharpbin/commit/24b25c2291eea16fab16c250b5856b91f7385b74))
* implement server-side user data fetching; enhance user controller for detailed responses; update token handling to use cookies ([4151c62](https://github.com/whoswhip/Sharpbin/commit/4151c62b8cd10cdbf6a757f6e82935e8d5426a5a))
* implement Turnstile verification for enhanced security during login and registration ([848b859](https://github.com/whoswhip/Sharpbin/commit/848b8598e5fb407f284027875c1f09c396b4aa6f))
* implement user update functionality by UUID and add validation to UpdateUserRequest ([f40d4ab](https://github.com/whoswhip/Sharpbin/commit/f40d4ab68c3aabf95b8775601b1534bda9665b4b))
* improve file download naming by using syntax extension conditionally ([fed0663](https://github.com/whoswhip/Sharpbin/commit/fed06630b7383eb185b2afbdfd30d2776416bcc5))
* improve paste creation validation; add content size check and remove unnecessary logging ([dd6ce5c](https://github.com/whoswhip/Sharpbin/commit/dd6ce5c39506e9e22aeefa4db34ac8caa48a5cdd))
* improve recent page; improve SEO for pages ([3a5738b](https://github.com/whoswhip/Sharpbin/commit/3a5738b53173ddae500098ffcbf1769dada11584))
* initial commit ([050f0bc](https://github.com/whoswhip/Sharpbin/commit/050f0bc935937b8b80500a59bc6ac5513fd7af93))
* integrate hash-wasm for enhanced AES encryption and decryption ([7e1fb3a](https://github.com/whoswhip/Sharpbin/commit/7e1fb3add4f438a206638ea0c90b0a27fd108c53))
* login & registration; enhanced paste view; custom dropdown + search; navbar; global user access via store; auto token refresh; paste creation as user; /api/user/me, returns info on yourself including pastes; ([db1d870](https://github.com/whoswhip/Sharpbin/commit/db1d8704a1d0f183812fbd41ad077274c6626801))
* paste cleanup service; sveltekit frontend; paste editing; paste metadata modifying ([adad139](https://github.com/whoswhip/Sharpbin/commit/adad139081fb4d9b2ed644e8fe4cdd89ac2ef38d))
* paste compression & verification enforcement settings; enforce 2fa on admins setting; increase paste validation; anonymous uploads ([9f55aa1](https://github.com/whoswhip/Sharpbin/commit/9f55aa1b2273ee0298892dba380c71630c743289))
* paste creation, utilities, revert to gzip, grammar fixes etc ([93daa2e](https://github.com/whoswhip/Sharpbin/commit/93daa2e1a2b75cc2e93cbc7149b837e79eb9ece4))
* paste creation; paste viewing; more langs supported; jwt settings class; paste settings class; data validation on paste metadata modification ([b9b14a3](https://github.com/whoswhip/Sharpbin/commit/b9b14a3d5a553fd1e7e7294c8ba29cd8cb8218dd))
* paste views; configuration validation; hmacsha256 method; enhance paste clean up serivce; paste view clean up service; ([3048af3](https://github.com/whoswhip/Sharpbin/commit/3048af3a6dece0338e278bf6d6b2358c0f4952fc))
* preview markdown in paste creation; prevent external option in parseMarkdown ([3f27a3a](https://github.com/whoswhip/Sharpbin/commit/3f27a3a3e726e941ad6e996db53f9366506a7012))
* refactor drag and drop file handling to update syntax selection conditionally ([ca9fa81](https://github.com/whoswhip/Sharpbin/commit/ca9fa81771af49b20628c148a1ac61ad6a168bf9))
* refactor refresh token handling; update schema and logic for improved security and functionality ([ae91108](https://github.com/whoswhip/Sharpbin/commit/ae91108484ff73a6cdee16e0454acc330a221a33))
* reporting apis; better rate limiting ([14bbd9c](https://github.com/whoswhip/Sharpbin/commit/14bbd9c762f641ac738714822d19845d86bb6582))
* reports; improved+simplifed modals; extractError funcction; ([67447d5](https://github.com/whoswhip/Sharpbin/commit/67447d51aec59af200524e7f33bcee5678adc2bc))
* seo optimizations + opengraph embeds ([3bbd646](https://github.com/whoswhip/Sharpbin/commit/3bbd64631a46d510e720db3a3d5cf7ad4298702d))
* totp 2fa; httpcontext extension for jwtuser; asp.net data protection; prevent banned users from certain actions; account deletion requires 2fa if enabled; making users admins requires 2fa if enabled; httpcontext extension to get ip; enhance user store ([20ceb91](https://github.com/whoswhip/Sharpbin/commit/20ceb91db8405172d5beb9df646d3d912cea40a5))
* update API routes for paste options and recent pastes ([1f2761f](https://github.com/whoswhip/Sharpbin/commit/1f2761f463e160a0d4d865a4d6a5763fc408712b))
* update button styles for active state in paste creation ([6981836](https://github.com/whoswhip/Sharpbin/commit/698183690c1b48b6e6ebf83f62025242d746c607))
* update favicon and improve tooltip for paste size display ([1ed2178](https://github.com/whoswhip/Sharpbin/commit/1ed21789e656dfdc7a65119f4c5ec010a1669593))
* update minimum height for main sections across multiple pages for consistent layout ([c565c57](https://github.com/whoswhip/Sharpbin/commit/c565c57e20cb0eb7d6e57e17182382e2ee931190))
* view raw button; paste header follows when scrolling; scroll to top button appears after scrolling far enough ([28a0ccb](https://github.com/whoswhip/Sharpbin/commit/28a0ccbfab4461fd6fe75d25b3f7cffce063041f))
### Reverts
* Revert "chore: format via csharpier" ([6bea6c4](https://github.com/whoswhip/Sharpbin/commit/6bea6c49bef1eea4dfd72d962b4e06e20b64594f))
+27 -13
View File
@@ -1,6 +1,8 @@
# SharpbinV3
Sharpbin is a pastebin-style website built with ASP.NET Core and SvelteKit.
Sharpbin is a [pastebin](https://en.wikipedia.org/wiki/Pastebin)-style website built with ASP.NET Core and SvelteKit.
A live instance is available at [sharpbin.cc](https://sharpbin.cc).
## Features
@@ -13,20 +15,17 @@ Sharpbin is a pastebin-style website built with ASP.NET Core and SvelteKit.
- Server-side paste compression to save storage.
- Captcha support via Cloudflare Turnstile.
## Project Structure
- **[SharpbinV3.Server](SharpbinV3.Server/README.md)**: Backend API built with C# and ASP.NET Core. Refer to its README for server-side development and configuration.
- **[SharpbinV3.Client](SharpbinV3.Client/README.md)**: Frontend application built with SvelteKit and TypeScript. Refer to its README for client-side development and setup.
## Getting Started
The easiest way to run SharpbinV3 is using Docker Compose.
1. Ensure Docker and Docker Compose are installed.
2. Clone the repository.
```bash
git clone https://github.com/whoswhip/Sharpbin.git
```
3. Run the following command in the root directory:
```bash
@@ -35,29 +34,44 @@ docker-compose up -d
### Configuration
You can configure the application using environment variables. When using Docker Compose, these can be set in the `docker-compose.yml` file.
You can configure Sharpbin using environment variables or `appsettings.json`. When using Docker Compose, these can be set in the `docker-compose.yml` file.
> When configuring via `appsettings.json` instead of for example `ConnectionStrings__DefaultConnection` it would be:
```json
"ConnectionStrings": {
"DefaultConnection": "Data Source=sharpbin.db"
},
```
#### Backend (SharpbinV3.Server)
- `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`).
- `JwtSettings__Secret`: A secure string used for signing JWT tokens.
- `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key.
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
- `AuthSettings__Registration_Enabled`: Set to `true` by default, enables/disables registration.
- `AuthSettings__Registration_Enabled`:**true**: Enables/disables registration.
- `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use.
- `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions.
- `AuthSettings__API_Key_HMAC_Secret`: Recommended to securely hash API keys, but is not required.
- `PasteSettings__MaxTitleLength`: Max title length in characters.
- `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB)
- `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default.
- `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default.
- `PasteSettings__MaxPasteSizeInBytes`:**1_048_576** (1MB): Max Paste Size set in bytes.
- `PasteSettings__EnablePasteCompression`:**true**: Enables/Disables server-side paste compression.
- `PasteSettings__RequiresVerification`:**true**: Enables/Disables CAPTCHA verification when creating pastes.
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers
- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
- `ASPNETCORE_ENVIRONMENT`: Set to `Production` or `Development`.
#### Frontend (SharpbinV3.Client)
- `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.
The frontend will be accessible at http://localhost:5173.
## Project Structure
- **[SharpbinV3.Server](SharpbinV3.Server/README.md)**: Backend API built with C# and ASP.NET Core. Refer to its README for server-side development and configuration.
- **[SharpbinV3.Client](SharpbinV3.Client/README.md)**: Frontend application built with SvelteKit and TypeScript. Refer to its README for client-side development and setup.
+1
View File
@@ -7,6 +7,7 @@ node_modules
.wrangler
/.svelte-kit
/build
.cache
# OS
.DS_Store
+2
View File
@@ -1,5 +1,7 @@
# syntax=docker/dockerfile:1
FROM node:20-alpine as build
ARG GIT_COMMIT_HASH
ENV GIT_COMMIT_HASH=${GIT_COMMIT_HASH}
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
+3 -11
View File
@@ -19,7 +19,7 @@ npm install
### Environment Configuration
The application requires an environment variable to point to the backend API. Create a `.env` file in this directory or set the variable in your environment:
The frontend requires an environment variable to point to the backend API. Create a `.env` file in this directory or set the variable in your environment:
- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`).
- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`)
@@ -33,21 +33,13 @@ Start the development server with Hot Module Replacement (HMR):
npm run dev
```
The application will be available at http://localhost:5173.
The frontend will be available at http://localhost:5173.
## Script Reference
- `npm run dev`: Start the Vite development server.
- `npm run build`: Create a production build of the application.
- `npm run build`: Create a production build of the frontend.
- `npm run preview`: Locally preview the production build.
- `npm run check`: Run type checking with svelte-check.
- `npm run lint`: Run ESLint and Prettier checks.
- `npm run format`: Format the codebase with Prettier.
## Tech Stack
- Svelte 5 with SvelteKit.
- Tailwind CSS for styling.
- Lucide Svelte for icons.
- Highlight.js for syntax highlighting.
- TypeScript for type safety.
+2161 -263
View File
File diff suppressed because it is too large Load Diff
+21 -7
View File
@@ -1,7 +1,7 @@
{
"name": "sharpbinv3.client",
"private": true,
"version": "3.0.0",
"version": "3.0.5",
"type": "module",
"scripts": {
"dev": "vite dev",
@@ -11,18 +11,23 @@
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint ."
"lint": "prettier --check . && eslint .",
"change-log": "conventional-changelog -p angular -i ../CHANGELOG.md -s -r 0"
},
"devDependencies": {
"@eslint/compat": "^1.4.0",
"@eslint/js": "^9.39.1",
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/kit": "^2.50.0",
"@sveltejs/kit": "^2.60.1",
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17",
"@types/better-sqlite3": "^7.6.13",
"@types/jsdom": "^27.0.0",
"@types/node": "^22",
"@types/papaparse": "^5.5.2",
"@types/qrcode": "^1.5.6",
"conventional-changelog": "^7.1.1",
"conventional-changelog-angular": "^8.1.0",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.13.1",
@@ -30,21 +35,30 @@
"prettier": "^3.7.4",
"prettier-plugin-svelte": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.7.2",
"svelte": "^5.45.6",
"svelte": "^5.55.7",
"svelte-check": "^4.3.4",
"tailwind-scrollbar": "^4.0.2",
"tailwindcss": "^4.1.17",
"typescript": "^5.9.3",
"typescript-eslint": "^8.48.1",
"vite": "^7.2.6"
"vite": "^7.3.2"
},
"dependencies": {
"@fontsource/inter": "^5.2.8",
"@fontsource/jetbrains-mono": "^5.2.8",
"@lucide/svelte": "^0.562.0",
"@resvg/resvg-js": "^2.6.2",
"@sveltejs/adapter-node": "^5.4.0",
"dompurify": "^3.3.1",
"better-sqlite3": "^12.8.0",
"dompurify": "^3.4.0",
"hash-wasm": "^4.12.0",
"highlight.js": "^11.8.0",
"jsdom": "^27.4.0",
"marked": "^17.0.1",
"qrcode": "^1.5.4"
"papaparse": "^5.5.3",
"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;
var turnstileLoaded: (() => void) | undefined;
declare const __APP_VERSION__: string;
declare const COMMIT_HASH: string;
}
export {};
@@ -4,26 +4,41 @@
label: string;
}
export let options: Option[] = [];
export let value: string | number = '';
export let placeholder = 'Select...';
export let searchable = false;
export let displayValue: (val: string | number) => string = (val) => {
return options.find((o) => o.value === val)?.label ?? String(val);
};
export let variant: string = '';
interface Props {
options?: Option[];
value?: string | number;
placeholder?: string;
searchable?: boolean;
displayValue?: (val: string | number) => string;
variant?: string;
}
let isOpen = false;
let searchQuery = '';
let dropdownElement: HTMLDivElement;
let {
options = [],
value = $bindable(''),
placeholder = 'Select...',
searchable = false,
displayValue = (val) => {
return options.find((o) => o.value === val)?.label ?? String(val);
},
variant = ''
}: Props = $props();
$: filteredOptions = searchable
? options.filter(
(opt) =>
opt.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
String(opt.value).toLowerCase().includes(searchQuery.toLowerCase())
)
: options;
let isOpen = $state(false);
let searchQuery = $state('');
let dropdownElement = $state<HTMLDivElement | undefined>(undefined);
let dropdownListElement = $state<HTMLDivElement | undefined>(undefined);
let dropdownMaxHeight = $state('12rem');
let filteredOptions = $derived(
searchable
? options.filter(
(opt) =>
opt.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
String(opt.value).toLowerCase().includes(searchQuery.toLowerCase())
)
: options
);
function handleSelect(selectedValue: string | number) {
value = selectedValue;
@@ -39,10 +54,18 @@
function toggleDropdown() {
isOpen = !isOpen;
if (isOpen && searchable) {
if (isOpen) {
setTimeout(() => {
const input = dropdownElement?.querySelector('input[type="text"]') as HTMLInputElement;
input?.focus();
if (dropdownElement && dropdownListElement) {
const rect = dropdownElement.getBoundingClientRect();
const spaceBelow = window.innerHeight - rect.bottom - 8;
const maxCap = 416;
dropdownMaxHeight = Math.max(120, Math.min(spaceBelow, maxCap)) + 'px';
}
if (searchable) {
const input = dropdownElement?.querySelector('input[type="text"]') as HTMLInputElement;
input?.focus();
}
}, 0);
}
}
@@ -54,12 +77,12 @@
}
</script>
<svelte:window on:click={handleClickOutside} />
<svelte:window onclick={handleClickOutside} />
<div bind:this={dropdownElement} class="relative mb-2 w-full" class:dropdown-sm={variant === 'sm'}>
<button
type="button"
on:click={toggleDropdown}
onclick={toggleDropdown}
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-left transition-colors hover:bg-neutral-700"
class:dropdown-sm-btn={variant === 'sm'}
>
@@ -70,23 +93,29 @@
<div
class="absolute top-full z-50 mt-1 w-full rounded border border-neutral-700 bg-neutral-800 shadow-lg"
class:dropdown-sm-list={variant === 'sm'}
bind:this={dropdownListElement}
style="max-height: {dropdownMaxHeight}; width: 100%;"
>
{#if searchable}
<input
type="text"
placeholder="Search..."
class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none"
class:dropdown-sm-input={variant === 'sm'}
bind:value={searchQuery}
on:keydown={handleKeyDown}
/>
<div style="position: sticky; top: 0; z-index: 1; background: inherit;">
<input
type="text"
placeholder="Search..."
class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none"
class:dropdown-sm-input={variant === 'sm'}
bind:value={searchQuery}
onkeydown={handleKeyDown}
/>
</div>
{/if}
<div class="max-h-48 overflow-y-auto">
<div
class="scrollbar-thin scrollbar-thumb-neutral-600 scrollbar-track-neutral-700"
style="overflow-y: auto; max-height: calc({dropdownMaxHeight} - 3rem);"
>
{#each filteredOptions as option (option.value)}
<button
type="button"
on:click={() => handleSelect(option.value)}
onclick={() => handleSelect(option.value)}
class="w-full border-b border-neutral-700 px-3 py-2 text-left last:border-b-0 hover:bg-neutral-600"
class:bg-neutral-700={value === option.value}
class:dropdown-sm-option={variant === 'sm'}
@@ -1,3 +1,7 @@
<script lang="ts">
import { resolve } from '$app/paths';
</script>
<div
class="mb-5 max-h-10 w-full border-t border-neutral-800 pt-5 text-center text-sm text-neutral-500"
>
@@ -10,5 +14,18 @@
Source Code
</a>
<span class="mx-1">•</span>
<a href={resolve('/stats')} class="text-neutral-400 underline hover:text-neutral-200"
>Statistics</a
>
<span class="mx-1">•</span>
v{__APP_VERSION__}
<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>
+104 -73
View File
@@ -4,45 +4,62 @@
import { parseTotpEnabled } from '$lib/utils/totp';
import { tick } from 'svelte';
import { extractError } from '$lib/utils/misc';
import type { ModalItem, ModalMode } from '$lib/types/modal';
export let show = false;
export let mode:
| 'decrypt'
| 'encrypt'
| 'confirm'
| 'prompt'
| 'multiselect'
| 'totp'
| 'totpSetup'
| 'report' = 'decrypt';
export let title = '';
export let message = '';
export let error = '';
export let placeholder = '';
export let inputType = 'text';
export let items: { label: string; value: unknown }[] = [];
export let initialValue: unknown = null;
export let totpActive: boolean | null = null;
export let reportTarget: 'user' | 'paste' | null = null;
export let reportTargetId: string | number | null = null;
export let reportSiteKey: string | null = null;
export let onConfirm: (value: unknown) => void;
export let onCancel: () => void;
export let confirmButtonText = '';
interface Props {
show?: boolean;
mode?: ModalMode;
title?: string;
message?: string;
error?: string;
placeholder?: string;
inputType?: string;
inputMaxLength?: number | null;
items?: ModalItem[];
initialValue?: unknown;
totpActive?: boolean | null;
reportTarget?: 'user' | 'paste' | null;
reportTargetId?: string | number | null;
reportSiteKey?: string | null;
onConfirm: (value: unknown) => void;
onCancel: () => void;
confirmButtonText?: string;
}
let inputValue: string | unknown[] | boolean = '';
let totpSecret = '';
let totpQr = '';
let totpEnabled = false;
let totpInitialized = false;
let totpLoading = false;
let totpError = '';
let displayError = '';
let reportTypes: string[] = [];
let reportType = '';
let reportInitialized = false;
let reportLoading = false;
let turnstileEl: HTMLDivElement | null = null;
let {
show = false,
mode = 'decrypt',
title = '',
message = '',
error = $bindable(''),
placeholder = '',
inputType = 'text',
inputMaxLength = null,
items = [],
initialValue = null,
totpActive = null,
reportTarget = null,
reportTargetId = null,
reportSiteKey = null,
onConfirm,
onCancel,
confirmButtonText = ''
}: Props = $props();
let inputValue: string | unknown[] | boolean = $state('');
let totpSecret = $state('');
let totpQr = $state('');
let totpEnabled = $state(false);
let totpInitialized = $state(false);
let totpLoading = $state(false);
let totpError = $state('');
let displayError = $derived(error || totpError);
let reportTypes: string[] = $state([]);
let reportType = $state('');
let reportInitialized = $state(false);
let reportLoading = $state(false);
let multiselectInitialized = $state(false);
let turnstileEl: HTMLDivElement | null = $state(null);
let turnstileWidgetId: string | null = null;
const titleMap = {
@@ -61,29 +78,12 @@
encrypt: 'Encrypt',
confirm: 'Confirm',
multiselect: 'Confirm',
totpSetup: totpEnabled ? 'Disable' : 'Enable',
totpSetup: 'Enable',
totp: 'Verify',
report: 'Submit Report',
prompt: 'Submit'
};
$: displayError = error || totpError;
$: if (!show) resetModal();
$: if (show && mode === 'totpSetup' && !totpInitialized) {
totpInitialized = true;
if (totpActive !== null) {
totpEnabled = totpActive;
}
initializeTotp();
}
$: if (show && mode === 'report' && !reportInitialized) {
reportInitialized = true;
initializeReport();
}
function resetModal() {
inputValue =
initialValue !== null
@@ -101,6 +101,7 @@
reportType = '';
reportInitialized = false;
reportLoading = false;
multiselectInitialized = false;
if (turnstileWidgetId && typeof window !== 'undefined' && window.turnstile?.remove) {
window.turnstile.remove(turnstileWidgetId);
}
@@ -204,7 +205,8 @@
return null;
}
async function handleSubmit() {
async function handleSubmit(event: Event) {
event.preventDefault();
if (mode === 'report') {
await submitReport();
return;
@@ -230,7 +232,9 @@
}
turnstileWidgetId = window.turnstile.render(turnstileEl, {
sitekey: reportSiteKey,
theme: 'dark'
theme: 'dark',
size: 'flexible',
appearence: 'interaction-only'
});
};
if (window.turnstile) {
@@ -298,7 +302,8 @@
body.VerificationToken = verification;
}
const targetId = encodeURIComponent(String(reportTargetId));
const res = await fetch(`/api/${reportTarget}/${targetId}/report`, {
const reportPath = reportTarget === 'paste' ? 'pastes' : 'users';
const res = await fetch(`/api/report/${reportPath}/${targetId}/report`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -384,18 +389,45 @@
}
}
$: displayTitle = title || titleMap[mode];
$: confirmLabel = confirmButtonText || confirmLabelMap[mode];
$: shouldShowInput =
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report';
$effect(() => {
if (!show) resetModal();
});
$effect(() => {
if (show && mode === 'totpSetup' && !totpInitialized) {
totpInitialized = true;
if (totpActive !== null) {
totpEnabled = totpActive;
}
initializeTotp();
}
});
$effect(() => {
if (show && mode === 'report' && !reportInitialized) {
reportInitialized = true;
initializeReport();
}
});
$effect(() => {
if (show && mode === 'multiselect' && !multiselectInitialized) {
multiselectInitialized = true;
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
}
});
let displayTitle = $derived(title || titleMap[mode]);
let confirmLabel = $derived(
confirmButtonText ||
(mode === 'totpSetup' ? (totpEnabled ? 'Disable' : 'Enable') : confirmLabelMap[mode])
);
let shouldShowInput = $derived(
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report'
);
</script>
{#if show}
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-xs">
<form
on:submit|preventDefault={handleSubmit}
class="w-full max-w-md rounded bg-neutral-900 p-6"
onsubmit={handleSubmit}
class="w-full max-w-md rounded border border-neutral-800 bg-neutral-900 p-6"
>
<h2 class="mb-4 text-xl font-semibold text-white">
{displayTitle}
@@ -438,7 +470,7 @@
>
<button
type="button"
on:click={copySecret}
onclick={copySecret}
class="rounded bg-neutral-700 px-3 py-1 text-sm font-medium text-white transition-colors hover:bg-neutral-800"
>
Copy
@@ -453,7 +485,7 @@
maxlength="6"
inputmode="numeric"
pattern="[0-9]*"
on:input={onCodeInput}
oninput={onCodeInput}
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
/>
{/if}
@@ -475,20 +507,19 @@
{/if}
<textarea
bind:value={inputValue}
maxlength="1000"
maxlength={inputMaxLength ?? undefined}
placeholder={placeholder || 'Describe the issue'}
class="h-28 w-full resize-none rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
></textarea>
{#if reportSiteKey}
<div class="flex justify-center">
<div class="cf-turnstile" bind:this={turnstileEl}></div>
</div>
<div class="cf-turnstile w-full" bind:this={turnstileEl}></div>
{/if}
{/if}
</div>
{:else if shouldShowInput}
<input
type={inputType}
maxlength={inputMaxLength ?? undefined}
bind:value={inputValue}
class="mb-3 w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
{placeholder}
@@ -534,7 +565,7 @@
</button>
<button
type="button"
on:click={onCancel}
onclick={onCancel}
class="cursor-pointer rounded border border-neutral-700 px-4 py-2 text-white hover:bg-neutral-950"
>
Cancel
@@ -2,7 +2,7 @@
import Modal from '$lib/components/Modal.svelte';
import { cancelModal, confirmModal, modal } from '$lib/stores/modal';
$: state = $modal;
let state = $derived($modal);
</script>
<Modal
@@ -13,6 +13,7 @@
error={state.error}
placeholder={state.placeholder}
inputType={state.inputType}
inputMaxLength={state.maxInputLength ?? null}
items={state.items}
initialValue={state.initialValue}
totpActive={state.totpActive}
@@ -2,11 +2,12 @@
import { user } from '$lib/stores/user';
import { resolve } from '$app/paths';
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 type { PageData } from '../../routes/$types';
import { slide } from 'svelte/transition';
import { Menu, X } from '@lucide/svelte';
import { onMount } from 'svelte';
function logout() {
clearTokens();
@@ -14,39 +15,70 @@
window.location.href = '/';
}
export let data: PageData;
interface Props {
data: PageData;
}
let menuOpen = false;
let { data }: Props = $props();
let menuOpen = $state(false);
let currentPath = page.url.pathname;
let returnParam =
currentPath !== '/' && !currentPath.startsWith('/login') && !currentPath.startsWith('/register')
? `?return=${encodeURIComponent(page.url.pathname + page.url.search)}`
: '';
function handleClickOutside(event: MouseEvent) {
const navbar = document.getElementById('navbar');
const mobileMenu = document.getElementById('mobile-menu');
if (menuOpen && mobileMenu && navbar && !navbar.contains(event.target as Node)) {
menuOpen = false;
}
}
onMount(() => {
document.addEventListener('click', handleClickOutside);
return () => {
document.removeEventListener('click', handleClickOutside);
};
});
</script>
<div class="top-0 left-0 z-100 h-15 w-full bg-neutral-900">
<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>
<a href={resolve('/')} class="text-xl font-bold text-white hover:text-neutral-300">Sharpbin</a
<div class="flex items-center gap-6">
<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>
{#if $user}
<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
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}
<a
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
on:click={logout}
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800"
onclick={logout}
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
>Logout</button
>
</div>
@@ -54,13 +86,14 @@
<div class="ml-auto flex items-center space-x-4">
<a
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 -->
<a
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
?.registration_enabled
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600 {data
.options?.registration_enabled
? ''
: 'cursor-not-allowed bg-neutral-800 text-neutral-500!'}">Register</a
>
@@ -75,20 +108,21 @@
</a>
<button
class="ml-auto flex h-10 w-10 items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 hover:bg-neutral-700 focus:outline-none"
on:click={() => (menuOpen = !menuOpen)}
onclick={() => (menuOpen = !menuOpen)}
aria-label="Toggle Menu"
aria-expanded={menuOpen}
>
{#if menuOpen}
<X class="h-6 w-6 text-white" />
<X class="pointer-events-none h-6 w-6 text-white" />
{:else}
<Menu class="h-6 w-6 text-white" />
<Menu class="pointer-events-none h-6 w-6 text-white" />
{/if}
</button>
</div>
{#if menuOpen}
<div
class="mx-auto mb-2 w-full rounded-b border-b border-neutral-800 bg-neutral-900 px-2 py-3 md:hidden"
id="mobile-menu"
in:slide={{ duration: 180 }}
out:slide={{ duration: 180 }}
style="z-index:1000;position:relative;"
@@ -96,23 +130,23 @@
<a
href={resolve('/recent')}
class="block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
on:click={() => (menuOpen = false)}>Recent Pastes</a
onclick={() => (menuOpen = false)}>Recent Pastes</a
>
{#if $user}
{#if $user.roles.includes(1) || $user.roles.includes(255)}
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
<a
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"
on:click={() => (menuOpen = false)}>Reports</a
onclick={() => (menuOpen = false)}>Reports</a
>
{/if}
<a
href={resolve(`/user/${$user.username}`)}
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"
on:click={() => (menuOpen = false)}>Profile</a
onclick={() => (menuOpen = false)}>Profile</a
>
<button
on:click={() => {
onclick={() => {
logout();
menuOpen = false;
}}
@@ -123,7 +157,7 @@
<a
href={resolve(`/login${returnParam}`)}
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"
on:click={() => (menuOpen = false)}>Login</a
onclick={() => (menuOpen = false)}>Login</a
>
<!-- eslint-disable svelte/no-navigation-without-resolve -->
<a
@@ -132,7 +166,7 @@
.options?.registration_enabled
? ''
: 'cursor-not-allowed bg-neutral-900 text-neutral-500'}"
on:click={() => (menuOpen = false)}>Register</a
onclick={() => (menuOpen = false)}>Register</a
>
<!-- eslint-enable svelte/no-navigation-without-resolve -->
{/if}
+172 -68
View File
@@ -1,95 +1,199 @@
<script lang="ts">
import {
tooltip,
dateToRelativeString,
extractDateFromUUIDv7,
formatNumber,
formatBytes
} from '$lib/utils/misc';
import { tooltip, dateToRelativeString, formatNumber, formatBytes } from '$lib/utils/misc';
import { resolve } from '$app/paths';
import { Eye, FileBox, Code, User, History, Calendar, Timer } from '@lucide/svelte';
import {
Eye,
FileBox,
Code,
User,
History,
CalendarDays,
CalendarOff,
Lock,
EyeOff,
Globe,
HatGlasses
} from '@lucide/svelte';
import { syntaxes } from '$lib/consts';
import type { Paste } from '$lib/types/paste';
export let paste: Paste;
export let now: Date;
interface Props {
paste: Paste;
now: Date;
showUser?: boolean;
compact?: boolean;
}
const createdAt = extractDateFromUUIDv7(paste.uuid);
const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext'];
let { paste, now, showUser = true, compact = false }: Props = $props();
let syntax = $derived(syntaxes[paste.syntax] ?? syntaxes['plaintext']);
</script>
<a
href={resolve(`/${paste.id}`)}
class="flex 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"
>
<span
class="w-fit max-w-full truncate text-lg font-semibold text-neutral-100 hover:text-white"
use:tooltip={paste.title || 'Untitled Paste'}
{#if compact}
<a
href={resolve(`/${paste.id}`)}
class="flex flex-col gap-1 rounded border border-neutral-700 bg-neutral-800 px-4 py-3 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
>
{paste.title || 'Untitled Paste'}
</span>
<div class="flex flex-row justify-between">
<div>
<div class="flex w-full flex-row justify-between">
<span
class="text-md w-fit max-w-full truncate font-semibold text-neutral-100 hover:text-white"
use:tooltip={paste.title || 'Untitled Paste'}
>
{paste.title || 'Untitled Paste'}
</span>
<div
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" />
<span>
{#if createdAt}
{#if createdAt.getTime() > Date.now() - 86_400_000}
Created {dateToRelativeString(createdAt, true, false, now)}
{:else}
Created on {createdAt.toLocaleDateString()}
{/if}
<CalendarDays class="h-4 w-4" />
{#if paste.createdAt}
{#if paste.createdAt > Date.now() - 86_400_000}
Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
{:else}
Creation date unknown
{new Date(paste.createdAt).toLocaleDateString()}
{/if}
</span>
{:else}
Creation date unknown
{/if}
</div>
{#if paste.expiresAt > 0}
</div>
<div class="flex flex-row justify-between text-sm text-neutral-400">
<div>
{#if showUser}
<div class="flex items-center gap-2">
{#if paste.author}
<User class="h-4 w-4" />
{:else}
<HatGlasses class="h-4 w-4" />
{/if}
{paste.author?.username ?? 'Anonymous'}
</div>
{:else}
<div class="flex items-center gap-2">
{#if paste.visibility === 0}
<Globe class="h-4 w-4" />
Public
{:else if paste.visibility === 1}
<EyeOff class="h-4 w-4" />
Unlisted
{:else}
<Lock class="h-4 w-4" />
Private
{/if}
</div>
{/if}
<div class="flex items-center gap-2">
<Eye class="h-4 w-4" />
{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}
</div>
</div>
<div>
<div
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={new Date(paste.expiresAt).toLocaleString()}
class="flex items-center gap-2"
use:tooltip={paste.isCompressed
? `Compressed Size: ${formatBytes(paste.storedSize)}`
: ''}
>
<Timer class="h-4 w-4" />
<FileBox class="h-4 w-4" />
{formatBytes(paste.originalSize)}
</div>
<div class="flex items-center gap-2">
<Code class="h-4 w-4" />
{syntax.name}
</div>
</div>
</div>
</a>
{:else}
<a
href={resolve(`/${paste.id}`)}
class="flex 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"
>
<span
class="w-fit max-w-full truncate text-lg font-semibold text-neutral-100 hover:text-white"
use:tooltip={paste.title || 'Untitled Paste'}
>
{paste.title || 'Untitled Paste'}
</span>
<div class="flex flex-row justify-between">
<div>
<div
class="flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
>
<CalendarDays class="h-4 w-4" />
<span>
{paste.expiresAt > 0 && paste.expiresAt < Date.now()
? `Expired ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`
: `Expires in ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`}
{#if paste.createdAt}
{#if paste.createdAt > Date.now() - 86_400_000}
Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
{:else}
Created on {new Date(paste.createdAt).toLocaleDateString()}
{/if}
{:else}
Creation date unknown
{/if}
</span>
</div>
{/if}
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
<User class="h-4 w-4" />
<span>{paste.author?.username ?? 'Anonymous'}</span>
{#if paste.editedAt && paste.editedAt != 0}
<div
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={new Date(paste.editedAt).toLocaleString()}
>
<History class="h-4 w-4" />
<span>
{#if paste.editedAt > Date.now() - 86_400_000}
Edited {dateToRelativeString(new Date(paste.editedAt), true, false, now)}
{:else}
Edited on {new Date(paste.editedAt).toLocaleDateString()}
{/if}
</span>
</div>
{/if}
{#if paste.expiresAt > 0}
<div
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={new Date(paste.expiresAt).toLocaleString()}
>
<CalendarOff class="h-4 w-4" />
<span>
{paste.expiresAt > 0 && paste.expiresAt < Date.now()
? `Expired ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`
: `Expires in ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`}
</span>
</div>
{/if}
{#if showUser}
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
{#if paste.author}
<User class="h-4 w-4" />
{:else}
<HatGlasses class="h-4 w-4" />
{/if}
<span>{paste.author?.username ?? 'Anonymous'}</span>
</div>
{/if}
</div>
{#if paste.editedAt}
<div>
<div class="flex items-center gap-2 text-sm text-neutral-400">
<Eye class="h-4 w-4" />
<span>{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}</span>
</div>
<div
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={new Date(paste.editedAt).toLocaleString()}
use:tooltip={paste.isCompressed
? `Compressed Size: ${formatBytes(paste.storedSize)}`
: ''}
>
<History class="h-4 w-4" />
<span>Edited {dateToRelativeString(new Date(paste.editedAt), true, false, now)}</span>
<FileBox class="h-4 w-4" />
<span>{formatBytes(paste.originalSize)}</span>
</div>
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
<Code class="h-4 w-4" />
<span>{syntax.name}</span>
</div>
{/if}
</div>
<div>
<div class="flex items-center gap-2 text-sm text-neutral-400">
<Eye class="h-4 w-4" />
<span>{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}</span>
</div>
<div
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={paste.isCompressed ? `Compressed Size: ${formatBytes(paste.size)}` : ''}
>
<FileBox class="h-4 w-4" />
<span>{formatBytes(paste.trueSize)}</span>
</div>
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
<Code class="h-4 w-4" />
<span>{syntax.name}</span>
</div>
</div>
</div>
</a>
</a>
{/if}
@@ -0,0 +1,283 @@
<script lang="ts">
import type { CommentReaction, CommentTreeNode } from '$lib/types/comment';
import { dateToRelativeString, tooltip } from '$lib/utils/misc';
import { parseCommentMarkdown } from '$lib/utils/markdown';
import { escapeHtml } from '$lib/utils/html';
import { user } from '$lib/stores/user';
import PasteCommentItem from '$lib/components/PasteCommentItem.svelte';
import { ThumbsUp, ThumbsDown, Trash2, Shredder } from '@lucide/svelte';
import { resolve } from '$app/paths';
import RichTextEditor from './RichTextEditor.svelte';
import { hasRole, roles } from '$lib/utils/auth';
interface Props {
node: CommentTreeNode;
depth?: number;
now: Date;
reactingIds: Record<number, boolean>;
onReact: (commentId: number, target: 1 | 2, current: CommentReaction) => Promise<void>;
onReply: (parentCommentID: number, content: string) => Promise<boolean>;
deleteCommentAction: (commentId: number, hardDelete?: boolean) => Promise<boolean>;
}
let {
node,
depth = 1,
now,
reactingIds,
onReact,
onReply,
deleteCommentAction
}: Props = $props();
let deleting = $state(false);
const maxCommentLength = 320;
let expanded = $state(false);
let showDeepReplies = $state(false);
let replyOpen = $state(false);
let replyText = $state('');
let replySubmitting = $state(false);
let replyError = $state('');
let replyEditor = $state<{ focus: () => void } | undefined>(undefined);
let commentText = $derived(node.content ?? '*[Deleted comment]*');
let isLongComment = $derived(commentText.length > maxCommentLength);
let isDeleted = $derived(node.content === null);
let parsedHtml = $derived(
isDeleted ? escapeHtml(commentText) : parseCommentMarkdown(commentText)
);
let authorDisplay = $derived(
node.author
? (node.author.displayName?.length || 0) > 0
? node.author.displayName
: node.author.username
: 'Deleted User'
);
async function submitReply() {
replyError = '';
if (!$user) {
replyError = 'You must be signed in to reply.';
return;
}
if (!replyText.trim()) {
replyError = 'Reply cannot be empty.';
return;
}
replySubmitting = true;
const ok = await onReply(node.id, replyText);
replySubmitting = false;
if (ok) {
replyText = '';
replyError = '';
replyOpen = false;
} else {
replyError = 'Failed to post reply.';
}
}
function openReply(initialText: string) {
replyOpen = true;
replyError = '';
replyText = initialText;
queueMicrotask(() => {
replyEditor?.focus();
});
}
async function handleDelete(hardDelete = false) {
if (deleting) return;
deleting = true;
await deleteCommentAction(node.id, hardDelete);
deleting = false;
}
</script>
<div class="p-3">
<div class="mb-2 flex items-center justify-between gap-3 text-xs text-neutral-400">
<div class="flex min-w-0 items-center gap-2 text-lg">
{#if node.author}
{#if node.author.isBanned}
<span class="text-red-500">BANNED</span>
{/if}
<a
href={resolve(`/user/${node.author?.username}`)}
class="flex items-center gap-2 underline"
>
<span
class="truncate font-semibold text-neutral-200 {node.author.isBanned
? 'line-through decoration-red-500 decoration-2'
: ''}">{authorDisplay}</span
>
</a>
{/if}
{#if node.updatedAt}
<span
class="text-sm text-neutral-500"
use:tooltip={`Edited on ${new Date(node.updatedAt * 1000).toLocaleString()} • ${dateToRelativeString(new Date(node.updatedAt * 1000), true, true, now, 3)}`}
>edited</span
>
{/if}
</div>
<span
class="shrink-0"
use:tooltip={`${new Date(node.createdAt * 1000).toLocaleString()} • ${dateToRelativeString(new Date(node.createdAt * 1000), true, true, now, 3)}`}
>{dateToRelativeString(new Date(node.createdAt * 1000), true, false, now, 2)}</span
>
</div>
<div class="text-sm leading-relaxed text-neutral-200">
<div class="wrap-break-word" class:italic={isDeleted} class:text-neutral-800={isDeleted}>
{#if expanded || !isLongComment}
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html parsedHtml}
{:else}
<div class="line-clamp-3">
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html parsedHtml}
</div>
{/if}
</div>
{#if isLongComment}
<button
type="button"
class="mt-2 text-xs text-neutral-400 hover:text-neutral-200"
onclick={() => {
expanded = !expanded;
}}
>
{expanded ? 'Show less' : 'Show more'}
</button>
{/if}
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<button
type="button"
class="h-7 min-w-12 rounded border px-2 py-1 text-xs {node.userReaction !== 1
? 'hover:bg-neutral-800 active:bg-neutral-700'
: 'hover:bg-green-800 active:bg-green-700'} disabled:cursor-not-allowed disabled:hover:bg-transparent"
class:border-green-700={node.userReaction === 1}
class:bg-green-900={node.userReaction === 1}
class:text-green-200={node.userReaction === 1}
class:border-neutral-700={node.userReaction !== 1}
class:text-neutral-300={node.userReaction !== 1}
onclick={() => onReact(node.id, 1, node.userReaction)}
disabled={reactingIds[node.id] || !$user}
>
<ThumbsUp class="mr-1 inline h-3.5 w-3.5" />
{node.likes}
</button>
<button
type="button"
class="h-7 min-w-12 rounded border px-2 py-1 text-xs {node.userReaction !== 2
? 'hover:bg-neutral-800 active:bg-neutral-700'
: 'hover:bg-red-800 active:bg-red-700'} disabled:cursor-not-allowed disabled:hover:bg-transparent"
class:border-red-700={node.userReaction === 2}
class:bg-red-900={node.userReaction === 2}
class:text-red-200={node.userReaction === 2}
class:border-neutral-700={node.userReaction !== 2}
class:text-neutral-300={node.userReaction !== 2}
onclick={() => onReact(node.id, 2, node.userReaction)}
disabled={reactingIds[node.id] || !$user}
>
<ThumbsDown class="mr-1 inline h-3.5 w-3.5" />
{node.dislikes}
</button>
{#if $user}
{#if !replyOpen}
<button
type="button"
class="h-7 min-w-12 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
onclick={() => {
openReply(node.content ? `> ${node.content.replace(/\n/g, '\n> ')}\n\n` : '');
}}
>
Quote
</button>
{/if}
<button
type="button"
class="h-7 min-w-12 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
onclick={() => {
if (replyOpen) {
replyOpen = false;
replyError = '';
replyText = '';
return;
}
openReply('');
}}
>
{replyOpen ? 'Cancel' : 'Reply'}
</button>
{#if node.author?.uuid === $user.uuid || hasRole($user.roles, 4) || hasRole($user.roles, 2)}
<div class="ml-auto">
<button
type="button"
class="h-7 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
onclick={() => handleDelete(false)}
disabled={deleting}
>
<Trash2 class="inline h-3.5 w-3.5" />
</button>
{#if hasRole($user.roles, roles.Moderator) || hasRole($user.roles, roles.Admin)}
<button
type="button"
class="h-7 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
onclick={() => handleDelete(true)}
disabled={deleting}
>
<Shredder class="inline h-3.5 w-3.5" />
</button>
{/if}
</div>
{/if}
{/if}
</div>
{#if replyOpen}
<RichTextEditor
class="mt-3"
bind:this={replyEditor}
bind:value={replyText}
placeholder="Write a reply..."
onSubmit={submitReply}
disabled={replySubmitting}
submitting={replySubmitting}
/>
{#if replyError}
<p class="mt-2 text-xs text-red-400">{replyError}</p>
{/if}
{/if}
{#if node.children.length > 0}
<div class="mt-3 border-l border-neutral-800 pl-3">
{#if depth >= 3 && !showDeepReplies}
<button
type="button"
class="rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:text-neutral-100"
onclick={() => {
showDeepReplies = true;
}}
>
Show {node.children.length} more repl{node.children.length === 1 ? 'y' : 'ies'}
</button>
{:else}
<div class="space-y-3">
{#each node.children as child (child.id)}
<PasteCommentItem
node={child}
depth={depth + 1}
{now}
{reactingIds}
{onReact}
{onReply}
{deleteCommentAction}
/>
{/each}
</div>
{/if}
</div>
{/if}
</div>
@@ -0,0 +1,294 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getToken } from '$lib/utils/auth';
import { user } from '$lib/stores/user';
import type {
CommentReaction,
CommentReactionResult,
PasteComment,
CommentTreeNode
} from '$lib/types/comment';
import PasteCommentItem from '$lib/components/PasteCommentItem.svelte';
import { SvelteMap } from 'svelte/reactivity';
import RichTextEditor from './RichTextEditor.svelte';
import { openModal } from '$lib/stores/modal';
interface Props {
pasteId: string;
initialComments?: PasteComment[];
}
let { pasteId, initialComments = [] }: Props = $props();
let comments = $derived.by(() => [...initialComments]);
let loading = $state(false);
let posting = $state(false);
let now = $state(new Date());
let interval: ReturnType<typeof setInterval> | null = null;
let errorMessage = $state('');
let newComment = $state('');
let reactingIds = $state<Record<number, boolean>>({});
const sortedComments = $derived(
[...comments].sort((a, b) => {
if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;
return a.id - b.id;
})
);
const threadedComments = $derived(buildCommentTree(sortedComments));
onMount(() => {
interval = setInterval(() => {
now = new Date();
}, 1000 * 30);
void refreshComments();
return () => {
if (interval) clearInterval(interval);
};
});
function buildCommentTree(list: PasteComment[]): CommentTreeNode[] {
const nodes = new SvelteMap<number, CommentTreeNode>();
const roots: CommentTreeNode[] = [];
for (const comment of list) {
nodes.set(comment.id, {
...comment,
children: []
});
}
for (const node of nodes.values()) {
if (node.parentCommentID && nodes.has(node.parentCommentID)) {
nodes.get(node.parentCommentID)?.children.push(node);
} else {
roots.push(node);
}
}
return roots;
}
async function refreshComments() {
loading = true;
errorMessage = '';
const token = getToken();
const headers = new Headers();
if (token) headers.set('Authorization', `Bearer ${token}`);
try {
const res = await fetch(`/api/paste/${pasteId}/comments`, { headers });
if (!res.ok) {
errorMessage = 'Failed to load comments.';
loading = false;
return;
}
const json = await res.json();
comments = Array.isArray(json?.comments) ? (json.comments as PasteComment[]) : [];
} catch {
errorMessage = 'Failed to load comments.';
} finally {
loading = false;
}
}
async function postComment(content: string, parentCommentID: number | null): Promise<boolean> {
errorMessage = '';
const token = getToken();
if (!token) {
errorMessage = 'You must be signed in to comment.';
return false;
}
const trimmed = content.trim();
if (!trimmed) {
errorMessage = 'Comment cannot be empty.';
return false;
}
if (parentCommentID === null) posting = true;
try {
const res = await fetch(`/api/paste/${pasteId}/comments`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ content: trimmed, parentCommentID })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
errorMessage = err?.message || 'Failed to post comment.';
return false;
}
const json = await res.json();
const created = json?.comment as PasteComment | undefined;
if (!created) {
errorMessage = 'Failed to post comment.';
return false;
}
comments = [...comments, created];
if (parentCommentID === null) newComment = '';
return true;
} catch {
errorMessage = 'Failed to post comment.';
return false;
} finally {
if (parentCommentID === null) posting = false;
}
}
async function reactToComment(commentId: number, target: 1 | 2, current: CommentReaction) {
errorMessage = '';
const token = getToken();
if (!token) {
errorMessage = 'You must be signed in to react.';
return;
}
reactingIds = { ...reactingIds, [commentId]: true };
const nextReaction: CommentReaction = current === target ? null : target;
try {
const res = await fetch(`/api/paste/${pasteId}/comments/${commentId}/reaction`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ reaction: nextReaction })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
errorMessage = err?.message || 'Failed to apply reaction.';
return;
}
const json = await res.json();
const reaction = json?.reaction as CommentReactionResult | undefined;
if (!reaction) {
errorMessage = 'Failed to apply reaction.';
return;
}
comments = comments.map((comment) =>
comment.id === commentId
? {
...comment,
likes: reaction.likes,
dislikes: reaction.dislikes,
userReaction: reaction.userReaction
}
: comment
);
} catch {
errorMessage = 'Failed to apply reaction.';
} finally {
const next = { ...reactingIds };
delete next[commentId];
reactingIds = next;
}
}
async function submitTopLevelComment(content: string) {
await postComment(content, null);
}
async function deleteComment(commentId: number, hardDelete = false): Promise<boolean> {
errorMessage = '';
const token = getToken();
if (!token) {
errorMessage = 'You must be signed in to delete comments.';
return false;
}
const title = hardDelete ? 'Hard delete comment?' : 'Delete comment?';
const message = hardDelete
? 'This permanently removes the comment from the thread. This cannot be undone.'
: 'This will remove the comment content while preserving the thread structure.';
const confirmButtonText = hardDelete ? 'Hard delete' : 'Delete';
const ok = await openModal<boolean>({
mode: 'confirm',
title,
message,
confirmButtonText,
cancelValue: false
});
if (!ok) {
return false;
}
try {
const query = hardDelete ? '?hardDelete=true' : '';
const res = await fetch(`/api/paste/${pasteId}/comments/${commentId}${query}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`
}
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
errorMessage = err?.message || 'Failed to delete comment.';
return false;
}
await refreshComments();
return true;
} catch {
errorMessage = 'Failed to delete comment.';
return false;
}
}
</script>
<section id="comments-section" class="mt-6 rounded border border-neutral-800 p-4">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<h2 class="text-xl font-semibold text-neutral-100">Comments ({comments.length})</h2>
<button
type="button"
class="rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:text-neutral-100"
onclick={refreshComments}
disabled={loading}
>
{loading ? 'Refreshing...' : 'Refresh'}
</button>
</div>
{#if $user}
<RichTextEditor
bind:value={newComment}
placeholder="Write a comment..."
onSubmit={submitTopLevelComment}
disabled={posting}
submitting={posting}
/>
{:else}
<div class="mb-4 rounded border border-neutral-800 p-3 text-sm text-neutral-400">
Sign in to post comments and reactions.
</div>
{/if}
{#if errorMessage}
<div class="mb-4 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
{errorMessage}
</div>
{/if}
{#if loading && comments.length === 0}
<div class="rounded border border-neutral-800 p-3 text-sm text-neutral-400">
Loading comments...
</div>
{:else if threadedComments.length === 0}
<div class="rounded border border-neutral-800 p-3 text-sm text-neutral-400">
No comments yet.
</div>
{:else}
<div class="space-y-3">
{#each threadedComments as node (node.id)}
<PasteCommentItem
{node}
{now}
{reactingIds}
onReact={reactToComment}
onReply={(parentCommentID, content) => postComment(content, parentCommentID)}
deleteCommentAction={deleteComment}
/>
{/each}
</div>
{/if}
</section>
@@ -0,0 +1,217 @@
<script lang="ts">
import { Bold, Italic, CodeXml, Quote } from '@lucide/svelte';
import { parseCommentMarkdown } from '$lib/utils/markdown';
interface Props {
class?: string;
value?: string;
placeholder?: string;
disabled?: boolean;
submitting?: boolean;
submitLabel?: string;
submittingLabel?: string;
onSubmit?: (value: string) => void | Promise<void>;
}
let {
class: className = '',
value = $bindable(''),
placeholder = 'Write a comment...',
disabled = false,
submitting = false,
submitLabel = 'Post comment',
submittingLabel = 'Posting...',
onSubmit
}: Props = $props();
let editor = $state<HTMLTextAreaElement | null>(null);
let mode = $state<'preview' | 'raw'>('raw');
const isDisabled = $derived(disabled || submitting);
const canSubmit = $derived(!isDisabled && value.trim().length > 0);
const parsedHtml = $derived(parseCommentMarkdown(value));
function focusEditor() {
editor?.focus();
}
export function focus() {
focusEditor();
}
function toggleMode() {
mode = mode === 'preview' ? 'raw' : 'preview';
queueMicrotask(focusEditor);
}
function replaceSelection(replacement: string, selectionStart: number, selectionEnd: number) {
value = `${value.slice(0, selectionStart)}${replacement}${value.slice(selectionEnd)}`;
}
function wrapSelection(prefix: string, suffix: string, fallback: string) {
if (!editor) {
value = `${value}${prefix}${fallback}${suffix}`;
return;
}
const selectionStart = editor.selectionStart;
const selectionEnd = editor.selectionEnd;
const selectedText = value.slice(selectionStart, selectionEnd);
const inner = selectedText.length > 0 ? selectedText : fallback;
const replacement = `${prefix}${inner}${suffix}`;
const cursorStart = selectionStart + prefix.length;
const cursorEnd = cursorStart + inner.length;
replaceSelection(replacement, selectionStart, selectionEnd);
queueMicrotask(() => {
if (!editor) return;
editor.focus();
editor.setSelectionRange(cursorStart, cursorEnd);
});
}
function addBold() {
wrapSelection('**', '**', 'text');
}
function addItalic() {
wrapSelection('*', '*', 'text');
}
function addCode() {
wrapSelection('`', '`', 'code');
}
function addQuote() {
if (!editor) {
value = `${value}${value.length > 0 && !value.endsWith('\n') ? '\n' : ''}> `;
return;
}
const selectionStart = editor.selectionStart;
const selectionEnd = editor.selectionEnd;
const selectedText = value.slice(selectionStart, selectionEnd);
if (selectedText.length === 0) {
const needsNewline = selectionStart > 0 && !value.slice(0, selectionStart).endsWith('\n');
const insert = `${needsNewline ? '\n' : ''}> `;
const nextCaret = selectionStart + insert.length;
replaceSelection(insert, selectionStart, selectionEnd);
queueMicrotask(() => {
if (!editor) return;
editor.focus();
editor.setSelectionRange(nextCaret, nextCaret);
});
return;
}
const quoted = selectedText
.split('\n')
.map((line) => (line.startsWith('> ') ? line : `> ${line}`))
.join('\n');
replaceSelection(quoted, selectionStart, selectionEnd);
queueMicrotask(() => {
if (!editor) return;
editor.focus();
editor.setSelectionRange(selectionStart, selectionStart + quoted.length);
});
}
async function submit() {
if (!canSubmit || !onSubmit) return;
await onSubmit(value);
if (mode === 'raw') {
queueMicrotask(focusEditor);
}
}
function handleKeydown(event: KeyboardEvent) {
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
event.preventDefault();
void submit();
}
}
</script>
<div class="mb-4 flex flex-col rounded {className}">
{#if mode === 'raw'}
<textarea
bind:this={editor}
class="min-h-24 w-full rounded-t border border-b-0 border-neutral-700 bg-neutral-900 p-2 font-mono text-sm text-neutral-100 outline-none"
{placeholder}
maxlength={5000}
disabled={isDisabled}
bind:value
onkeydown={handleKeydown}
></textarea>
{:else}
<div
class="min-h-24 w-full rounded-t border border-b-0 border-neutral-700 bg-neutral-900 p-2 text-sm text-neutral-100"
>
{#if value.trim().length === 0}
<div class="text-neutral-500">{placeholder}</div>
{:else}
<div class="text-sm leading-relaxed wrap-break-word text-neutral-200">
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html parsedHtml}
</div>
{/if}
</div>
{/if}
<div
class="flex w-full flex-col gap-2 rounded-b border border-neutral-700 bg-neutral-800 p-2 md:flex-row md:gap-0"
>
<div class="flex items-center gap-1">
<button
type="button"
class="rounded px-2 py-1 text-sm text-neutral-300 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-600"
onclick={addBold}
disabled={isDisabled || mode === 'preview'}
>
<Bold class="h-4 w-4" />
</button>
<button
type="button"
class="rounded px-2 py-1 text-sm text-neutral-300 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-600"
onclick={addItalic}
disabled={isDisabled || mode === 'preview'}
>
<Italic class="h-4 w-4" />
</button>
<button
type="button"
class="rounded px-2 py-1 text-sm text-neutral-300 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-600"
onclick={addQuote}
disabled={isDisabled || mode === 'preview'}
>
<Quote class="h-4 w-4" />
</button>
<button
type="button"
class="rounded px-2 py-1 text-sm text-neutral-300 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-600"
onclick={addCode}
disabled={isDisabled || mode === 'preview'}
>
<CodeXml class="h-5 w-5" />
</button>
</div>
<div class="flex flex-col items-center gap-2 md:ml-auto md:flex-row">
<button
type="button"
class="ml-auto w-full rounded border border-neutral-600 px-3 py-1 text-sm text-neutral-200 hover:border-neutral-500 hover:text-neutral-100 md:w-auto"
onclick={toggleMode}
disabled={isDisabled}
>
{mode === 'preview' ? 'Raw' : 'Preview'}
</button>
<button
type="button"
class="w-full rounded border border-neutral-600 px-3 py-1 text-sm text-neutral-100 hover:bg-neutral-600 disabled:cursor-not-allowed disabled:border-neutral-700 disabled:text-neutral-500 md:ml-2 md:w-auto"
onclick={submit}
disabled={!canSubmit}
>
{submitting ? submittingLabel : submitLabel}
</button>
</div>
</div>
</div>
+204 -156
View File
@@ -4,164 +4,212 @@ export type Syntax = {
};
export const syntaxes: Record<string, Syntax> = {
plaintext: { name: 'Plain Text', extension: '' },
abap: { name: 'ABAP', extension: '.abap' },
'actionscript-3': { name: 'ActionScript 3', extension: '.as' },
ada: { name: 'Ada', extension: '.adb' },
apache: { name: 'Apache', extension: '.conf' },
apex: { name: 'Apex', extension: '.cls' },
apl: { name: 'APL', extension: '.apl' },
applescript: { name: 'AppleScript', extension: '.applescript' },
ara: { name: 'ARA', extension: '.ara' },
asm: { name: 'Assembly', extension: '.asm' },
astro: { name: 'Astro', extension: '.astro' },
awk: { name: 'AWK', extension: '.awk' },
ballerina: { name: 'Ballerina', extension: '.bal' },
bat: { name: 'Batch', extension: '.bat' },
berry: { name: 'Berry', extension: '.be' },
bibtex: { name: 'BibTeX', extension: '.bib' },
bicep: { name: 'Bicep', extension: '.bicep' },
blade: { name: 'Blade', extension: '.blade.php' },
c: { name: 'C', extension: '.c' },
cadence: { name: 'Cadence', extension: '.cdc' },
clarity: { name: 'Clarity', extension: '.clar' },
clojure: { name: 'Clojure', extension: '.clj' },
cmake: { name: 'CMake', extension: '.cmake' },
cobol: { name: 'COBOL', extension: '.cob' },
codeql: { name: 'CodeQL', extension: '.ql' },
coffee: { name: 'CoffeeScript', extension: '.coffee' },
cpp: { name: 'C++', extension: '.cpp' },
crystal: { name: 'Crystal', extension: '.cr' },
csharp: { name: 'C#', extension: '.cs' },
css: { name: 'CSS', extension: '.css' },
cue: { name: 'CUE', extension: '.cue' },
d: { name: 'D', extension: '.d' },
dart: { name: 'Dart', extension: '.dart' },
diff: { name: 'Diff', extension: '.diff' },
docker: { name: 'Docker', extension: 'Dockerfile' },
'dream-maker': { name: 'Dream Maker', extension: '.dm' },
elixir: { name: 'Elixir', extension: '.ex' },
elm: { name: 'Elm', extension: '.elm' },
erb: { name: 'ERB', extension: '.erb' },
erlang: { name: 'Erlang', extension: '.erl' },
fish: { name: 'Fish', extension: '.fish' },
fsharp: { name: 'F#', extension: '.fs' },
gdresource: { name: 'Godot Resource', extension: '.tres' },
gdscript: { name: 'GDScript', extension: '.gd' },
gdshader: { name: 'Godot Shader', extension: '.gdshader' },
gherkin: { name: 'Gherkin', extension: '.feature' },
'git-commit': { name: 'Git Commit', extension: '' },
'git-rebase': { name: 'Git Rebase', extension: '' },
glsl: { name: 'GLSL', extension: '.glsl' },
gnuplot: { name: 'Gnuplot', extension: '.gp' },
go: { name: 'Go', extension: '.go' },
graphql: { name: 'GraphQL', extension: '.graphql' },
groovy: { name: 'Groovy', extension: '.groovy' },
hack: { name: 'Hack', extension: '.hack' },
haml: { name: 'Haml', extension: '.haml' },
handlebars: { name: 'Handlebars', extension: '.hbs' },
haskell: { name: 'Haskell', extension: '.hs' },
hcl: { name: 'HCL', extension: '.hcl' },
hjson: { name: 'HJSON', extension: '.hjson' },
hlsl: { name: 'HLSL', extension: '.hlsl' },
html: { name: 'HTML', extension: '.html' },
ini: { name: 'INI', extension: '.ini' },
java: { name: 'Java', extension: '.java' },
javascript: { name: 'JavaScript', extension: '.js' },
jison: { name: 'Jison', extension: '.jison' },
json: { name: 'JSON', extension: '.json' },
json5: { name: 'JSON5', extension: '.json5' },
jsonc: { name: 'JSONC', extension: '.json' },
jsonnet: { name: 'Jsonnet', extension: '.jsonnet' },
jssm: { name: 'JSSM', extension: '.jssm' },
jsx: { name: 'JSX', extension: '.jsx' },
julia: { name: 'Julia', extension: '.jl' },
kotlin: { name: 'Kotlin', extension: '.kt' },
latex: { name: 'LaTeX', extension: '.tex' },
less: { name: 'Less', extension: '.less' },
liquid: { name: 'Liquid', extension: '.liquid' },
lisp: { name: 'Lisp', extension: '.lisp' },
logo: { name: 'Logo', extension: '.logo' },
lua: { name: 'Lua', extension: '.lua' },
makefile: { name: 'Makefile', extension: '.makefile' },
markdown: { name: 'Markdown', extension: '.md' },
marko: { name: 'Marko', extension: '.marko' },
matlab: { name: 'MATLAB', extension: '.m' },
mdx: { name: 'MDX', extension: '.mdx' },
nginx: { name: 'Nginx', extension: '.conf' },
nim: { name: 'Nim', extension: '.nim' },
nix: { name: 'Nix', extension: '.nix' },
'objective-c': { name: 'Objective-C', extension: '.m' },
'objective-cpp': { name: 'Objective-C++', extension: '.mm' },
ocaml: { name: 'OCaml', extension: '.ml' },
pascal: { name: 'Pascal', extension: '.pas' },
perl: { name: 'Perl', extension: '.pl' },
php: { name: 'PHP', extension: '.php' },
plsql: { name: 'PL/SQL', extension: '.sql' },
postcss: { name: 'PostCSS', extension: '.pcss' },
powerquery: { name: 'Power Query', extension: '.pq' },
powershell: { name: 'PowerShell', extension: '.ps1' },
prisma: { name: 'Prisma', extension: '.prisma' },
prolog: { name: 'Prolog', extension: '.pl' },
proto: { name: 'Protocol Buffers', extension: '.proto' },
pug: { name: 'Pug', extension: '.pug' },
puppet: { name: 'Puppet', extension: '.pp' },
purescript: { name: 'PureScript', extension: '.purs' },
python: { name: 'Python', extension: '.py' },
r: { name: 'R', extension: '.r' },
raku: { name: 'Raku', extension: '.raku' },
razor: { name: 'Razor', extension: '.cshtml' },
reg: { name: 'Registry', extension: '.reg' },
rel: { name: 'Rel', extension: '.rel' },
riscv: { name: 'RISC-V', extension: '.s' },
rst: { name: 'reStructuredText', extension: '.rst' },
ruby: { name: 'Ruby', extension: '.rb' },
rust: { name: 'Rust', extension: '.rs' },
sas: { name: 'SAS', extension: '.sas' },
sass: { name: 'Sass', extension: '.sass' },
scala: { name: 'Scala', extension: '.scala' },
scheme: { name: 'Scheme', extension: '.scm' },
scss: { name: 'SCSS', extension: '.scss' },
shaderlab: { name: 'ShaderLab', extension: '.shader' },
shell: { name: 'Shell', extension: '.sh' },
smalltalk: { name: 'Smalltalk', extension: '.st' },
solidity: { name: 'Solidity', extension: '.sol' },
sparql: { name: 'SPARQL', extension: '.rq' },
sql: { name: 'SQL', extension: '.sql' },
'ssh-config': { name: 'SSH Config', extension: '' },
stata: { name: 'Stata', extension: '.do' },
stylus: { name: 'Stylus', extension: '.styl' },
svelte: { name: 'Svelte', extension: '.svelte' },
swift: { name: 'Swift', extension: '.swift' },
'system-verilog': { name: 'SystemVerilog', extension: '.sv' },
tasl: { name: 'TASL', extension: '.tasl' },
tcl: { name: 'Tcl', extension: '.tcl' },
tex: { name: 'TeX', extension: '.tex' },
toml: { name: 'TOML', extension: '.toml' },
tsx: { name: 'TSX', extension: '.tsx' },
turtle: { name: 'Turtle', extension: '.ttl' },
twig: { name: 'Twig', extension: '.twig' },
typescript: { name: 'TypeScript', extension: '.ts' },
v: { name: 'V', extension: '.v' },
vb: { name: 'VB', extension: '.vb' },
verilog: { name: 'Verilog', extension: '.v' },
vhdl: { name: 'VHDL', extension: '.vhdl' },
viml: { name: 'VimL', extension: '.vim' },
vue: { name: 'Vue', extension: '.vue' },
wasm: { name: 'WebAssembly', extension: '.wasm' },
wenyan: { name: 'Wenyan', extension: '.wy' },
xml: { name: 'XML', extension: '.xml' },
xsl: { name: 'XSL', extension: '.xsl' },
yaml: { name: 'YAML', extension: '.yaml' },
zenscript: { name: 'ZenScript', extension: '.zs' }
plaintext: { name: 'Plain Text', extension: 'txt' },
'1c': { name: '1c', extension: '' },
abnf: { name: 'Augmented Backus-Naur Form', extension: 'abnf' },
accesslog: { name: 'Access Log', extension: 'log' },
actionscript: { name: 'ActionScript', extension: 'as' },
ada: { name: 'Ada', extension: 'ada' },
angelscript: { name: 'AngelScript', extension: 'angelscript' },
apache: { name: 'Apache', extension: 'apache' },
applescript: { name: 'AppleScript', extension: 'applescript' },
arcade: { name: 'Arcade', extension: 'arcade' },
arduino: { name: 'Arduino', extension: 'ino' },
arm: { name: 'ARM Assembly', extension: 's' },
asciidoc: { name: 'AsciiDoc', extension: 'adoc' },
aspectj: { name: 'AspectJ', extension: 'aj' },
autohotkey: { name: 'AutoHotkey', extension: 'ahk' },
autoit: { name: 'AutoIt', extension: 'au3' },
avrasm: { name: 'AVR Assembly', extension: 's' },
awk: { name: 'AWK', extension: 'awk' },
bash: { name: 'Bash', extension: 'sh' },
basic: { name: 'BASIC', extension: 'bas' },
bnf: { name: 'Backus-Naur Form', extension: 'bnf' },
brainfuck: { name: 'Brainfuck', extension: 'bf' },
c: { name: 'C', extension: 'c' },
cpp: { name: 'C++', extension: 'cpp' },
hpp: { name: 'C++ Header', extension: 'h' },
csharp: { name: 'C#', extension: 'cs' },
cal: { name: 'C/AL', extension: '' },
cos: { name: 'Cache Object Script', extension: '' },
capnproto: { name: "Cap'n Proto", extension: 'capnp' },
clojure: { name: 'Clojure', extension: 'clj' },
cmake: { name: 'CMake', extension: 'cmake' },
coffeescript: { name: 'CoffeeScript', extension: 'coffee' },
coq: { name: 'Coq', extension: 'v' },
crmsh: { name: 'CRMsH', extension: '' },
crystal: { name: 'Crystal', extension: 'cr' },
csp: { name: 'CSP', extension: 'csp' },
css: { name: 'CSS', extension: 'css' },
csv: { name: 'CSV', extension: 'csv' },
d: { name: 'D', extension: 'd' },
dart: { name: 'Dart', extension: 'dart' },
deplhi: { name: 'Delphi', extension: 'pas' },
diff: { name: 'Diff', extension: 'diff' },
django: { name: 'Django', extension: 'django' },
dns: { name: 'DNS Zone', extension: 'dns' },
dockerfile: { name: 'Dockerfile', extension: 'dockerfile' },
dos: { name: 'DOS', extension: 'bat' },
bat: { name: 'Batchfile', extension: 'bat' },
dsconfig: { name: 'DSConfig', extension: '' },
dts: { name: 'Device Tree', extension: 'dts' },
dust: { name: 'Dust', extension: 'dust' },
ebnf: { name: 'Extended Backus-Naur Form', extension: 'ebnf' },
elixir: { name: 'Elixir', extension: 'ex' },
elm: { name: 'Elm', extension: 'elm' },
erlang: { name: 'Erlang', extension: 'erl' },
excel: { name: 'Excel', extension: 'xlsx' },
fsharp: { name: 'F#', extension: 'fs' },
fix: { name: 'FIX', extension: 'fix' },
flix: { name: 'Flix', extension: 'flix' },
fortran: { name: 'Fortran', extension: 'f90' },
gcode: { name: 'G-code', extension: 'gcode' },
gams: { name: 'GAMS', extension: 'gms' },
gauss: { name: 'GAUSS', extension: 'gss' },
gherkin: { name: 'Gherkin', extension: '' },
go: { name: 'Go', extension: 'go' },
golo: { name: 'Golo', extension: 'golo' },
gradle: { name: 'Gradle', extension: 'gradle' },
graphql: { name: 'GraphQL', extension: 'graphql' },
groovy: { name: 'Groovy', extension: 'groovy' },
haml: { name: 'HAML', extension: 'haml' },
handlebars: { name: 'Handlebars', extension: 'hbs' },
haskell: { name: 'Haskell', extension: 'hs' },
haxe: { name: 'Haxe', extension: 'hx' },
html: { name: 'HTML', extension: 'html' },
xml: { name: 'XML', extension: 'xml' },
rss: { name: 'RSS', extension: 'rss' },
atom: { name: 'Atom', extension: 'atom' },
svg: { name: 'SVG', extension: 'svg' },
http: { name: 'HTTP', extension: 'http' },
https: { name: 'HTTPS', extension: 'http' },
hy: { name: 'Hy', extension: 'hy' },
inform7: { name: 'Inform 7', extension: 'ni' },
ini: { name: 'INI', extension: 'ini' },
toml: { name: 'TOML', extension: 'toml' },
irpf90: { name: 'IRPF90', extension: 'irpf90' },
java: { name: 'Java', extension: 'java' },
javascript: { name: 'JavaScript', extension: 'js' },
jolie: { name: 'Jolie', extension: 'ol' },
json: { name: 'JSON', extension: 'json' },
json5: { name: 'JSON5', extension: 'json5' },
julia: { name: 'Julia', extension: 'jl' },
'julia-repl': { name: 'Julia REPL', extension: '' },
kotlin: { name: 'Kotlin', extension: 'kt' },
lasso: { name: 'Lasso', extension: 'lasso' },
latex: { name: 'LaTeX', extension: 'tex' },
ldif: { name: 'LDIF', extension: 'ldif' },
leaf: { name: 'Leaf', extension: 'leaf' },
less: { name: 'Less', extension: 'less' },
lisp: { name: 'Lisp', extension: 'lisp' },
livecodeserver: { name: 'LiveCode Server', extension: '' },
livescript: { name: 'LiveScript', extension: 'ls' },
lua: { name: 'Lua', extension: 'lua' },
makefile: { name: 'Makefile', extension: 'makefile' },
markdown: { name: 'Markdown', extension: 'md' },
mathematica: { name: 'Mathematica', extension: 'nb' },
matlab: { name: 'MATLAB', extension: 'm' },
maxima: { name: 'Maxima', extension: 'max' },
mel: { name: 'Maya Embedded Language', extension: 'mel' },
mercury: { name: 'Mercury', extension: 'm' },
mipsasm: { name: 'MIPS Assembly', extension: 's' },
mizar: { name: 'Mizar', extension: 'miz' },
mojolicious: { name: 'Mojolicious', extension: '' },
monkey: { name: 'Monkey', extension: 'monkey' },
moonscript: { name: 'MoonScript', extension: 'moon' },
n1ql: { name: 'N1QL', extension: '' },
nginx: { name: 'Nginx', extension: 'nginx' },
nim: { name: 'Nim', extension: 'nim' },
nix: { name: 'Nix', extension: 'nix' },
nsis: { name: 'NSIS', extension: 'nsi' },
objectivec: { name: 'Objective-C', extension: 'm' },
ocaml: { name: 'OCaml', extension: 'ml' },
glsl: { name: 'OpenGL Shading Language', extension: 'glsl' },
openscad: { name: 'OpenSCAD', extension: 'scad' },
ruleslanguage: { name: 'Oracle Rules Language', extension: '' },
oxygene: { name: 'Oxygene', extension: 'oxygene' },
parser3: { name: 'Parser3', extension: '' },
perl: { name: 'Perl', extension: 'pl' },
pf: { name: 'PF', extension: 'pf' },
php: { name: 'PHP', extension: 'php' },
pony: { name: 'Pony', extension: 'pony' },
postgresql: { name: 'PostgreSQL', extension: 'sql' },
powershell: { name: 'PowerShell', extension: 'ps1' },
processing: { name: 'Processing', extension: 'pde' },
prolog: { name: 'Prolog', extension: 'pl' },
properties: { name: 'Java Properties', extension: 'properties' },
protobuf: { name: 'Protocol Buffers', extension: 'proto' },
puppet: { name: 'Puppet', extension: 'pp' },
python: { name: 'Python', extension: 'py' },
profiler: { name: 'Poython Profiler Results', extension: '' },
'python-repl': { name: 'Python REPL', extension: '' },
q: { name: 'Q', extension: 'q' },
qml: { name: 'QML', extension: 'qml' },
r: { name: 'R', extension: 'r' },
reasonml: { name: 'ReasonML', extension: 're' },
rib: { name: 'RenderMan Interface Bytestream', extension: 'rib' },
rsl: { name: 'RenderMan Shading Language', extension: 'rsl' },
graph: { name: 'Roboconf', extension: '' },
ruby: { name: 'Ruby', extension: 'rb' },
rust: { name: 'Rust', extension: 'rs' },
sas: { name: 'SAS', extension: 'sas' },
scala: { name: 'Scala', extension: 'scala' },
scheme: { name: 'Scheme', extension: 'scm' },
scilab: { name: 'Scilab', extension: 'sci' },
scss: { name: 'SCSS', extension: 'scss' },
shell: { name: 'Shell', extension: 'sh' },
smali: { name: 'Smali', extension: 'smali' },
smalltalk: { name: 'Smalltalk', extension: 'st' },
sml: { name: 'Standard ML', extension: 'sml' },
sql: { name: 'SQL', extension: 'sql' },
stan: { name: 'Stan', extension: 'stan' },
stata: { name: 'Stata', extension: 'do' },
step21: { name: 'STEP Part 21', extension: 'stp' },
stylus: { name: 'Stylus', extension: 'styl' },
subunit: { name: 'SubUnit', extension: 'subunit' },
svelte: { name: 'Svelte', extension: 'svelte' }, // svelte seems to work even though the docs say it requires a plugin
swift: { name: 'Swift', extension: 'swift' },
tcl: { name: 'Tcl', extension: 'tcl' },
tap: { name: 'Test Anything Protocol', extension: 'tap' },
thrift: { name: 'Thrift', extension: 'thrift' },
toit: { name: 'Toit', extension: 'toit' },
tp: { name: 'TP', extension: 'tp' },
twig: { name: 'Twig', extension: 'twig' },
typescript: { name: 'TypeScript', extension: 'ts' },
vala: { name: 'Vala', extension: 'vala' },
vbnet: { name: 'VB.NET', extension: 'vb' },
vba: { name: 'VBA', extension: 'vba' },
vbscript: { name: 'VBScript', extension: 'vbs' },
verilog: { name: 'Verilog', extension: 'v' },
vhdl: { name: 'VHDL', extension: 'vhd' },
vim: { name: 'Vim Script', extension: 'vim' },
axapta: { name: 'X++', extension: 'xpp' },
x86asm: { name: 'x86 Assembly', extension: 's' },
xl: { name: 'XL', extension: 'xl' },
xquery: { name: 'XQuery', extension: 'xq' },
yaml: { name: 'YAML', extension: 'yaml' },
zephir: { name: 'Zephir', extension: 'zep' }
};
export const roles = {
0: 'User',
1: 'Moderator',
255: 'Administrator',
403: 'Banned'
};
export const expiresOptions = [
{ value: 0, label: 'Never Expire' },
{ value: 300000, label: 'Expire in 5 Minutes' },
{ value: 600000, label: 'Expire in 10 Minutes' },
{ value: 1800000, label: 'Expire in 30 Minutes' },
{ value: 3600000, label: 'Expire in 1 Hour' },
{ value: 21600000, label: 'Expire in 6 Hours' },
{ value: 43200000, label: 'Expire in 12 Hours' },
{ value: 86400000, label: 'Expire in 1 Day' },
{ value: 604800000, label: 'Expire in 1 Week' },
{ value: 1209600000, label: 'Expire in 2 Weeks' },
{ value: 2592000000, label: 'Expire in 1 Month' },
{ value: 7776000000, label: 'Expire in 3 Months' },
{ value: 15552000000, label: 'Expire in 6 Months' },
{ value: 31536000000, label: 'Expire in 1 Year' },
{ value: 63072000000, label: 'Expire in 2 Years' },
{ value: 157680000000, label: 'Expire in 5 Years' },
{ value: 315360000000, label: 'Expire in 10 Years' }
];
export const trustedDomains = [
'img.youtube.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,118 @@
<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';
interface Props {
title: PasteEmbedProps['title'];
uploader: PasteEmbedProps['uploader'];
metadata: PasteEmbedProps['metadata'];
previewLines: PasteEmbedProps['previewLines'];
isEncrypted: PasteEmbedProps['isEncrypted'];
}
let { title, uploader, metadata, previewLines, isEncrypted }: Props = $props();
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;
};
+2 -34
View File
@@ -1,38 +1,5 @@
import { writable } from 'svelte/store';
type ModalMode =
| 'decrypt'
| 'encrypt'
| 'confirm'
| 'prompt'
| 'multiselect'
| 'totp'
| 'totpSetup'
| 'report';
type ModalItem = { label: string; value: unknown };
type ModalState = {
show: boolean;
mode: ModalMode;
title: string;
message: string;
error: string;
placeholder: string;
inputType: string;
items: ModalItem[];
initialValue: unknown;
totpActive: boolean | null;
reportTarget: 'user' | 'paste' | null;
reportTargetId: string | number | null;
reportSiteKey: string | null;
confirmButtonText: string;
};
type ModalOpenOptions = Partial<Omit<ModalState, 'show'>> & {
mode: ModalMode;
cancelValue?: unknown;
};
import type { ModalOpenOptions, ModalState } from '$lib/types/modal';
const initialState: ModalState = {
show: false,
@@ -42,6 +9,7 @@ const initialState: ModalState = {
error: '',
placeholder: '',
inputType: 'text',
maxInputLength: undefined,
items: [],
initialValue: null,
totpActive: null,
@@ -0,0 +1,35 @@
import type { Author } from './author';
export type CommentReaction = 1 | 2 | null;
export interface CommentAuthor extends Author {
displayName?: string | null;
roles?: number;
isBanned?: boolean;
}
export interface PasteComment {
id: number;
parentCommentID: number | null;
content: string | null;
storedSize: number;
originalSize: number;
isCompressed: boolean;
createdAt: number;
updatedAt: number | null;
likes: number;
dislikes: number;
userReaction: CommentReaction;
author: CommentAuthor | null;
}
export interface CommentReactionResult {
commentID: number;
likes: number;
dislikes: number;
userReaction: CommentReaction;
}
export interface CommentTreeNode extends PasteComment {
children: CommentTreeNode[];
}
+34
View File
@@ -0,0 +1,34 @@
export type ModalMode =
| 'decrypt'
| 'encrypt'
| 'confirm'
| 'prompt'
| 'multiselect'
| 'totp'
| 'totpSetup'
| 'report';
export type ModalItem = { label: string; value: unknown };
export type ModalState = {
show: boolean;
mode: ModalMode;
title: string;
message: string;
error: string;
placeholder: string;
inputType: string;
maxInputLength?: number;
items: ModalItem[];
initialValue: unknown;
totpActive: boolean | null;
reportTarget: 'user' | 'paste' | null;
reportTargetId: string | number | null;
reportSiteKey: string | null;
confirmButtonText: string;
};
export type ModalOpenOptions = Partial<Omit<ModalState, 'show'>> & {
mode: ModalMode;
cancelValue?: unknown;
};
+8 -2
View File
@@ -1,17 +1,23 @@
import type { Author } from './author';
export type PasteReaction = 1 | 2 | null;
export interface Paste {
id: string;
uuid: string;
createdAt: number;
title: string | null;
size: number;
trueSize: number;
storedSize: number;
originalSize: number;
isCompressed: boolean;
views: number;
syntax: string;
visibility: 0 | 1 | 2;
expiresAt: number;
editedAt: number | null;
likes: number;
dislikes: number;
userReaction: PasteReaction;
reportCount: number | null;
author: Author | null;
}
+3 -10
View File
@@ -24,15 +24,8 @@ export interface ReportListResponse {
pagination: Pagination;
}
export const reportTypeLabels = [
'Spam',
'Abuse',
'InappropriateContent',
'CopyrightViolation',
'Fraud',
'Other'
] as const;
export const reportTypeLabels = ['CopyrightViolation', 'IllegalContent', 'Fraud', 'Other'] as const;
export const reportStatusLabels = ['Open', 'InProgress', 'Resolved', 'Closed'] as const;
export const reportStatusLabels = ['Open', 'Closed'] as const;
export const reportTargetLabels = ['Paste', 'User'] as const;
export const reportTargetLabels = ['Paste', 'User', 'Comment'] as const;
+11 -1
View File
@@ -8,7 +8,8 @@ export interface User {
displayName: string | null;
email: string | null;
lastLogin: number | null;
roles: number[];
roles: number; // bitfield; 5 = User | Admin
isBanned: boolean;
visibility: 0 | 1 | 2;
pastes: Paste[] | null;
pagination: Pagination | null;
@@ -17,3 +18,12 @@ export interface User {
export interface AuthUser extends User {
totpEnabled: boolean;
}
export interface JWTUser {
uuid: string;
username: string;
displayname: string;
totpEnabled: boolean;
roles: number;
isBanned: boolean;
}
+214 -36
View File
@@ -1,43 +1,141 @@
import { browser } from '$app/environment';
import type { Cookies } from '@sveltejs/kit';
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 REFRESH_TOKEN_KEY = 'refreshToken';
const TOKEN_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 180;
const AUTH_TOKENS_UPDATED_EVENT = 'auth:tokens-updated';
const AUTH_TOKENS_CLEARED_EVENT = 'auth:tokens-cleared';
export function getToken() {
let refreshPromise: Promise<void> | null = null;
let lastRefreshAttempt = 0;
let refreshFailureCount = 0;
let refreshIntervalId: ReturnType<typeof setInterval> | null = null;
let listenersRegistered = false;
function getCookieValue(key: string) {
if (!browser) return null;
const entry = document.cookie
.split('; ')
.find((cookieEntry) => cookieEntry.startsWith(`${key}=`));
if (!entry) return null;
const value = entry.slice(key.length + 1);
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function getCookieSecurityAttributes() {
if (!browser) return '';
return window.location.protocol === 'https:' ? '; secure' : '';
}
function emitAuthEvent(eventName: string) {
if (!browser) return;
window.dispatchEvent(new CustomEvent(eventName));
}
function decodeBase64Url(value: string) {
const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
const padding = normalized.length % 4 === 0 ? '' : '='.repeat(4 - (normalized.length % 4));
return atob(normalized + padding);
}
function decodeJwtPayload(token: string): Record<string, unknown> | null {
try {
const [, payload] = token.split('.');
if (!payload) return null;
return JSON.parse(decodeBase64Url(payload));
} catch {
return null;
}
}
function parseBooleanClaim(value: unknown) {
if (typeof value === 'string') return value.toLowerCase() === 'true';
return Boolean(value);
}
function parseNumberClaim(value: unknown): number | null {
const numeric =
typeof value === 'number' ? value : typeof value === 'string' ? parseInt(value, 10) : NaN;
return Number.isFinite(numeric) ? numeric : null;
}
function isPermanentRefreshFailure(status: number, message?: string) {
if (status === 401 || status === 403) return true;
if (!message) return false;
const normalized = message.toLowerCase();
return (
document.cookie
.split('; ')
.find((c) => c.startsWith(`${TOKEN_KEY}=`))
?.split('=')[1] || null
normalized.includes('invalid') ||
normalized.includes('expired') ||
normalized.includes('revoked') ||
normalized.includes('malformed')
);
}
async function queueRefresh(token: string, refreshToken: string) {
if (refreshPromise) {
await refreshPromise;
return;
}
const now = Date.now();
const timeSinceLastAttempt = now - lastRefreshAttempt;
const minDelay = getBackoffDelay(refreshFailureCount);
if (timeSinceLastAttempt < minDelay) return;
refreshPromise = performRefresh(token, refreshToken);
try {
await refreshPromise;
} finally {
refreshPromise = null;
}
}
export function getToken() {
return getCookieValue(TOKEN_KEY);
}
export function getRefreshToken() {
if (!browser) return null;
return (
document.cookie
.split('; ')
.find((c) => c.startsWith(`${REFRESH_TOKEN_KEY}=`))
?.split('=')[1] || null
);
return getCookieValue(REFRESH_TOKEN_KEY);
}
export function setTokens(token: string, refreshToken: string) {
if (!browser) return;
console.log('Setting tokens');
document.cookie = `${TOKEN_KEY}=${token}; path=/; secure; samesite=strict`;
document.cookie = `${REFRESH_TOKEN_KEY}=${refreshToken}; path=/; secure; samesite=strict`;
const secureAttributes = getCookieSecurityAttributes();
document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=${TOKEN_COOKIE_MAX_AGE_SECONDS}; samesite=strict${secureAttributes}`;
document.cookie = `${REFRESH_TOKEN_KEY}=${encodeURIComponent(refreshToken)}; path=/; max-age=${TOKEN_COOKIE_MAX_AGE_SECONDS}; samesite=strict${secureAttributes}`;
refreshFailureCount = 0;
emitAuthEvent(AUTH_TOKENS_UPDATED_EVENT);
}
export function clearTokens() {
if (!browser) return;
console.log('Clearing tokens');
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`;
const secureAttributes = getCookieSecurityAttributes();
document.cookie = `${TOKEN_KEY}=; path=/; max-age=0; samesite=strict${secureAttributes}`;
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; max-age=0; samesite=strict${secureAttributes}`;
user.set(null);
emitAuthEvent(AUTH_TOKENS_CLEARED_EVENT);
}
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() {
@@ -45,37 +143,84 @@ export async function refreshTokenIfNeeded() {
const refreshToken = getRefreshToken();
if (!token || !refreshToken) return;
const payload = JSON.parse(atob(token.split('.')[1]));
const exp = payload.exp * 1000;
const payload = decodeJwtPayload(token);
const expClaim = payload ? parseNumberClaim(payload.exp) : null;
if (expClaim === null) {
await queueRefresh(token, refreshToken);
return;
}
const exp = expClaim * 1000;
const now = Date.now();
if (exp - now < 2 * 60 * 1000) {
console.log('Refreshing token...');
if (exp - now >= 2 * 60 * 1000) return;
await queueRefresh(token, refreshToken);
}
async function performRefresh(token: string, refreshToken: string) {
lastRefreshAttempt = Date.now();
try {
const res = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, refreshToken })
});
if (res.ok) {
const data = await res.json();
if (data.success && data.token?.token && data.token?.refreshToken) {
console.log('Token refreshed successfully');
setTokens(data.token.token, data.token.refreshToken);
} else {
console.log('Invalid tokens received during refresh');
let data: {
success?: boolean;
message?: string;
token?: { token?: string; refreshToken?: string };
} | null = null;
try {
data = await res.json();
} catch {
data = null;
}
if (!res.ok) {
refreshFailureCount++;
if (isPermanentRefreshFailure(res.status, data?.message)) {
clearTokens();
}
} else {
console.log('Failed to refresh token');
clearTokens();
return;
}
if (data?.success && data.token?.token && data.token?.refreshToken) {
setTokens(data.token.token, data.token.refreshToken);
} else {
refreshFailureCount++;
if (isPermanentRefreshFailure(res.status, data?.message)) {
clearTokens();
}
}
} catch {
refreshFailureCount++;
}
console.log('Token is still valid, no refresh needed');
}
export function startTokenRefreshInterval() {
if (!browser) return;
setInterval(refreshTokenIfNeeded, 60 * 1000);
if (refreshIntervalId !== null) return;
refreshIntervalId = setInterval(() => {
void refreshTokenIfNeeded();
}, 60 * 1000);
if (!listenersRegistered) {
window.addEventListener('focus', () => {
void refreshTokenIfNeeded();
});
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
void refreshTokenIfNeeded();
}
});
window.addEventListener('online', () => {
void refreshTokenIfNeeded();
});
listenersRegistered = true;
}
void refreshTokenIfNeeded();
}
export function getServerToken(cookies: Cookies) {
@@ -87,12 +232,19 @@ export function getServerRefreshToken(cookies: Cookies) {
}
export function setServerTokens(cookies: Cookies, token: string, refreshToken: string) {
cookies.set('token', token, { path: '/', httpOnly: true, sameSite: 'strict', secure: true });
cookies.set('token', token, {
path: '/',
httpOnly: true,
sameSite: 'strict',
secure: true,
maxAge: TOKEN_COOKIE_MAX_AGE_SECONDS
});
cookies.set('refreshToken', refreshToken, {
path: '/',
httpOnly: true,
sameSite: 'strict',
secure: true
secure: true,
maxAge: TOKEN_COOKIE_MAX_AGE_SECONDS
});
}
@@ -100,3 +252,29 @@ export function clearServerTokens(cookies: Cookies) {
cookies.delete('token', { path: '/' });
cookies.delete('refreshToken', { path: '/' });
}
export function getUserFromToken(token: string): JWTUser | null {
const payload = decodeJwtPayload(token);
if (!payload) return null;
const uuid = typeof payload.uuid === 'string' ? payload.uuid : null;
const username = typeof payload.username === 'string' ? payload.username : null;
const displayname = typeof payload.displayname === 'string' ? payload.displayname : '';
const rolesClaim = parseNumberClaim(payload.roles);
if (!uuid || !username || rolesClaim === null) return null;
return {
uuid,
username,
displayname,
totpEnabled: parseBooleanClaim(payload.totp_enabled),
roles: rolesClaim,
isBanned: parseBooleanClaim(payload.is_banned)
};
}
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';
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 {
let binary = '';
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) {
binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK_SIZE));
}
return btoa(binary);
}
@@ -20,34 +31,32 @@ function fromBase64(data: string): Uint8Array {
export async function encryptAES(content: string, password: string): Promise<string> {
const enc = new TextEncoder();
const salt = window.crypto.getRandomValues(new Uint8Array(32));
const memorySize = 65536;
const iterations = 3;
const parallelism = 1;
const salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
const keyMaterial = await argon2id({
password,
salt,
iterations,
memorySize,
parallelism,
hashLength: 32,
iterations: ARGON2_ITERATIONS,
memorySize: ARGON2_MEMORY_SIZE,
parallelism: ARGON2_PARALLELISM,
hashLength: ARGON2_HASH_LENGTH,
outputType: 'binary'
});
const key = await window.crypto.subtle.importKey(
'raw',
keyMaterial as unknown as BufferSource,
{ name: 'AES-GCM' },
new Uint8Array(keyMaterial),
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
false,
['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(
{
name: 'AES-GCM',
iv
iv,
additionalData: enc.encode(ENCRYPTION_AAD)
},
key,
enc.encode(content)
@@ -61,9 +70,9 @@ export async function encryptAES(content: string, password: string): Promise<str
return JSON.stringify({
version: 4,
kdf: 'Argon2id',
memorySize,
iterations,
parallelism,
memorySize: ARGON2_MEMORY_SIZE,
iterations: ARGON2_ITERATIONS,
parallelism: ARGON2_PARALLELISM,
algorithm: 'AES-GCM',
saltLength: salt.byteLength,
ivLength: iv.byteLength,
@@ -73,9 +82,9 @@ export async function encryptAES(content: string, password: string): Promise<str
export function estimateEncryptedSize(content: string): number {
const rawSize = new TextEncoder().encode(content).length;
const combinedSize = rawSize + 60;
const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
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> {
@@ -84,8 +93,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
const parsed = JSON.parse(result);
const combined = fromBase64(parsed.data);
const saltLength = parsed.saltLength || 16;
const ivLength = parsed.ivLength || 12;
const saltLength = parsed.saltLength || SALT_LENGTH;
const ivLength = parsed.ivLength || IV_LENGTH;
const salt = combined.slice(0, saltLength);
const iv = combined.slice(saltLength, 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,
memorySize: parsed.memorySize,
parallelism: parsed.parallelism,
hashLength: 32,
hashLength: ARGON2_HASH_LENGTH,
outputType: 'binary'
});
} else {
@@ -118,7 +127,7 @@ export async function decryptAES(result: string, password: string): Promise<stri
hash: parsed.hash
},
baseKey,
{ name: 'AES-GCM', length: 256 },
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
true,
['encrypt', 'decrypt']
);
@@ -127,8 +136,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
const key = await window.crypto.subtle.importKey(
'raw',
keyMaterial as unknown as BufferSource,
{ name: 'AES-GCM' },
new Uint8Array(keyMaterial),
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
false,
['decrypt']
);
@@ -136,7 +145,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
const decryptedContent = await window.crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv
iv,
additionalData: enc.encode(ENCRYPTION_AAD)
},
key,
data
+12
View File
@@ -0,0 +1,12 @@
const htmlEscapeMap: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
'`': '&#96;'
};
export function escapeHtml(value: string): string {
return value.replace(/[&<>"'`]/g, (char) => htmlEscapeMap[char]);
}
+224 -1
View File
@@ -2,6 +2,9 @@ import { marked } from 'marked';
import createDOMPurify from 'dompurify';
import type { WindowLike } from 'dompurify';
import { trustedDomains } from '$lib/consts';
import { escapeHtml } from './html';
export const externalMediaWarningStorageKey = 'sharpbin:ignore-external-media-warning';
const tagMap: Record<string, string> = {
IMG: 'image',
@@ -10,6 +13,18 @@ const tagMap: Record<string, string> = {
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(
md: string,
preventExternal: boolean = true,
@@ -80,6 +95,14 @@ export async function parseMarkdown(
'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'))
button.setAttribute('data-alt', element.getAttribute('alt') || '');
if (element.getAttribute('title'))
@@ -89,9 +112,17 @@ export async function parseMarkdown(
if (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(subWarning);
placeholder.appendChild(button);
placeholder.appendChild(actions);
const parent = element.parentNode;
if (parent && parent.nodeName === 'A') {
@@ -108,3 +139,195 @@ export async function parseMarkdown(
return DOMPurify.sanitize(html);
}
export function parseCommentMarkdown(text: string): string {
const lines = text.replace(/\r\n?/g, '\n').split('\n');
const output: string[] = [];
let index = 0;
while (index < lines.length) {
const codeBlock = tryParseCodeBlock(lines, index);
if (codeBlock) {
output.push(codeBlock.html);
index = codeBlock.nextIndex;
continue;
}
const spoilerBlock = tryParseSpoilerBlock(lines, index);
if (spoilerBlock) {
output.push(spoilerBlock.html);
index = spoilerBlock.nextIndex;
continue;
}
const quoteBlock = tryParseQuoteBlock(lines, index);
if (quoteBlock) {
output.push(quoteBlock.html);
index = quoteBlock.nextIndex;
continue;
}
if (/^\s*---\s*$/.test(lines[index])) {
output.push('<hr class="my-2 border-t border-neutral-700" />');
index += 1;
continue;
}
output.push(parseInlineElements(lines[index]));
index += 1;
}
return output.join('');
}
interface ParsedCommentBlock {
html: string;
nextIndex: number;
}
function tryParseCodeBlock(lines: string[], startIndex: number): ParsedCommentBlock | null {
const firstLine = lines[startIndex];
if (!firstLine.startsWith('```')) return null;
const inlineCloseIndex = firstLine.indexOf('```', 3);
if (inlineCloseIndex > -1) {
const code = firstLine.slice(3, inlineCloseIndex);
const trailing = firstLine.slice(inlineCloseIndex + 3).trim();
const html = renderCodeBlock(code);
if (trailing.length === 0) {
return { html, nextIndex: startIndex + 1 };
}
return {
html: `${html}\n${parseInlineElements(trailing)}`,
nextIndex: startIndex + 1
};
}
const codeLines: string[] = [];
let index = startIndex + 1;
while (index < lines.length && !lines[index].startsWith('```')) {
codeLines.push(lines[index]);
index += 1;
}
if (index < lines.length) index += 1;
return {
html: renderCodeBlock(codeLines.join('\n')),
nextIndex: index
};
}
function tryParseSpoilerBlock(lines: string[], startIndex: number): ParsedCommentBlock | null {
const spoilerOpenMatch = lines[startIndex].match(/^\[Spoiler(?:="([^"]*)")?\](.*)$/i);
if (!spoilerOpenMatch) return null;
const title = spoilerOpenMatch[1]?.trim() || 'Spoiler';
const contentParts: string[] = [];
let remainder = spoilerOpenMatch[2] ?? '';
let index = startIndex;
while (true) {
const closeMatch = /\[\/spoiler\]/i.exec(remainder);
if (closeMatch && closeMatch.index !== undefined) {
const beforeClose = remainder.slice(0, closeMatch.index);
if (beforeClose.length > 0) contentParts.push(beforeClose);
const contentHtml = contentParts.map((line) => parseInlineElements(line)).join('<br />');
let html = `<details class="rounded-sm my-2 bg-neutral-800"><summary class="cursor-pointer px-2 py-1 font-semibold text-neutral-300 hover:text-neutral-200 w-full">${escapeHtml(title)}</summary><div class=" text-neutral-300 bg-neutral-700/40 px-2 p-2 rounded-b-sm">${contentHtml}</div></details>`;
const afterClose = remainder.slice(closeMatch.index + closeMatch[0].length).trim();
if (afterClose.length > 0) {
html += `\n${parseInlineElements(afterClose)}`;
}
return {
html,
nextIndex: index + 1
};
}
if (remainder.length > 0) contentParts.push(remainder);
index += 1;
if (index >= lines.length) return null;
remainder = lines[index];
}
}
function tryParseQuoteBlock(lines: string[], startIndex: number): ParsedCommentBlock | null {
if (!lines[startIndex].startsWith('>')) return null;
const quoteLines: string[] = [];
let index = startIndex;
while (index < lines.length && lines[index].startsWith('>')) {
quoteLines.push(parseInlineElements(lines[index].replace(/^>\s?/, '')));
index += 1;
}
return {
html: `<blockquote class="border-l-4 border-neutral-600 pl-3 my-2 text-neutral-400 italic">${quoteLines.join('<br />')}</blockquote>`,
nextIndex: index
};
}
function renderCodeBlock(code: string): string {
return `<pre class="my-2 overflow-x-auto rounded bg-neutral-900 p-2"><code class="font-mono text-sm text-neutral-100">${escapeHtml(code)}</code></pre>`;
}
function normalizeCommentLink(rawUrl: string): string | null {
const url = rawUrl.trim();
if (url.length === 0) return null;
if (url.startsWith('/')) return url;
try {
const parsed = new URL(url);
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
return parsed.toString();
}
return null;
} catch {
return null;
}
}
function parseInlineElements(text: string): string {
const inlinePattern =
/```([\s\S]*?)```|\*\*\*([^*\n]+)\*\*\*|\*\*([^*\n]+)\*\*|\*([^*\n]+)\*|`([^`\n]+)`|\[([^\]\n]+)\]\(([^)\n]+)\)|@([a-zA-Z0-9_-]+)/g;
let output = '';
let lastIndex = 0;
for (const match of text.matchAll(inlinePattern)) {
const index = match.index ?? 0;
output += escapeHtml(text.slice(lastIndex, index));
if (match[1] !== undefined) {
output += renderCodeBlock(match[1]);
} else if (match[2] !== undefined) {
output += `<strong class="font-bold"><em class="italic">${escapeHtml(match[2])}</em></strong>`;
} else if (match[3] !== undefined) {
output += `<strong class="font-bold">${escapeHtml(match[3])}</strong>`;
} else if (match[4] !== undefined) {
output += `<em class="italic">${escapeHtml(match[4])}</em>`;
} else if (match[5] !== undefined) {
output += `<code class="bg-neutral-800 px-1 py-0.5 rounded text-neutral-100 font-mono text-sm">${escapeHtml(match[5])}</code>`;
} else if (match[6] !== undefined && match[7] !== undefined) {
const safeUrl = normalizeCommentLink(match[7]);
if (safeUrl) {
output += `<a href="${escapeHtml(safeUrl)}" class="text-blue-400 hover:underline" target="_blank" rel="noopener noreferrer">${escapeHtml(match[6])}</a>`;
} else {
output += escapeHtml(match[0]);
}
} else if (match[8] !== undefined) {
const username = match[8];
output += `<a href="/user/${encodeURIComponent(username)}" class="text-blue-400 hover:underline">@${escapeHtml(username)}</a>`;
}
lastIndex = index + match[0].length;
}
output += escapeHtml(text.slice(lastIndex));
return output;
}
+40 -11
View File
@@ -1,5 +1,10 @@
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 {
if (bytes === 0) return '0 Bytes';
@@ -15,6 +20,10 @@ export function formatBytes(bytes: number, decimals = 2): string {
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 {
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 {
const ext = extension.startsWith('.') ? extension.slice(1) : extension;
for (const [key, value] of Object.entries(syntaxes)) {
if (value.extension === `.${ext}`) {
if (value.extension.toLowerCase() === ext.toLowerCase()) {
return key;
}
}
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(
date: Date,
useSuffix = true,
@@ -96,7 +113,7 @@ export function dateToRelativeString(
return `${count} ${unit.name}${count > 1 ? 's' : ''} ${suffix}`.trim();
}
}
return `0 seconds ${suffix}`.trim();
return useSuffix ? 'just now' : '0 seconds';
}
const parts: string[] = [];
let acc = 0;
@@ -109,12 +126,21 @@ export function dateToRelativeString(
acc++;
}
}
if (parts.length === 0) parts.push('0 seconds');
if (parts.length === 0) return useSuffix ? 'just now' : '0 seconds';
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 caretEl: HTMLDivElement | null = null;
let showTimeout: ReturnType<typeof setTimeout>;
@@ -123,8 +149,9 @@ export function tooltip(node: HTMLElement, text: string) {
function createTooltip() {
if (!currentText || currentText.trim() === '') return;
const el = document.createElement('div');
el.className =
'fixed z-50 rounded bg-neutral-800 px-2 py-1 text-sm text-white shadow-lg opacity-0 transition-opacity duration-150';
el.className = `fixed z-50 rounded ${
darker ? 'bg-neutral-900 border border-neutral-800' : 'bg-neutral-800'
} px-2 py-1 text-sm text-white shadow-lg opacity-0 transition-opacity duration-150`;
el.style.maxWidth = '90%';
el.style.wordBreak = 'break-word';
@@ -219,10 +246,10 @@ export function tooltip(node: HTMLElement, text: string) {
caretEl.style.borderLeft = '7px solid transparent';
caretEl.style.borderRight = '7px solid transparent';
if (caretOnTop) {
caretEl.style.borderBottom = '7px solid #27272a';
caretEl.style.borderBottom = `7px solid ${darker ? '#171717' : '#27272a'}`;
caretEl.style.borderTop = '';
} else {
caretEl.style.borderTop = '7px solid #27272a';
caretEl.style.borderTop = `7px solid ${darker ? '#171717' : '#27272a'}`;
caretEl.style.borderBottom = '';
}
}
@@ -260,8 +287,10 @@ export function tooltip(node: HTMLElement, text: string) {
window.addEventListener('resize', mouseOut, true);
return {
update(newText: string) {
currentText = newText ?? '';
update(newParams: string | [string, boolean?]) {
currentText = typeof newParams === 'string' ? newParams : (newParams[0] ?? '');
darker = typeof newParams === 'string' ? false : (newParams[1] ?? false);
if (!currentText || currentText.trim() === '') {
if (tooltipEl) {
tooltipEl.remove();
-7
View File
@@ -9,10 +9,3 @@ export function parseTotpEnabled(tokenValue: string | null) {
return false;
}
}
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number[], nextRoles: number[]) {
if (!totpEnabled) return false;
const nextHasAdmin = nextRoles.includes(255);
const alreadyAdmin = currentRoles.includes(255);
return nextHasAdmin && !alreadyAdmin;
}
@@ -0,0 +1,35 @@
import hljs from 'highlight.js';
import { escapeHtml } from '../utils/html';
type HighlightRequest = {
id: number;
code: string;
lang: string;
};
type HighlightResponse = {
id: number;
html: string;
};
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);
};
+71 -22
View File
@@ -11,7 +11,43 @@
import { page } from '$app/state';
import type { LayoutData } from './$types';
export let data: LayoutData;
interface Props {
data: LayoutData;
children?: import('svelte').Snippet;
}
let { data, children }: Props = $props();
async function syncUserFromToken() {
const token = getToken();
if (!token) {
user.set(null);
return;
}
try {
const res = await fetch('/api/user/me', {
headers: { Authorization: `Bearer ${token}` }
});
if (!res.ok) {
if (res.status === 401 || res.status === 403) {
user.set(null);
}
return;
}
const me = await res.json();
let userData = me;
if (me && 'user' in me && typeof me.user === 'object') {
const { user: nestedUser, ...rest } = me;
userData = { ...rest, ...nestedUser };
}
user.set({ ...userData, totpEnabled: parseTotpEnabled(getToken()) });
} catch {
return;
}
}
if (typeof window !== 'undefined') {
startTokenRefreshInterval();
@@ -20,29 +56,43 @@
};
}
onMount(async () => {
await refreshTokenIfNeeded();
const token = getToken();
if (!token) {
user.set(null);
return;
}
onMount(() => {
const refreshAndSync = async () => {
await refreshTokenIfNeeded();
await syncUserFromToken();
};
const res = await fetch('/api/user/me', {
headers: { Authorization: `Bearer ${token}` }
});
const handleFocus = () => {
void refreshAndSync();
};
if (res.ok) {
const me = await res.json();
let userData = me;
if (me && 'user' in me && typeof me.user === 'object') {
const { user: nestedUser, ...rest } = me;
userData = { ...rest, ...nestedUser };
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
void refreshAndSync();
}
user.set({ ...userData, totpEnabled: parseTotpEnabled(getToken()) });
} else {
};
const handleTokensUpdated = () => {
void syncUserFromToken();
};
const handleTokensCleared = () => {
user.set(null);
}
};
void refreshAndSync();
window.addEventListener('focus', handleFocus);
document.addEventListener('visibilitychange', handleVisibilityChange);
window.addEventListener('auth:tokens-updated', handleTokensUpdated);
window.addEventListener('auth:tokens-cleared', handleTokensCleared);
return () => {
window.removeEventListener('focus', handleFocus);
document.removeEventListener('visibilitychange', handleVisibilityChange);
window.removeEventListener('auth:tokens-updated', handleTokensUpdated);
window.removeEventListener('auth:tokens-cleared', handleTokensCleared);
};
});
</script>
@@ -58,8 +108,7 @@
</svelte:head>
<Navbar {data} />
<!-- <div class="h-15 w-full"></div> -->
<slot />
{@render children?.()}
<Footer />
<ModalHost />
+108 -92
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import type { PageData } from './$types';
import { syntaxes } from '$lib/consts';
import { syntaxes, expiresOptions } from '$lib/consts';
import { user } from '$lib/stores/user';
import { getToken } from '$lib/utils/auth';
import { onMount } from 'svelte';
@@ -18,61 +18,73 @@
import { SvelteURLSearchParams } from 'svelte/reactivity';
import { FileUp, X, Eye, EyeClosed, Dices } from '@lucide/svelte';
export let data: PageData;
interface Props {
data: PageData;
}
let textArea: HTMLTextAreaElement;
let { data }: Props = $props();
let error = '';
let title = '';
let content = '';
let selectedSyntax = data.options?.syntaxes?.[0];
let expiresIn: number = 0;
let selectedVisibility = data.options?.visibilities?.[0]?.value;
let password = '';
let passwordVisible = false;
let anonymousUpload = false;
let isDragging = false;
let dragError = '';
let previewMode = false;
let renderedMarkdown = '';
let textArea = $state<HTMLTextAreaElement | undefined>(undefined);
let markdownConatiner = $state<HTMLDivElement | undefined>(undefined);
$: currentByteSize =
const getInitialSyntax = () => data.options?.syntaxes?.[0] ?? 'plaintext';
const getInitialVisibility = () => data.options?.visibilities?.[0]?.value ?? 0;
let error = $state('');
let title = $state('');
let content = $state('');
let selectedSyntax = $state(getInitialSyntax());
let expiresIn: number = $state(0);
let selectedVisibility = $state(getInitialVisibility());
let password = $state('');
let passwordVisible = $state(false);
let anonymousUpload = $state(false);
let isDragging = $state(false);
let dragError = $state('');
let previewMode = $state(false);
let renderedMarkdown = $state('');
let currentByteSize = $derived(
selectedVisibility === 2
? estimateEncryptedSize(content)
: new TextEncoder().encode(content).length;
: new TextEncoder().encode(content).length
);
$: if (selectedSyntax !== 'markdown') {
previewMode = false;
}
$effect(() => {
if (selectedSyntax !== 'markdown') {
previewMode = false;
}
});
const MAX_HEIGHT = () => Math.floor((window.innerHeight - 120) * 0.6);
let previewHeight = 'auto';
let previewHeight = $state('auto');
async function togglePreview(toPreview: boolean) {
if (toPreview && !previewMode) {
previewHeight = textArea?.style.height || 'auto';
renderedMarkdown = await parseMarkdown(content, false);
}
previewMode = toPreview;
if (!toPreview) {
requestAnimationFrame(resize);
}
requestAnimationFrame(() => resize(previewMode));
}
function resize() {
if (!textArea) return;
function resize(markdown: boolean = false) {
const element = markdown ? markdownConatiner : textArea;
if (!element) return;
textArea.style.height = 'auto';
let h: number;
let max: number;
const h = textArea.scrollHeight;
const max = MAX_HEIGHT();
element.style.height = 'auto';
h = element.scrollHeight;
max = MAX_HEIGHT();
if (h > max) {
textArea.style.height = max + 'px';
textArea.style.overflowY = 'auto';
element.style.height = max + 'px';
element.style.overflowY = 'auto';
} else {
textArea.style.height = h + 'px';
textArea.style.overflowY = 'hidden';
element.style.height = h + 'px';
element.style.overflowY = 'hidden';
}
}
@@ -86,7 +98,9 @@
) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.auth.cf_turnstile_site_key,
theme: 'dark'
theme: 'dark',
size: 'flexible',
appearence: 'interaction-only'
});
}
};
@@ -102,33 +116,21 @@
};
});
const syntaxOptions =
data.options?.syntaxes?.map((lang: string) => ({
value: lang,
label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1)
})) ?? [];
let syntaxOptions = $derived.by(
() =>
data.options?.syntaxes?.map((lang: string) => ({
value: lang,
label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1)
})) ?? []
);
const expiresOptions = [
{ value: 0, label: 'Never Expire' },
{ value: 600000, label: 'Expire in 10 Minutes' },
{ value: 3600000, label: 'Expire in 1 Hour' },
{ value: 86400000, label: 'Expire in 1 Day' },
{ value: 604800000, label: 'Expire in 1 Week' },
{ value: 1209600000, label: 'Expire in 2 Weeks' },
{ value: 2592000000, label: 'Expire in 1 Month' },
{ value: 7776000000, label: 'Expire in 3 Months' },
{ value: 15552000000, label: 'Expire in 6 Months' },
{ value: 31536000000, label: 'Expire in 1 Year' },
{ value: 63072000000, label: 'Expire in 2 Years' },
{ value: 157680000000, label: 'Expire in 5 Years' },
{ value: 315360000000, label: 'Expire in 10 Years' }
];
const visibilityOptions =
data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value,
label: visibility.displayName
})) ?? [];
let visibilityOptions = $derived.by(
() =>
data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value,
label: visibility.displayName
})) ?? []
);
async function handleSubmit(event: Event) {
event.preventDefault();
@@ -144,9 +146,9 @@
data.auth?.cf_turnstile_site_key &&
window.turnstile
) {
const token = window.turnstile.getResponse();
if (token) {
params.append('token', token);
const verificationToken = window.turnstile.getResponse();
if (verificationToken) {
params.append('verificationToken', verificationToken);
}
}
@@ -228,11 +230,27 @@
<svelte:head>
<title>Create a Paste - Sharpbin</title>
<meta
name="description"
content="Create and share code snippets, and text instantly with Sharpbin. Supports syntax highlighting, encryption, expiry, and more."
/>
<meta name="robots" content="index, follow" />
<link rel="canonical" href={data.url.split('/').slice(0, 3).join('/') + '/'} />
<!-- normalized to prevent duplicate content issues -google search console -->
<meta property="og:title" content="Create a Paste - Sharpbin" />
<meta property="og:description" content="Create and share your pastes easily with Sharpbin." />
<meta
property="og:description"
content="Create and share code snippets, and text instantly with Sharpbin. Supports syntax highlighting, encryption, expiry, and more."
/>
<meta property="og:type" content="website" />
<meta property="og:url" content={data.url} />
<meta property="og:site_name" content="Sharpbin" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Create a Paste - Sharpbin" />
<meta
name="twitter:description"
content="Create and share code snippets, and text instantly with Sharpbin."
/>
</svelte:head>
<main
@@ -240,11 +258,11 @@
>
<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">Create a Paste</h1>
<form class="mt-4" on:submit|preventDefault={handleSubmit}>
<form class="mt-4" onsubmit={handleSubmit}>
<input
type="text"
placeholder="Title (optional)"
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
class="mb-2 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
spellcheck="false"
autocomplete="off"
bind:value={title}
@@ -256,7 +274,9 @@
<div
class="markdown min-h-20 w-full overflow-y-auto rounded rounded-b-none border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200"
style="height: {previewHeight}"
bind:this={markdownConatiner}
>
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html renderedMarkdown}
</div>
{:else}
@@ -268,10 +288,10 @@
minlength="1"
bind:this={textArea}
bind:value={content}
on:input={resize}
on:change={resize}
on:focus={resize}
on:beforeinput={(e) => {
oninput={() => resize()}
onchange={() => resize()}
onfocus={() => resize()}
onbeforeinput={(e) => {
if (!data.options?.maxPasteSize) return;
const futureSize =
@@ -286,20 +306,20 @@
e.preventDefault();
}
}}
on:dragenter={(e) => {
ondragenter={(e) => {
e.preventDefault();
isDragging = true;
}}
on:dragover={(e) => {
ondragover={(e) => {
e.preventDefault();
isDragging = true;
}}
on:dragleave={(e) => {
ondragleave={(e) => {
e.preventDefault();
isDragging = false;
}}
on:drop={(e) => {
requestAnimationFrame(resize);
ondrop={(e) => {
requestAnimationFrame(() => resize());
e.preventDefault();
isDragging = false;
@@ -363,14 +383,14 @@
<div class="mt-1 flex">
{#if selectedSyntax === 'markdown'}
<div
class="monospace mb-2 flex h-12 w-36 items-center justify-between gap-1 rounded-bl border border-neutral-700 bg-neutral-800 p-1 text-sm text-neutral-400 md:h-8"
class="monospace mb-2 flex min-h-full w-36 items-center justify-between gap-1 rounded-bl border border-neutral-700 bg-neutral-800 p-1 text-sm text-neutral-400 md:h-8"
>
<button
type="button"
class="h-full w-1/2 rounded-l transition-colors {previewMode
? 'hover:bg-neutral-700'
: 'bg-neutral-700 text-white'}"
on:click={() => togglePreview(false)}
onclick={() => togglePreview(false)}
>
Code
</button>
@@ -379,17 +399,17 @@
class="h-full w-1/2 rounded-r transition-colors {!previewMode
? 'hover:bg-neutral-700'
: 'bg-neutral-700 text-white'}"
on:click={() => togglePreview(true)}
onclick={() => togglePreview(true)}
>
Preview
</button>
</div>
{/if}
<div
class="monospace mb-2 flex h-12 items-center justify-between {selectedSyntax ===
class="monospace mb-2 flex h-fit min-h-12 items-center justify-between {selectedSyntax ===
'markdown'
? 'ml-auto w-[calc(100%-150px)] rounded-br'
: 'w-full rounded-b'} border border-neutral-700 bg-neutral-800 p-1 pr-2 pl-2 text-sm text-neutral-400 md:h-8"
: 'w-full rounded-b'} border border-neutral-700 bg-neutral-800 p-1 pr-2 pl-2 text-sm text-neutral-400 md:h-8 md:min-h-8"
>
<div class="flex flex-col md:flex-row md:gap-2">
<span>
@@ -430,7 +450,7 @@
/>
</div>
{#if selectedVisibility === 2}
<div class="flex w-full mb-2">
<div class="mb-2 flex w-full">
<input
type={passwordVisible ? 'text' : 'password'}
placeholder="Password for private paste"
@@ -443,20 +463,20 @@
<button
type="button"
class="mr-1 ml-1 flex w-12.5 items-center justify-center border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
on:click={() => {
onclick={() => {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
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" />
</button>
<button
type="button"
class="flex w-12.5 items-center justify-center rounded-r border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
on:click={() => (passwordVisible = !passwordVisible)}
onclick={() => (passwordVisible = !passwordVisible)}
>
{#if passwordVisible}
<EyeClosed class="h-5 w-5" />
@@ -479,15 +499,11 @@
</label>
{/if}
{#if data.options?.requiresVerification && data.auth?.cf_turnstile_site_key}
<div
class="mb-2 flex min-h-16.25 w-auto items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 pb-1"
>
<div class="cf-turnstile" data-sitekey={data.auth.cf_turnstile_site_key}></div>
</div>
<div class="cf-turnstile mb-1 w-full" data-sitekey={data.auth.cf_turnstile_site_key}></div>
{/if}
<button
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"
>Create Paste</button
>
@@ -499,7 +515,7 @@
{error}
</div>
{/if}
{#if $user?.roles && $user.roles.includes(403)}
{#if $user?.isBanned}
<div
transition:fly={{ y: 40, duration: 300 }}
class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
@@ -0,0 +1,7 @@
import { error, redirect } from '@sveltejs/kit';
export async function GET({ params }) {
const username = params?.username;
if (!username) throw error(404, 'User not found');
throw redirect(302, `/user/${encodeURIComponent(username)}`);
}
@@ -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.originalSize) },
{
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,34 @@
import type { PageServerLoad } from './$types';
import type { Paste } from '$lib/types/paste';
import type { PasteComment } from '$lib/types/comment';
import { getServerToken } from '$lib/utils/auth';
import { env } from '$env/dynamic/private';
import { apiUrl, viewInternalApiKey } from '$lib/server/api';
import { error } from '@sveltejs/kit';
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
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 }) => {
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent, request }) => {
const { id } = params;
if (!id) {
// realistically this shouldnt happen
throw error(400, 'Missing paste id.');
}
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: {
Authorization: token ? `Bearer ${token}` : ''
}
});
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, { headers: clientHeaders });
if (pasteRes.status === 404) {
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`, {
method: 'POST',
headers: {
'X-Internal-API-Key': apiKey,
Authorization: token ? `Bearer ${token}` : ''
}
headers: viewedHeaders
});
const pasteData = await pasteRes.json();
@@ -39,28 +36,33 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent
if (viewed.status === 200) {
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;
}
} else {
} else if (viewInternalApiKey === '') {
console.error(
`Failed to increment view count for paste ${id}, status code ${viewed.status}: ${await viewed.text()}`
'The API key for internal requests is not set. Please configure it in the environment variables.'
);
if (apiKey === '') {
console.error(
'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 pasteOptions = await fetch('/api/paste/info');
const pasteContent = await fetch(`${apiUrl}/api/paste/${id}/raw`, { headers: clientHeaders });
const pasteOptions = await fetch(`${apiUrl}/api/paste/info`, { headers: clientHeaders });
const commentsRes = await fetch(`${apiUrl}/api/paste/${id}/comments`, { headers: clientHeaders });
const options = await pasteOptions.json();
const content = await pasteContent.text();
let comments: PasteComment[] = [];
if (commentsRes.ok) {
const commentsJson = await commentsRes.json().catch(() => ({}));
comments = Array.isArray(commentsJson?.comments)
? (commentsJson.comments as PasteComment[])
: [];
}
return {
paste,
content,
comments,
options,
authOptions:
parentData && typeof parentData === 'object' && parentData !== null && 'options' in parentData
+442 -141
View File
@@ -1,12 +1,14 @@
<script lang="ts">
import hljs from 'highlight.js';
import Papa from 'papaparse';
import { onMount } from 'svelte';
import type { PageData } from './$types';
import {
File,
FileBox,
Eye,
EyeClosed,
Globe,
Lock,
EyeOff,
User,
CalendarDays,
@@ -21,7 +23,11 @@
Check,
CalendarCog,
Flag,
ArrowUp
ArrowUp,
HatGlasses,
MessageCircle,
ThumbsUp,
ThumbsDown
} from '@lucide/svelte/icons/index';
import {
formatBytes,
@@ -31,40 +37,78 @@
tooltip,
isBinaryData
} from '$lib/utils/misc';
import { parseMarkdown } from '$lib/utils/markdown';
import { syntaxes } from '$lib/consts';
import {
getIgnoreExternalMediaWarning,
parseMarkdown,
setIgnoreExternalMediaWarning
} from '$lib/utils/markdown';
import { syntaxes, expiresOptions } from '$lib/consts';
import { resolve } from '$app/paths';
import { decryptAES, encryptAES } from '$lib/utils/encryption';
import { escapeHtml } from '$lib/utils/html';
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 Dropdown from '$lib/components/Dropdown.svelte';
import PasteComments from '$lib/components/PasteComments.svelte';
import { openModal } from '$lib/stores/modal';
import type { Paste } from '$lib/types/paste';
export let data: PageData;
import type { Paste, PasteReaction } from '$lib/types/paste';
import HighlightWorker from '$lib/workers/highlight.worker?worker';
interface Props {
data: PageData;
}
let reportSiteKey: string | null = null;
let editing = false;
let editContent: string | null = null;
let editMetadata: Paste | null = data.paste ? { ...data.paste } : null;
let editError = '';
let editLoading = false;
let isBinary = false;
let pasteContent = '';
let decryptedContent: string | null = null;
let { data = $bindable() }: Props = $props();
function updatePasteState(patch: Partial<Paste>) {
if (!data?.paste) return;
data = {
...data,
paste: {
...data.paste,
...patch
}
};
}
function updatePageContent(content: string) {
data = {
...data,
content
};
}
let reportSiteKey = $derived(
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null
);
let editing = $state(false);
let editContent: string | null = $state(null);
let editMetadata: Paste | null = $state(data.paste ? { ...data.paste } : null);
let editError = $state('');
let editLoading = $state(false);
let isBinary = $state(false);
let pasteContent = $state('');
let decryptedContent: string | null = $state(null);
let decryptError = '';
let decryptStatus = '';
let contentRendered = false;
let downloadedPaste = false;
let copiedPaste = false;
let decryptStatus = $state('');
let contentRendered = $state(false);
let downloadedPaste = $state(false);
let copiedPaste = $state(false);
let reactingToPaste = $state(false);
let highlightWorker: Worker | null = null;
let highlightRequestId = 0;
let ignoreExternalMediaWarning = false;
let iconsOnly = $state(false);
let scrollY = 0;
let scrollY = $state(0);
let now = new Date();
$: isExpired =
let now = $state(new Date());
let isExpired = $derived(
data?.paste?.expiresAt && data.paste.expiresAt !== 0
? new Date(data.paste.expiresAt).getTime() <= now.getTime()
: false;
: false
);
let interval: ReturnType<typeof setInterval> | null = null;
@@ -73,21 +117,7 @@
value: lang,
label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1)
})) ?? [];
const expiresOptions = [
{ value: 0, label: 'Never Expire' },
{ value: 600000, label: 'Expire in 10 Minutes' },
{ value: 3600000, label: 'Expire in 1 Hour' },
{ value: 86400000, label: 'Expire in 1 Day' },
{ value: 604800000, label: 'Expire in 1 Week' },
{ value: 1209600000, label: 'Expire in 2 Weeks' },
{ value: 2592000000, label: 'Expire in 1 Month' },
{ value: 7776000000, label: 'Expire in 3 Months' },
{ value: 15552000000, label: 'Expire in 6 Months' },
{ value: 31536000000, label: 'Expire in 1 Year' },
{ value: 63072000000, label: 'Expire in 2 Years' },
{ value: 157680000000, label: 'Expire in 5 Years' },
{ value: 315360000000, label: 'Expire in 10 Years' }
];
const visibilityOptions =
data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value,
@@ -102,10 +132,12 @@
};
onMount(() => {
highlightWorker = new HighlightWorker();
interval = setInterval(() => {
now = new Date();
}, 1000);
return () => {
if (highlightWorker) highlightWorker.terminate();
if (interval) clearInterval(interval);
};
});
@@ -119,52 +151,73 @@
const numbered = lines
.map(
(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('');
return html.replace(code, numbered);
}
async function renderCode(content: string | null = null) {
async function renderPaste(content: string | null = null) {
if (!data?.paste) return;
let code = content ?? decryptedContent ?? data.content ?? '';
const encoder = new TextEncoder();
const buffer = encoder.encode(code).buffer;
isBinary = isBinaryData(buffer);
let contentToRender = content ?? decryptedContent ?? data.content ?? '';
isBinary = isBinaryData(new TextEncoder().encode(contentToRender).buffer);
if (isBinary) {
contentRendered = true;
decryptStatus = '';
return;
}
switch (data.paste.syntax) {
case 'markdown':
pasteContent = await parseMarkdown(contentToRender, !ignoreExternalMediaWarning);
contentRendered = true;
decryptStatus = '';
break;
case 'csv':
await renderCsv(contentToRender);
break;
default:
await renderCode(contentToRender);
break;
}
}
async function renderCode(content: string | null = null) {
if (!data?.paste) return;
let code = content ?? decryptedContent ?? data.content ?? '';
const lang = (data.paste.syntax ?? '').toLowerCase();
if (lang === 'markdown') {
pasteContent = await parseMarkdown(code);
contentRendered = true;
decryptStatus = '';
return;
}
let highlighted = '';
try {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
} else {
highlighted = hljs.highlightAuto(code).value;
}
} catch {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else {
highlighted = hljs.highlightAuto(code).value;
const worker = highlightWorker;
if (worker) {
const requestId = ++highlightRequestId;
highlighted = await new Promise((resolve) => {
const handler = (event: MessageEvent<{ id: number; html: string }>) => {
if (event.data.id !== requestId) return;
worker.removeEventListener('message', handler);
resolve(event.data.html);
};
worker.addEventListener('message', handler);
worker.postMessage({ id: requestId, code, lang });
});
} else {
try {
if (lang === 'plaintext') {
highlighted = escapeHtml(code);
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
} else {
highlighted = hljs.highlightAuto(code).value;
}
} catch {
if (lang === 'plaintext') {
highlighted = escapeHtml(code);
} else {
highlighted = hljs.highlightAuto(code).value;
}
}
}
const wrapped = `<pre><code class="hljs">${highlighted}</code></pre>`;
@@ -173,6 +226,51 @@
decryptStatus = '';
}
async function renderCsv(content: string) {
try {
const results = Papa.parse(content, {
header: false,
skipEmptyLines: true,
dynamicTyping: false
});
if (!results.data || results.data.length === 0) {
pasteContent = '<div class="p-4 text-neutral-400">No data in CSV</div>';
contentRendered = true;
decryptStatus = '';
return;
}
const rows = results.data as string[][];
const [header, ...body] = rows;
const tableHtml = `
<table class="csv-table">
<thead>
<tr>
${header.map((c) => `<th>${c ? escapeHtml(c) : ''}</th>`).join('')}
</tr>
</thead>
<tbody>
${body
.map(
(row) => `<tr>${row.map((c) => `<td>${c ? escapeHtml(c) : ''}</td>`).join('')}</tr>`
)
.join('')}
</tbody>
</table>
`;
pasteContent = tableHtml;
contentRendered = true;
decryptStatus = '';
} catch {
pasteContent = '<div class="p-4 text-red-400">Failed to parse CSV</div>';
contentRendered = true;
decryptStatus = '';
}
}
async function updatePaste(content: string | null, metadata: Paste | null) {
editError = '';
editLoading = true;
@@ -219,9 +317,9 @@
editLoading = false;
return;
}
data.content = rawContent;
updatePageContent(rawContent);
decryptedContent = rawContent;
await renderCode(rawContent);
await renderPaste(rawContent);
}
if (
(metadata?.syntax !== data.paste.syntax ||
@@ -250,10 +348,13 @@
return;
}
const resJson = await res.json();
data.paste.syntax = resJson.paste.syntax ?? data.paste.syntax;
data.paste.expiresAt = resJson.paste.expiresAt ?? data.paste.expiresAt;
data.paste.visibility = resJson.paste.visibility ?? data.paste.visibility;
data.paste.title = resJson.paste.title ?? data.paste.title;
updatePasteState({
syntax: resJson.paste.syntax ?? data.paste.syntax,
expiresAt: resJson.paste.expiresAt ?? data.paste.expiresAt,
visibility: resJson.paste.visibility ?? data.paste.visibility,
title: resJson.paste.title ?? data.paste.title
});
editMetadata = data.paste ? { ...data.paste } : null;
}
} catch {
editError = 'An error occurred while updating.';
@@ -264,6 +365,48 @@
}
}
async function reactToPaste(target: 1 | 2) {
if (!data?.paste || reactingToPaste || $user?.uuid === data.paste.author?.uuid) return;
const token = getToken();
if (!token) {
return;
}
reactingToPaste = true;
const currentReaction = (data.paste.userReaction ?? null) as PasteReaction;
const nextReaction: PasteReaction = currentReaction === target ? null : target;
try {
const res = await fetch(`/api/paste/${data.paste.id}/reaction`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ reaction: nextReaction })
});
if (!res.ok) {
return;
}
const json = await res.json();
const reaction = json?.reaction;
if (!reaction) {
return;
}
updatePasteState({
likes: reaction.likes ?? data.paste.likes,
dislikes: reaction.dislikes ?? data.paste.dislikes,
userReaction: reaction.userReaction ?? null
});
} finally {
reactingToPaste = false;
}
}
async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' | 'report' = 'decrypt') {
const title = modalTitleMap[mode];
if (mode === 'confirm') {
@@ -293,6 +436,13 @@
event.preventDefault();
event.stopPropagation();
if (target.classList.contains('ignore-media-warning-btn')) {
ignoreExternalMediaWarning = true;
setIgnoreExternalMediaWarning(true);
renderPaste();
return;
}
if (target.classList.contains('load-media-btn')) {
const src = target.getAttribute('data-src');
const tag = target.getAttribute('data-tag');
@@ -358,6 +508,8 @@
onMount(async () => {
try {
ignoreExternalMediaWarning = getIgnoreExternalMediaWarning();
if (data?.paste && data.paste.visibility === 2) {
contentRendered = false;
decryptStatus = 'Preparing decryption...';
@@ -376,14 +528,14 @@
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
} else {
await renderCode();
await renderPaste();
history.replaceState(null, '', window.location.pathname + window.location.search);
}
} else {
decryptStatus = 'Decryption canceled.';
}
} else {
await renderCode();
await renderPaste();
}
return;
}
@@ -396,25 +548,27 @@
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
} else {
await renderCode();
await renderPaste();
}
} else {
decryptStatus = 'Decryption canceled.';
}
} else {
decryptStatus = 'Rendering content...';
await renderCode();
await renderPaste();
}
} catch {
decryptStatus = 'Rendering content...';
await renderCode();
await renderPaste();
}
});
$: if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderCode();
$: reportSiteKey =
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null;
$effect(() => {
if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderPaste();
});
let pasteImageUrl = $derived(
data?.paste && data?.url ? `${new URL(data.url).origin}/${data.paste.id}.jpg` : null
);
</script>
<svelte:window bind:scrollY />
@@ -426,18 +580,37 @@
: 'Paste Not Found - Sharpbin'}</title
>
{#if data.paste}
<meta property="og:title" content={data.paste.title || 'Untitled Paste'} />
{@const pasteDescription = `A ${syntaxes[data.paste.syntax].name} paste on Sharpbin created by ${
data.paste.author ? data.paste.author.username : 'an anonymous user'
}, created on ${
extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'
} with ${data.paste.views} view${data.paste.views !== 1 ? 's' : ''}.`}
<meta name="description" content={pasteDescription} />
<meta
property="og:description"
content={`A ${data.paste.syntax} paste on Sharpbin created by ${
data.paste.author ? data.paste.author.username : 'Anonymous'
}, created on ${
extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'
} with ${data.paste.views} view${data.paste.views !== 1 ? 's' : ''}.`}
name="robots"
content={data.paste.visibility === 0 ? 'index, follow' : 'noindex, nofollow'}
/>
<link rel="canonical" href={data.url} />
{#if data.paste.author}
<meta name="author" content={data.paste.author.username} />
{/if}
<meta property="og:title" content={data.paste.title || 'Untitled Paste'} />
<meta property="og:description" content={pasteDescription} />
<meta property="og:type" content="article" />
<meta property="og:url" content={data.url} />
<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} />
{:else}
<meta name="twitter:card" content="summary" />
{/if}
<meta name="twitter:title" content={data.paste.title || 'Untitled Paste'} />
<meta name="twitter:description" content={pasteDescription} />
<meta
property="og:article:published_time"
content={extractDateFromUUIDv7(data.paste.uuid)?.toISOString() ?? ''}
@@ -461,8 +634,7 @@
{#if data.paste}
<div class="mb-4 w-full text-center">
<h1
class="mx-auto max-w-[90%] min-w-0 truncate text-3xl leading-tight font-bold sm:text-4xl"
use:tooltip={data.paste.title && data.paste.title.length > 40 ? data.paste.title : ''}
class="mx-auto max-w-[90%] min-w-0 text-3xl leading-tight font-bold wrap-break-word sm:text-4xl"
>
{#if !editing}
{data.paste.title || 'Untitled Paste'}
@@ -477,14 +649,15 @@
{/if}
</h1>
<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}
<User class="inline-block h-4 w-4 text-neutral-400" />
<a
href={resolve(`/user/${data.paste.author.username}`)}
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
>{data.paste.author.username}</a
>
{:else}
<HatGlasses class="inline-block h-4 w-4 text-neutral-400" />
<span class="text-neutral-400">Anonymous</span>
{/if}
</div>
@@ -494,12 +667,18 @@
<div class="relative flex shrink-0 items-center">
<div
class="flex"
use:tooltip={data.paste.isCompressed
? `Compressed Size: ${formatBytes(data.paste.size)}`
: `This paste is not compressed.`}
use:tooltip={`${
data.paste.isCompressed
? `Compressed Size: ${formatBytes(data.paste.storedSize)}`
: ''
}${
data.paste.visibility === 2
? ` • Decrypted Size: ${formatBytes(decryptedContent ? new TextEncoder().encode(decryptedContent).length : 0)}`
: ''
}`}
>
<FileBox class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{formatBytes(data.paste.trueSize)}</span>
<span class="text-neutral-400">{formatBytes(data.paste.originalSize)}</span>
</div>
</div>
@@ -594,13 +773,13 @@
<div>
<div class="flex shrink-0 items-center">
{#if data.paste.visibility === 0}
<Eye class="mr-2 h-6 w-6 text-neutral-400" />
<Globe class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{editing ? '' : 'Public'}</span>
{:else if data.paste.visibility === 1}
<EyeClosed class="mr-2 h-6 w-6 text-neutral-400" />
<EyeOff class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{editing ? '' : 'Unlisted'}</span>
{:else if data.paste.visibility === 2}
<EyeOff class="mr-2 h-6 w-6 text-neutral-400" />
<Lock class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{editing ? '' : 'Private'}</span>
{/if}
{#if editing && editMetadata}
@@ -616,7 +795,7 @@
</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}
<div class="flex items-center gap-2 text-sm text-neutral-300">
@@ -637,6 +816,33 @@
? 's'
: ''}</span
>
<button
type="button"
class="ml-4 rounded border px-2 py-0.5 text-sm transition-colors disabled:opacity-60 disabled:cursor-not-allowed! {data
.paste.userReaction === 1
? 'border-green-700 bg-green-900 text-green-200'
: 'border-neutral-700 bg-neutral-700 text-neutral-300 hover:bg-neutral-600'}"
onclick={() => reactToPaste(1)}
disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
aria-disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
>
<ThumbsUp class="mr-1 inline-block h-4 w-4 text-green-400" />
<span>{formatNumber(data.paste.likes)}</span>
</button>
<button
type="button"
class="rounded border px-2 py-0.5 text-sm transition-colors disabled:opacity-60 disabled:cursor-not-allowed! {data
.paste.userReaction === 2
? 'border-red-700 bg-red-900 text-red-200'
: 'border-neutral-700 bg-neutral-700 text-neutral-300 hover:bg-neutral-600'}"
onclick={() => reactToPaste(2)}
disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
aria-disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
>
<ThumbsDown class="mr-1 inline-block h-4 w-4 text-red-400" />
<span>{formatNumber(data.paste.dislikes)}</span>
</button>
</div>
{:else}
<div></div>
@@ -646,13 +852,13 @@
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => {
onclick={() => {
navigator.clipboard.writeText(decryptedContent ?? data.content);
copiedPaste = true;
setTimeout(() => (copiedPaste = false), 1000);
}}
>
<div class="relative mr-1 h-5 w-5">
<div class="relative {iconsOnly ? '' : 'mr-1'} h-5 w-5">
{#if copiedPaste}
<span
transition:fade={{ duration: 200 }}
@@ -667,14 +873,15 @@
>
{/if}
</div>
<span class="text-neutral-300">Copy</span>
{#if !iconsOnly}
<span class="text-neutral-300">Copy</span>
{/if}
</button>
{/if}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => {
onclick={() => {
const blob = new Blob([decryptedContent ?? data.content], {
type: 'text/plain'
});
@@ -694,8 +901,8 @@
const a = document.createElement('a');
a.href = url;
a.download = data.paste?.title
? data.paste.title.slice(0, 100) + extension
: `paste_${data.paste?.id}${extension}`;
? `${data.paste.title.slice(0, 100)}.${extension}`
: `paste_${data.paste?.id}.${extension}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
@@ -704,7 +911,7 @@
setTimeout(() => (downloadedPaste = false), 1000);
}}
>
<div class="relative mr-1 h-5 w-5">
<div class="relative {iconsOnly ? '' : 'mr-1'} h-5 w-5">
{#if downloadedPaste}
<span
transition:fade={{ duration: 200 }}
@@ -719,50 +926,73 @@
>
{/if}
</div>
<span class="text-neutral-300">Download</span>
{#if !iconsOnly}
<span class="text-neutral-300">Download</span>
{/if}
</button>
<a
href={resolve(`/raw/${data.paste.id}`)}
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
>
<File class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">View Raw</span>
<File class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
{#if !iconsOnly}
<span class="text-neutral-300">View Raw</span>
{/if}
</a>
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
onclick={() => {
document.getElementById('comments-section')?.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}}
>
<MessageCircle class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
{#if !iconsOnly}
<span class="text-neutral-300">Comments</span>
{/if}
</button>
{#if $user !== null && $user.uuid !== data.paste?.author?.uuid}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-amber-600/50"
on:click={() => {
onclick={() => {
promptUser('report');
}}
>
<Flag class="mr-1 h-5 w-5 text-amber-400" />
<span class="text-amber-300">Report</span>
<Flag class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-amber-400" />
{#if !iconsOnly}
<span class="text-amber-300">Report</span>
{/if}
</button>
{/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 !isBinary}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => {
onclick={() => {
editContent = decryptedContent ?? data.content;
editError = '';
editing = true;
}}
>
<Pencil class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">Edit</span>
<Pencil class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
{#if !iconsOnly}
<span class="text-neutral-300">Edit</span>
{/if}
</button>
{/if}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-red-900"
on:click={() => {
onclick={() => {
promptUser('confirm').then(async (value) => {
if (value) {
const token = getToken();
@@ -784,33 +1014,39 @@
});
}}
>
<Trash2 class="mr-1 h-5 w-5 text-red-400" />
<span class="text-red-300">Delete</span>
<Trash2 class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-red-400" />
{#if !iconsOnly}
<span class="text-red-300">Delete</span>
{/if}
</button>
{:else}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={async () => {
onclick={async () => {
if (editContent !== null || editMetadata !== null) {
await updatePaste(editContent, editMetadata);
}
}}
disabled={editLoading}
>
<PencilLine class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">{editLoading ? 'Saving...' : 'Save Edits'}</span>
<PencilLine class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
{#if !iconsOnly || editLoading}
<span class="text-neutral-300">{editLoading ? 'Saving...' : 'Save Edits'}</span>
{/if}
</button>
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => {
onclick={() => {
editing = false;
editError = '';
}}
>
<PencilOff class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">Cancel Edit</span>
<PencilOff class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
{#if !iconsOnly}
<span class="text-neutral-300">Cancel Edit</span>
{/if}
</button>
{/if}
{/if}
@@ -818,11 +1054,13 @@
<button
transition:fade={{ duration: 200 }}
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
onclick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
aria-label="Scroll to top"
>
<ArrowUp class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">Scroll to top</span>
<ArrowUp class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
{#if !iconsOnly}
<span class="text-neutral-300">Scroll to top</span>
{/if}
</button>
{/if}
</div>
@@ -855,15 +1093,19 @@
<div
class={data.paste.syntax === 'markdown'
? 'markdown rounded-b-md bg-neutral-800 p-4'
: 'codeblock-with-lines overflow-x-auto overflow-y-auto'}
: data.paste.syntax === 'csv'
? 'csv-container scrollbar overflow-x-auto overflow-y-auto scrollbar-thumb-neutral-600 scrollbar-track-neutral-800'
: 'codeblock-with-lines overflow-x-auto overflow-y-auto'}
class:hidden={!contentRendered}
on:click={handleMarkdownClick}
onclick={handleMarkdownClick}
role="presentation"
>
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html pasteContent}
</div>
{/if}
<PasteComments pasteId={data.paste.id} initialComments={data.comments ?? []} />
{:else}
<h1 class="mb-4 text-center text-4xl font-bold">Paste not found</h1>
<h2 class="mt-2 text-center text-xl">The paste you are looking for does not exist.</h2>
@@ -873,6 +1115,7 @@
<style>
.hljs {
background-color: var(--color-neutral-800) !important;
padding: 0 !important;
}
.codeblock-with-lines {
@@ -900,30 +1143,88 @@
display: flex;
align-items: flex-start;
min-width: 0;
padding: 0.1em 0;
border-radius: 0.15em;
padding: 0;
}
.code-row:hover {
background-color: rgba(255, 255, 255, 0.05);
}
.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;
color: #888;
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;
padding-top: 0.1em;
padding-bottom: 0.1em;
padding-right: 0.5em;
padding-left: 0.25em;
padding-left: 0.9em;
background: none;
border-right: 1px solid var(--color-neutral-700);
}
.code-line {
display: block;
white-space: pre-wrap;
word-break: break-word;
overflow-wrap: anywhere;
padding-left: 0.25em;
padding-top: 0.1em;
padding-bottom: 0.1em;
padding-left: 0.9em;
min-width: 0;
}
.csv-table {
border-collapse: separate;
border-spacing: 0;
background-color: var(--color-neutral-800);
border-bottom-left-radius: 0.25rem;
border-bottom-right-radius: 0.25rem;
min-width: 100%;
}
.csv-table thead th {
position: sticky;
top: 0;
background-color: var(--color-neutral-800);
border-bottom: 2px solid var(--color-neutral-700);
z-index: 2;
}
.csv-table tbody tr,
.csv-table thead th {
border-bottom: 1px solid var(--color-neutral-700);
}
.csv-table tbody tr:hover,
.csv-table thead tr:hover {
background-color: rgba(255, 255, 255, 0.05);
}
.csv-table tbody td,
.csv-table thead th {
padding: 0.75rem 1rem;
text-align: left;
color: var(--color-neutral-300);
white-space: nowrap;
}
.csv-table tbody tr:last-child {
border-bottom: none;
}
.csv-container {
max-height: 60vh;
border-bottom-left-radius: 0.25rem;
border-bottom-right-radius: 0.25rem;
}
</style>
</main>
+7 -1
View File
@@ -1,5 +1,6 @@
@import 'tailwindcss';
@import 'highlight.js/styles/github-dark.css';
@plugin 'tailwind-scrollbar';
* {
box-sizing: border-box;
@@ -82,7 +83,8 @@ select {
color: #3b82f6;
text-decoration: underline;
}
.markdown .load-media-btn:hover {
.markdown .load-media-btn:hover,
.markdown .ignore-media-warning-btn:hover {
background-color: #525252 !important;
}
.markdown pre {
@@ -119,3 +121,7 @@ select {
.markdown th {
background-color: #2a2a2a;
}
button {
cursor: pointer;
}
+18 -13
View File
@@ -5,19 +5,25 @@
import { onMount } from 'svelte';
import type { PageData } from './$types';
let username = '';
let password = '';
let error = '';
let totpEnabled = false;
let totpCode = '';
export let data: PageData;
let username = $state('');
let password = $state('');
let error = $state('');
let totpEnabled = $state(false);
let totpCode = $state('');
interface Props {
data: PageData;
}
let { data }: Props = $props();
onMount(() => {
const render = () => {
if (window.turnstile && data.options?.cf_turnstile_site_key) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.options.cf_turnstile_site_key,
theme: 'dark'
theme: 'dark',
size: 'flexible',
appearence: 'interaction-only'
});
}
};
@@ -33,7 +39,8 @@
};
});
async function login() {
async function login(event: Event) {
event.preventDefault();
const body: { username: string; password: string; token?: string; totpcode?: string } = {
username,
password
@@ -94,7 +101,7 @@
>
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
<form on:submit|preventDefault={login} class="space-y-4">
<form onsubmit={login} class="space-y-4">
<input
type="text"
placeholder="Username"
@@ -120,7 +127,7 @@
inputmode="numeric"
pattern="[0-9]*"
required
on:input={(e) => {
oninput={(e) => {
if (e.target instanceof HTMLInputElement) {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
totpCode = e.target.value;
@@ -130,9 +137,7 @@
/>
{/if}
{#if data.options?.cf_turnstile_site_key}
<div class="flex w-full justify-center">
<div class="cf-turnstile"></div>
</div>
<div class="cf-turnstile w-full"></div>
{/if}
<button
type="submit"
@@ -1,14 +1,19 @@
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 }) => {
export const GET: RequestHandler = async ({ params, request }) => {
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) {
return new Response('Paste not found', { status: 404 });
return new Response(null, {
status: 404,
statusText: 'Not Found'
});
}
const content = await res.text();
return new Response(content, {
@@ -3,9 +3,10 @@ import type { Paste } from '$lib/types/paste';
import { extractError } from '$lib/utils/misc';
import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ fetch }) => {
export const load: PageServerLoad = async ({ fetch, request }) => {
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) {
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
throw error(res.status, errorMsg);
@@ -3,9 +3,13 @@
import { onMount } from 'svelte';
import Paste from '$lib/components/Paste.svelte';
export let data: PageData;
interface Props {
data: PageData;
}
let now = new Date();
let { data }: Props = $props();
let now = $state(new Date());
onMount(() => {
const interval = setInterval(() => {
@@ -19,6 +23,16 @@
<svelte:head>
<title>Recent Pastes - Sharpbin</title>
<meta name="description" content="Browse the most recent pastes shared on Sharpbin." />
<meta name="robots" content="noindex, follow" />
<link rel="canonical" href={data.url} />
<meta property="og:title" content="Recent Pastes - Sharpbin" />
<meta property="og:description" content="Browse the most recent pastes shared on Sharpbin." />
<meta property="og:type" content="website" />
<meta property="og:url" content={data.url} />
<meta property="og:site_name" content="Sharpbin" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Recent Pastes - Sharpbin" />
<meta name="twitter:description" content="Browse the most recent pastes shared on Sharpbin." />
</svelte:head>
<main
@@ -2,30 +2,37 @@
import { goto } from '$app/navigation';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
import { extractError } from '$lib/utils/misc';
import { Check, X } from '@lucide/svelte';
import { Check, X, Eye, EyeClosed } from '@lucide/svelte';
import { slide, fade } from 'svelte/transition';
import { resolve } from '$app/paths';
import { onMount } from 'svelte';
import type { PageData } from './$types';
let username = '';
let password = '';
let confirmPassword = '';
let email = '';
let displayName = '';
let error = '';
let username = $state('');
let password = $state('');
let confirmPassword = $state('');
let email = $state('');
let displayName = $state('');
let error = $state('');
let passwordFocused = false;
let passwordChecks = {
length: false,
let passwordFocused = $state(false);
let showPassword = $state(false);
let passwordChecks = $state({
minLength: false,
maxLength: false,
upper: false,
lower: false,
number: false
};
let passwordValid = false;
let loading = false;
});
let passwordValid = $state(false);
let loading = $state(false);
export let data: PageData;
interface Props {
data: PageData;
}
let { data }: Props = $props();
onMount(() => {
const render = () => {
@@ -36,7 +43,9 @@
) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.options.cf_turnstile_site_key,
theme: 'dark'
theme: 'dark',
size: 'flexible',
appearence: 'interaction-only'
});
}
};
@@ -53,20 +62,25 @@
});
function validatePassword(pw: string) {
passwordChecks.length = pw.length >= 8;
passwordChecks.minLength = pw.length >= 8;
passwordChecks.maxLength = pw.length <= 128;
passwordChecks.upper = /[A-Z]/.test(pw);
passwordChecks.lower = /[a-z]/.test(pw);
passwordChecks.number = /[0-9]/.test(pw);
passwordValid =
passwordChecks.length &&
passwordChecks.minLength &&
passwordChecks.maxLength &&
passwordChecks.upper &&
passwordChecks.lower &&
passwordChecks.number;
}
$: validatePassword(password);
$effect(() => {
validatePassword(password);
});
async function register() {
async function register(event: Event) {
event.preventDefault();
if (!passwordValid || password !== confirmPassword) return;
loading = true;
error = '';
@@ -136,7 +150,7 @@
Registration is currently disabled.
</div>
{/if}
<form on:submit|preventDefault={register} class="space-y-4">
<form onsubmit={register} class="space-y-4">
<input
type="text"
placeholder="Username"
@@ -166,34 +180,61 @@
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
</div>
<input
type="password"
placeholder="Password"
bind:value={password}
required
on:focus={() => (passwordFocused = true)}
on:blur={() => (passwordFocused = false)}
autocomplete="new-password"
disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
<div class="flex w-full">
<input
type={showPassword ? 'text' : 'password'}
placeholder="Password"
bind:value={password}
required
onfocus={() => (passwordFocused = true)}
onblur={() => (passwordFocused = false)}
autocomplete="new-password"
disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-[calc(100%-40px)] rounded-l border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
<button
type="button"
onclick={() => (showPassword = !showPassword)}
disabled={loading || !data.options?.registration_enabled}
class="ml-2 flex w-10 items-center rounded-r border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200 hover:bg-neutral-700 focus:outline-none"
>
{#if showPassword}
<EyeClosed class="h-5 w-5 text-neutral-400" />
{:else}
<Eye class="h-5 w-5 text-neutral-400" />
{/if}
</button>
</div>
{#if passwordFocused}
<ul
transition:slide
class="space-y-2 rounded border border-neutral-700 bg-neutral-800 p-3 text-sm"
>
<li
class="flex items-center gap-2 {passwordChecks.length
class="flex items-center gap-2 {passwordChecks.minLength
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.length}
{#if passwordChecks.minLength}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least 8 characters
</li>
<li
class="flex items-center gap-2 {passwordChecks.maxLength
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.maxLength}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
No more than 128 characters
</li>
<li
class="flex items-center gap-2 {passwordChecks.upper
? 'text-green-400'
@@ -241,6 +282,7 @@
disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
{#if confirmPassword && password !== confirmPassword}
<div
transition:fade
@@ -250,9 +292,7 @@
</div>
{/if}
{#if data.options?.cf_turnstile_site_key && data.options?.registration_enabled}
<div class="flex w-full justify-center">
<div class="cf-turnstile"></div>
</div>
<div class="cf-turnstile w-full"></div>
{/if}
<button
type="submit"
@@ -1,33 +1,24 @@
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { getServerToken } from '$lib/utils/auth';
import { apiUrl } from '$lib/server/api';
import { getServerToken, clearServerTokens, roles, getUserFromToken } from '$lib/utils/auth';
import type { Report } from '$lib/types/report';
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 [];
}
}
export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
export const load: PageServerLoad = async ({ fetch, cookies, params, url, request }) => {
const token = getServerToken(cookies);
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}`, {
headers: { Authorization: `Bearer ${token}` }
const user = getUserFromToken(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) {
@@ -36,7 +27,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
}
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: [] };
return { report, url: url.href, canEdit, options };
@@ -5,15 +5,20 @@
import { tooltip } from '$lib/utils/misc';
import { getToken } from '$lib/utils/auth';
export let data: PageData;
interface Props {
data: PageData;
}
const report = data.report;
let saving = false;
let saveError = '';
const statusOptions = data.options?.statuses ?? [];
const typeOptions = data.options?.types ?? [];
let statusValue = reportStatusLabels[report.status] ?? '';
let typeValue = reportTypeLabels[report.type] ?? '';
let { data }: Props = $props();
const initialReport = () => ({ ...data.report });
let report = $state(initialReport());
let saving = $state(false);
let saveError = $state('');
let statusOptions = $derived(data.options?.statuses ?? []);
let typeOptions = $derived(data.options?.types ?? []);
let statusValue = $state(reportStatusLabels[report.status] ?? '');
let typeValue = $state(reportTypeLabels[report.type] ?? '');
async function updateReport() {
saveError = '';
@@ -143,7 +148,7 @@
<div class="flex items-center gap-3">
<button
class="rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-60"
on:click={updateReport}
onclick={updateReport}
disabled={saving}
>
{saving ? 'Saving...' : 'Update Report'}
@@ -1,37 +1,32 @@
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { getServerToken } from '$lib/utils/auth';
import { apiUrl } from '$lib/server/api';
import {
getServerToken,
getUserFromToken,
clearServerTokens,
hasRole,
roles
} from '$lib/utils/auth';
import type { ReportListResponse } from '$lib/types/report';
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' {
if (value === 'pastes' || value === 'users') return value;
return 'all';
}
export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
export const load: PageServerLoad = async ({ fetch, cookies, url, request }) => {
const token = getServerToken(cookies);
if (!token) throw error(401, 'Login required');
const roles = decodeJwtRoles(token);
if (!roles.includes(1) && !roles.includes(255)) {
const user = getUserFromToken(token);
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.');
}
@@ -49,8 +44,11 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
if ((target === 'pastes' || target === 'all') && pasteId) query.set('pasteId', pasteId);
if ((target === 'users' || target === 'all') && userUuid) query.set('userUUID', userUuid);
const reportsRes = await fetch(`${API_URL}/api/report/${target}?${query.toString()}`, {
headers: { Authorization: `Bearer ${token}` }
const headers = new Headers(request.headers);
headers.set('Authorization', `Bearer ${token}`);
const reportsRes = await fetch(`${apiUrl}/api/report/${target}?${query.toString()}`, {
headers: headers
});
if (!reportsRes.ok) {
@@ -60,7 +58,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
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: [] };
return {
@@ -1,4 +1,7 @@
<script lang="ts">
import { createBubbler, stopPropagation } from 'svelte/legacy';
const bubble = createBubbler();
import type { PageData } from './$types';
import { resolve } from '$app/paths';
import { goto } from '$app/navigation';
@@ -6,14 +9,30 @@
import { tooltip } from '$lib/utils/misc';
import { SvelteURLSearchParams } from 'svelte/reactivity';
export let data: PageData;
interface Props {
data: PageData;
}
let target = data.filters.target;
let status = data.filters.status;
let type = data.filters.type ?? '';
let pasteId = data.filters.pasteId;
let userUuid = data.filters.userUuid;
let mixedTarget = target === 'all' ? pasteId || userUuid : '';
let { data }: Props = $props();
const initialFilters = (() => {
const filters = data.filters;
return {
target: (filters.target as 'all' | 'pastes' | 'users') ?? 'all',
status: filters.status ?? '',
type: filters.type ?? '',
pasteId: filters.pasteId ?? '',
userUuid: filters.userUuid ?? ''
};
})();
let target = $state(initialFilters.target);
let status = $state(initialFilters.status);
let type = $state(initialFilters.type);
let pasteId = $state(initialFilters.pasteId);
let userUuid = $state(initialFilters.userUuid);
let mixedTarget = $state(
initialFilters.target === 'all' ? initialFilters.pasteId || initialFilters.userUuid : ''
);
let inputTimer: ReturnType<typeof setTimeout> | null = null;
const targets = [
@@ -22,8 +41,8 @@
{ value: 'users', label: 'Users' }
];
const statuses = data.options?.statuses ?? [];
const types = data.options?.types ?? [];
let statuses = $derived(data.options?.statuses ?? []);
let types = $derived(data.options?.types ?? []);
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function applyFilters(page = 1) {
@@ -108,7 +127,7 @@
id="report-target"
class="rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={target}
on:change={(e) => {
onchange={(e) => {
if (e.currentTarget instanceof HTMLSelectElement) {
handleTargetChange(e.currentTarget.value);
}
@@ -125,7 +144,7 @@
id="report-status"
class="rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={status}
on:change={() => applyFilters(1)}
onchange={() => applyFilters(1)}
>
<option value="">Any</option>
{#each statuses as s (s)}
@@ -139,7 +158,7 @@
id="report-type"
class="rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={type}
on:change={() => applyFilters(1)}
onchange={() => applyFilters(1)}
>
<option value="">Any</option>
{#each types as t (t)}
@@ -165,7 +184,7 @@
? 'User UUID'
: 'Paste ID or User UUID'}
value={target === 'pastes' ? pasteId : target === 'users' ? userUuid : mixedTarget}
on:input={(e) => {
oninput={(e) => {
if (e.currentTarget instanceof HTMLInputElement) {
handleTargetInput(e.currentTarget.value);
}
@@ -181,8 +200,8 @@
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"
role="link"
tabindex="0"
on:click={() => goto(resolve(`/report/${report.reportID}`))}
on:keydown={(e) => {
onclick={() => goto(resolve(`/report/${report.reportID}`))}
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
goto(resolve(`/report/${report.reportID}`));
@@ -204,7 +223,7 @@
<a
href={resolve(`/${report.pasteId}`)}
class="text-neutral-300 hover:text-white"
on:click|stopPropagation
onclick={stopPropagation(bubble('click'))}
>
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
</a>
@@ -215,7 +234,7 @@
href={resolve(`/user/${report.targetUsername}`)}
class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID}
on:click|stopPropagation
onclick={stopPropagation(bubble('click'))}
>
{report.targetDisplayName || report.targetUsername}
</a>
@@ -228,7 +247,7 @@
href={resolve(`/user/${report.reporterUsername}`)}
class="text-neutral-300 hover:text-white"
use:tooltip={report.reporterUUID}
on:click|stopPropagation
onclick={stopPropagation(bubble('click'))}
>
{report.reporterDisplayName || report.reporterUsername}
</a>
@@ -251,7 +270,7 @@
<div class="mt-6 flex items-center justify-center gap-4">
<button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => applyFilters(data.reports.pagination.page - 1)}
onclick={() => applyFilters(data.reports.pagination.page - 1)}
disabled={data.reports.pagination.page <= 1}
>
Prev
@@ -261,7 +280,7 @@
</span>
<button
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
on:click={() => applyFilters(data.reports.pagination.page + 1)}
onclick={() => applyFilters(data.reports.pagination.page + 1)}
disabled={data.reports.pagination.page >= data.reports.pagination.totalPages}
>
Next
@@ -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,130 @@
<script lang="ts">
import type { PageData } from './$types';
import { formatBytes, formatNumber, tooltip } from '$lib/utils/misc';
import { FileText, Users, Database, TrendingUp } from '@lucide/svelte';
interface Props {
data: PageData;
}
let { data }: Props = $props();
let stats = $derived(data.stats.stats);
let dailyData = $derived(stats.pastes.daily || []);
let maxCount = $derived(
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 { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { apiUrl } from '$lib/server/api';
import { getServerToken } from '$lib/utils/auth';
import type { User } from '$lib/types/user';
import type { Paste } from '$lib/types/paste';
import type { Pagination } from '$lib/types/pagination';
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 {
if (!token) return [];
if (!token) return 0;
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));
if (typeof roles === 'number') return roles;
if (typeof roles === 'string') {
const parsed = parseInt(roles, 10);
return isNaN(parsed) ? 0 : parsed;
}
return [];
return 0;
} 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 { username } = params;
const { options } = await parent();
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}`, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined
const res = await fetch(`${apiUrl}/api/user/${username}`, {
headers: headers
});
if (!res.ok) {
@@ -60,8 +65,8 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
let reportsTarget: ReportListResponse | null = null;
let reportsSubmitted: ReportListResponse | null = null;
const roles = token ? decodeJwtRoles(token) : [];
const canModerate = roles.includes(255) || roles.includes(1);
const roles = token ? decodeJwtRoles(token) : 0;
const canModerate = (roles & 4) !== 0 || (roles & 2) !== 0;
if (isOwner && reports && reportsPagination) {
reportsSubmitted = {
@@ -70,20 +75,20 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
};
}
if (token && canModerate && (!reportsSubmitted || !isOwner)) {
const submittedRes = await fetch(`${API_URL}/api/user/${user.uuid}/reports/submitted`, {
headers: { Authorization: `Bearer ${token}` }
if (token && !asGuest && canModerate && (!reportsSubmitted || !isOwner)) {
headers.set('Authorization', `Bearer ${token}`);
const submittedRes = await fetch(`${apiUrl}/api/report/users/${user.uuid}/reports/submitted`, {
headers: headers
});
if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
}
if (token && !isOwner) {
if (canModerate) {
const r = await fetch(`${API_URL}/api/user/${user.uuid}/reports`, {
headers: { Authorization: `Bearer ${token}` }
});
if (r.ok) reportsTarget = await r.json();
}
if (token && !asGuest && !isOwner && canModerate) {
headers.set('Authorization', `Bearer ${token}`);
const r = await fetch(`${apiUrl}/api/report/users/${user.uuid}/reports`, {
headers: headers
});
if (r.ok) reportsTarget = await r.json();
}
return {
File diff suppressed because it is too large Load Diff
@@ -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>
+12 -2
View File
@@ -1,3 +1,13 @@
# allow crawling everything by default
User-agent: *
Disallow:
Allow: /$
Allow: /recent
Allow: /stats
Allow: /user/
Disallow: /api/
Disallow: /login
Disallow: /register
Disallow: /verify-email
Disallow: /report/
Disallow: /reports
Disallow: /health
Disallow: /raw/
+4 -2
View File
@@ -16,12 +16,14 @@ const allowedHosts = process.env.VITE_ALLOWED_HOSTS
export default defineConfig({
plugins: [tailwindcss(), sveltekit()],
define: {
__APP_VERSION__: JSON.stringify(pkg.version)
__APP_VERSION__: JSON.stringify(pkg.version),
COMMIT_HASH: JSON.stringify(process.env.GIT_COMMIT_HASH || 'unknown')
},
server: {
host: true,
proxy: {
'/api': apiUrl
'/api': apiUrl,
'/openapi': apiUrl
},
allowedHosts: allowedHosts
},
+5
View File
@@ -0,0 +1,5 @@
Migrations/
obj/
bin/
cache/
SharpbinV3/
+6
View File
@@ -0,0 +1,6 @@
{
"printWidth": 150,
"useTabs": false,
"indentSize": 4,
"endOfLine": "auto"
}
@@ -0,0 +1,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
{
@@ -7,18 +8,31 @@ namespace SharpbinV3.Server.Authorization
{
private readonly bool _requireAuth = requireAuth;
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
NotBannedRequirement requirement)
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
{
var httpContext = context.Resource as HttpContext;
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
if (!isAuthenticated && httpContext != null)
{
var apiKey = httpContext.GetApiKeyFromContext();
if (apiKey != null)
{
isAuthenticated = true;
}
}
if (_requireAuth && !isAuthenticated)
return Task.CompletedTask;
var isBanned = context.User.Claims.Any(c =>
(c.Type == ClaimTypes.Role || c.Type == "role") &&
c.Value == "403");
var isBanned =
bool.TryParse(context.User.Claims.FirstOrDefault(c => c.Type == "is_banned")?.Value, out var parsedIsBanned) && parsedIsBanned;
if (!isBanned && httpContext?.GetJwtUser()?.IsBanned == true)
isBanned = true;
if (httpContext?.GetApiKeyFromContext()?.User?.IsBanned == true)
isBanned = true;
if (!isBanned)
context.Succeed(requirement);
@@ -2,7 +2,5 @@
namespace SharpbinV3.Server.Authorization
{
public class NotBannedRequirement : IAuthorizationRequirement
{
}
public class NotBannedRequirement : IAuthorizationRequirement { }
}
+184 -67
View File
@@ -6,6 +6,7 @@ using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.ApiKey;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.DTOs.User;
using SharpbinV3.Server.Extensions;
@@ -19,11 +20,19 @@ namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options,
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase
public class AuthController(
UserService userService,
AuthService authService,
ApiKeyService apiKeyService,
IOptions<AuthSettings> options,
VerificationService verification,
TotpVerificationProvider totp,
AppDbContext db
) : ControllerBase
{
private readonly AuthService _authService = authService;
private readonly UserService _userService = userService;
private readonly ApiKeyService _apiKeyService = apiKeyService;
private readonly VerificationService _verification = verification;
private readonly TotpVerificationProvider _totp = totp;
private readonly AppDbContext _db = db;
@@ -37,11 +46,7 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(new { success = false, message = "Registration is disabled." });
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (!await _verification.VerifyAsync(new VerificationContext
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
return BadRequest(new { success = false, message = "Verification failed." });
var existingUser = await _userService.GetByUsername(request.Username);
@@ -56,22 +61,39 @@ namespace SharpbinV3.Server.Controllers
if (!string.IsNullOrEmpty(request.DisplayName) && request.DisplayName.Length > 26)
return BadRequest(new { success = false, message = "Display name should not exceed 26 characters." });
var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
return Ok(new
User user;
try
{
message = "User registered successfully.",
user = new UserResponseDto
{
UID = user.UID,
UUID = user.UUID,
Username = user.Username,
DisplayName = user.DisplayName,
Email = user.Email,
Roles = user.Roles,
Visibility = user.Visibility,
LastLogin = user.LastLogin
}
user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
}
catch (DbUpdateException)
{
if (await _userService.GetByUsername(request.Username) != null)
return Conflict(new { success = false, message = "Username already exists." });
throw;
}
if (!string.IsNullOrWhiteSpace(user.Email))
await _authService.SendEmailVerification(user);
return Ok(
new
{
message = "User registered successfully.",
user = new UserResponseDto
{
UID = user.UID,
UUID = user.UUID,
Username = user.Username,
DisplayName = user.DisplayName,
Email = user.Email,
Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility,
LastLogin = user.LastLogin,
},
}
);
}
@@ -83,11 +105,7 @@ namespace SharpbinV3.Server.Controllers
if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email))
return BadRequest(new { success = false, message = "Username or email is required." });
if (!await _verification.VerifyAsync(new VerificationContext
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
return BadRequest(new { success = false, message = "Verification failed." });
User? user = null;
@@ -104,24 +122,25 @@ namespace SharpbinV3.Server.Controllers
{
if (string.IsNullOrWhiteSpace(request.TotpCode))
return BadRequest(new { success = false, message = "TOTP code is required." });
var totpValid = await _totp.VerifyAsync(new VerificationContext
{
UserUUID = user.UUID,
Code = request.TotpCode
});
var totpValid = await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode });
if (!totpValid)
return BadRequest(new { success = false, message = "Invalid TOTP code." });
}
var token = _authService.GenerateJWTToken(user);
await _authService.UpdateLoginTime(user);
var result = await token;
return Ok(new LoginResponseDto
{
Success = true,
Token = result.Token ?? string.Empty,
RefreshToken = result.RefreshToken ?? string.Empty
});
return Ok(
new LoginResponseDto
{
Success = true,
Token = result.Token ?? string.Empty,
RefreshToken = result.RefreshToken ?? string.Empty,
}
);
}
[HttpPost]
[Route("refresh")]
[EnableRateLimiting("Sliding")]
@@ -130,16 +149,17 @@ namespace SharpbinV3.Server.Controllers
try
{
var jwtResult = await _authService.RefreshJWTToken(request.Token, request.RefreshToken);
return Ok(new TokenRefreshResponseDto
{
Success = jwtResult?.Success ?? false,
Message = jwtResult?.Errors != null && jwtResult.Errors.Count > 0 ? string.Join("; ", jwtResult.Errors) : "Token refreshed successfully.",
Token = jwtResult != null ? new TokenData
return Ok(
new TokenRefreshResponseDto
{
Token = jwtResult.Token,
RefreshToken = jwtResult.RefreshToken
} : null
});
Success = jwtResult?.Success ?? false,
Message =
jwtResult?.Errors != null && jwtResult.Errors.Count > 0
? string.Join("; ", jwtResult.Errors)
: "Token refreshed successfully.",
Token = jwtResult != null ? new TokenData { Token = jwtResult.Token, RefreshToken = jwtResult.RefreshToken } : null,
}
);
}
catch (Exception ex)
{
@@ -153,39 +173,45 @@ namespace SharpbinV3.Server.Controllers
public IActionResult GetSiteInfo()
{
var authSettings = options.Value;
return Ok(new
{
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
registration_enabled = authSettings.Registration_Enabled
});
return Ok(
new
{
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
registration_enabled = authSettings.Registration_Enabled,
}
);
}
[HttpGet]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[Route("totp/enroll")]
public async Task<IActionResult> StartTotpEnrollment()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user is null) return BadRequest(new { success = false, message = "User not found." });
if (user is null)
return BadRequest(new { success = false, message = "User not found." });
var secret = _totp.GenerateSecret();
var secretBase32 = _totp.ToBase32(secret);
var account = string.IsNullOrWhiteSpace(user.Email) ? user.Username : user.Email!;
var uri = _totp.BuildOtpAuthUri("SharpbinV3", account, secretBase32);
return Ok(new { success = true, secret = secretBase32, otpauth = uri });
return Ok(
new
{
success = true,
secret = secretBase32,
otpauth = uri,
}
);
}
[HttpPost]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[Route("totp/enable")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
{
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
if (string.IsNullOrEmpty(uuidClaim))
return Unauthorized(new { success = false, message = "Invalid token." });
var uuid = Guid.Parse(uuidClaim);
var uuid = Guid.Parse(User.FindFirst("uuid")!.Value);
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new { success = false, message = "Secret and code are required." });
@@ -210,27 +236,118 @@ namespace SharpbinV3.Server.Controllers
}
[HttpPost]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[Route("totp/disable")]
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null) return BadRequest(new { success = false, message = "User not found." });
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
if (string.IsNullOrWhiteSpace(dto.Code))
return BadRequest(new { success = false, message = "TOTP code is required." });
var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == user.UUID);
if (existing is null)
return BadRequest(new { success = false, message = "TOTP is not enabled." });
if (!_totp.VerifyAsync(new VerificationContext
{
UserUUID = user.UUID,
Code = dto.Code
}).Result)
if (!_totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = dto.Code }).Result)
return BadRequest(new { success = false, message = "Invalid TOTP code." });
_db.UserTotps.Remove(existing);
await _db.SaveChangesAsync();
return Ok(new { success = true, message = "TOTP disabled." });
}
[HttpPost]
[Authorize(Policy = "JwtOnly")]
[Route("apikey/create")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> CreateApiKey([FromBody] CreateApiKeyRequest request)
{
if (string.IsNullOrWhiteSpace(request.Name))
return BadRequest(new { success = false, message = "API key name is required." });
if (request.Name.Length > 26)
return BadRequest(new { success = false, message = "API key name must not exceed 26 characters." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var existingKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
if (existingKeys.Count >= 10)
return BadRequest(new { success = false, message = "API key limit reached. Please delete existing keys before creating new ones." });
var (apiKey, key) = await _apiKeyService.CreateAsync(user.UUID, request.Name);
return Ok(
new
{
success = true,
message = "API key created. Save it now as you won't be able to see it again.",
apiKey = new ApiKeyResponseDto
{
UUID = apiKey.UUID,
Key = key,
Name = apiKey.Name,
CreatedAt = apiKey.CreatedAt,
},
}
);
}
[HttpGet]
[Authorize]
[Route("apikey/list")]
public async Task<IActionResult> ListApiKeys()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var apiKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
return Ok(
new
{
success = true,
apiKeys = apiKeys
.Select(k => new ApiKeyListItemDto
{
UUID = k.UUID,
Name = k.Name,
CreatedAt = k.CreatedAt,
LastUsedAt = k.LastUsedAt,
})
.ToList(),
}
);
}
[HttpDelete]
[Authorize(Policy = "JwtOnly")]
[Route("apikey/{uuid}")]
public async Task<IActionResult> DeleteApiKey(string uuid)
{
if (!Guid.TryParse(uuid, out var keyUUID))
return BadRequest(new { success = false, message = "Invalid API key UUID." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var deleted = await _apiKeyService.DeleteAsync(user.UUID, keyUUID);
if (!deleted)
return NotFound(new { success = false, message = "API key not found." });
return Ok(new { success = true, message = "API key deleted." });
}
[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 });
}
}
}
+423 -227
View File
@@ -1,8 +1,10 @@
using Microsoft.AspNetCore.Authorization;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.DTOs.Report;
using SharpbinV3.Server.DTOs.User;
@@ -15,13 +17,23 @@ namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PasteController(PasteService pasteService, VerificationService verificationService, AuthService authService,
ReportService reportService, IOptions<PasteSettings> options, IOptions<AuthSettings> authSettings) : ControllerBase
public class PasteController(
PasteService pasteService,
CommentService commentService,
VerificationService verificationService,
AuthService authService,
ReportService reportService,
ICompressionService compressionService,
IOptions<PasteSettings> options,
IOptions<AuthSettings> authSettings
) : ControllerBase
{
private readonly PasteService _pasteService = pasteService;
private readonly CommentService _commentService = commentService;
private readonly VerificationService _verificationService = verificationService;
private readonly AuthService _authService = authService;
private readonly ReportService _reportService = reportService;
private readonly ICompressionService _compressionService = compressionService;
private readonly PasteSettings _pasteSettings = options.Value;
private readonly AuthSettings _authSettings = authSettings.Value;
@@ -29,98 +41,130 @@ namespace SharpbinV3.Server.Controllers
[Route("create")]
[Authorize(Policy = "NotBanned")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0, string? token = null)
public async Task<IActionResult> CreatePaste(
string title = "",
string syntax = "plaintext",
Visibility visibility = Visibility.Public,
long expiresAt = 0,
string? verificationToken = null
)
{
if (!await _pasteService.ValidateExpiresAt(expiresAt))
if (!_pasteService.ValidateExpiresAt(expiresAt))
return BadRequest(new { success = false, message = "Invalid expiration time." });
if (!await _pasteService.ValidateVisibility(visibility))
if (!_pasteService.ValidateVisibility(visibility))
return BadRequest(new { success = false, message = "Invalid visibility level. Must be between 0 and 2." });
if (!await _pasteService.ValidateSyntax(syntax))
if (!_pasteService.ValidateSyntax(syntax))
return BadRequest(new { success = false, message = "Invalid syntax." });
if (!await _pasteService.ValidateTitle(title))
if (!_pasteService.ValidateTitle(title))
return BadRequest(new { success = false, message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (content.Length == 0)
return BadRequest(new { success = false, message = "Paste content cannot be empty." });
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
return BadRequest(new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
return BadRequest(
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
);
if (_pasteSettings.RequiresVerfication && !await _verificationService.VerifyAsync(new VerificationContext
if (_pasteSettings.RequiresVerification && !HttpContext.IsApiKeyAuthenticated())
{
Token = token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { success = false, message = "Verification failed." });
var providedApiKey = HttpContext.GetApiKey();
if (providedApiKey != null)
return BadRequest(new { success = false, message = "Invalid API key." });
var verifyResult = await _verificationService.VerifyAsync(
new VerificationContext { Token = verificationToken, Ip = HttpContext.GetRequestIP() }
);
if (!verifyResult)
return BadRequest(new { success = false, message = "Verification failed." });
}
var user = await _authService.GetUserFromHttpContext(HttpContext);
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
return Ok(new PasteCreatedResponseDto
{
ID = paste.ID,
UUID = paste.UUID,
IsCompressed = paste.IsCompressed,
Size = paste.Size,
TrueSize = paste.TrueSize,
ExpiresAt = paste.ExpiresAt
});
return Ok(
new PasteCreatedResponseDto
{
ID = paste.ID,
UUID = paste.UUID,
CreatedAt = paste.CreatedAt,
IsCompressed = paste.IsCompressed,
StoredSize = paste.StoredSize,
OriginalSize = paste.OriginalSize,
ExpiresAt = paste.ExpiresAt,
Visibility = paste.Visibility,
}
);
}
[HttpGet]
[EnableRateLimiting("NoLimit")]
[Route("{id}")]
public async Task<IActionResult> GetPasteByID(string 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" });
var jwtUser = HttpContext.GetJwtUser();
PasteInteraction? userInteraction = null;
if (jwtUser != null)
userInteraction = await _pasteService.GetUserInteraction(paste, jwtUser.UUID);
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
{
PastePID = paste.PID
};
var query = new ReportQuery { PastePID = paste.PID };
reportCount = await _reportService.GetReportCount(query);
}
return Ok(new
{
success = true,
paste = new PasteResponseDto
return Ok(
new
{
ID = paste.ID,
UUID = paste.UUID,
Title = paste.Title,
Size = paste.Size,
TrueSize = paste.TrueSize,
IsCompressed = paste.IsCompressed,
Views = paste.Views,
Syntax = paste.Syntax,
Visibility = paste.Visibility,
ExpiresAt = paste.ExpiresAt,
EditedAt = paste.EditedAt,
ReportCount = reportCount,
Author = paste.User != null && paste.User.Visibility == 0 ? new UserSimpleDto
success = true,
paste = new PasteResponseDto
{
UID = paste.User.UID,
UUID = paste.User.UUID,
Username = paste.User.Username,
DisplayName = paste.User.DisplayName,
Visibility = paste.User.Visibility,
Roles = paste.User.Roles
} : null
ID = paste.ID,
UUID = paste.UUID,
CreatedAt = paste.CreatedAt,
Title = paste.Title,
StoredSize = paste.StoredSize,
OriginalSize = paste.OriginalSize,
IsCompressed = paste.IsCompressed,
Views = paste.Views,
Syntax = paste.Syntax,
Visibility = paste.Visibility,
ExpiresAt = paste.ExpiresAt,
EditedAt = paste.EditedAt,
ReportCount = reportCount,
UserReaction = userInteraction != null ? userInteraction.Type : null,
Likes = paste.PositiveInteractionCount,
Dislikes = paste.NegativeInteractionCount,
Author =
paste.User != null && paste.User.Visibility == 0
? new UserSimpleDto
{
UID = paste.User.UID,
UUID = paste.User.UUID,
Username = paste.User.Username,
DisplayName = paste.User.DisplayName,
Visibility = paste.User.Visibility,
Roles = paste.User.Roles,
IsBanned = paste.User.IsBanned,
}
: null,
},
}
});
);
}
[HttpGet]
[EnableRateLimiting("NoLimit")]
[Route("{id}/raw")]
public async Task<IActionResult> GetRawPasteByID(string 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)
Response.Headers.Append("Content-Encoding", "gzip");
@@ -129,7 +173,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPut]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> EditPaste(string id)
{
string content = await new StreamReader(Request.Body).ReadToEndAsync();
@@ -140,40 +184,34 @@ namespace SharpbinV3.Server.Controllers
if (paste == null)
return StatusCode(404, new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
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);
if (!result) return StatusCode(500, new { success = false, message = "An error occurred while editing the paste." });
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while editing the paste." });
return Ok(new { message = "Paste edited successfully." });
}
[HttpPatch]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
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)
paste.Title = request.Title;
if (request.Syntax != null)
@@ -183,56 +221,57 @@ namespace SharpbinV3.Server.Controllers
if (request.ExpiresAt.HasValue)
paste.ExpiresAt = request.ExpiresAt.Value;
if (!await _pasteService.ValidateExpiresAt(paste.ExpiresAt))
if (!_pasteService.ValidateExpiresAt(paste.ExpiresAt))
return BadRequest(new { success = false, message = "Invalid expiration time." });
if (!await _pasteService.ValidateVisibility(paste.Visibility))
if (!_pasteService.ValidateVisibility(paste.Visibility))
return BadRequest(new { success = false, message = "Invalid visibility level. Must be between 0 and 2." });
if (!await _pasteService.ValidateSyntax(paste.Syntax ?? "plaintext"))
if (!_pasteService.ValidateSyntax(paste.Syntax ?? "plaintext"))
return BadRequest(new { success = false, message = "Invalid syntax." });
if (!await _pasteService.ValidateTitle(paste.Title ?? ""))
if (!_pasteService.ValidateTitle(paste.Title ?? ""))
return BadRequest(new { success = false, message = $"Invalid title. Must be less than {_pasteSettings.MaxTitleLength} characters." });
var newPaste = await _pasteService.Edit(paste);
return Ok(new
{
success = true,
message = "Paste metadata updated successfully.",
paste = new PasteResponseDto
return Ok(
new
{
ID = newPaste.ID,
UUID = newPaste.UUID,
Title = newPaste.Title,
Size = newPaste.Size,
TrueSize = newPaste.TrueSize,
IsCompressed = newPaste.IsCompressed,
Views = newPaste.Views,
Syntax = newPaste.Syntax,
Visibility = newPaste.Visibility,
ExpiresAt = newPaste.ExpiresAt
success = true,
message = "Paste metadata updated successfully.",
paste = new PasteResponseDto
{
ID = newPaste.ID,
UUID = newPaste.UUID,
CreatedAt = newPaste.CreatedAt,
Title = newPaste.Title,
OriginalSize = newPaste.OriginalSize,
StoredSize = newPaste.StoredSize,
IsCompressed = newPaste.IsCompressed,
Views = newPaste.Views,
Syntax = newPaste.Syntax,
Visibility = newPaste.Visibility,
ExpiresAt = newPaste.ExpiresAt,
},
}
});
);
}
[HttpDelete]
[Route("{id}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> DeletePaste(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null) return NotFound(new { success = false, message = "Paste not found." });
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
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);
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." });
}
@@ -241,16 +280,25 @@ namespace SharpbinV3.Server.Controllers
[Authorize(Policy = "NotBanned")]
public async Task<IActionResult> RecordPasteView(string id)
{
if (HttpContext.IsKnownBot())
return Ok(new { success = true, message = "View not recorded for known bot." });
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
if (_pasteSettings.View_HMAC_Secret == null)
return StatusCode(500, new { success = false, message = "View recording is not configured properly." });
if (!string.IsNullOrWhiteSpace(_pasteSettings.View_Internal_API_Key)
&& _pasteSettings.View_Internal_API_Key != Request.Headers["X-Internal-API-Key"])
if (
!string.IsNullOrWhiteSpace(_pasteSettings.View_Internal_API_Key)
&& _pasteSettings.View_Internal_API_Key != Request.Headers["X-Internal-API-Key"]
)
return Unauthorized(new { success = false, message = "Invalid API key." });
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);
if (result.paste is null && !result.alreadyExists)
@@ -262,119 +310,67 @@ namespace SharpbinV3.Server.Controllers
}
[HttpPost]
[Route("{id}/report")]
[Authorize(Policy = "AuthAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[Route("{id}/reaction")]
public async Task<IActionResult> ReactToPaste(string id, [FromBody] ReactToPasteDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser();
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
return NotFound(new { success = false, message = "Paste not found" });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
return Unauthorized(new { success = false, message = "User not authenticated." });
if (paste.AuthorUUID == user.UUID)
return BadRequest(new { success = false, message = "You cannot react to your own paste." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
var existingInteraction = await _pasteService.GetUserInteraction(paste, user.UUID);
if (!await _verificationService.VerifyAsync(new VerificationContext
if (request.Reaction.HasValue)
{
Token = request.VerificationToken,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { success = false, message = "Verification failed." });
Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description);
if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
return Ok(new
{
success = true,
message = "Paste reported successfully.",
report = new ReportResponseDto
if (existingInteraction == null)
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType,
UserUUID = report.UserUUID
var created = await _pasteService.RecordInteraction(paste, user, request.Reaction.Value);
if (created == null)
return StatusCode(500, new { success = false, message = "Could not save reaction." });
}
});
}
else if (existingInteraction.Type != request.Reaction.Value)
{
var removed = await _pasteService.RemoveInteraction(paste, user);
if (!removed)
return StatusCode(500, new { success = false, message = "Could not update reaction." });
[HttpPatch]
[Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var created = await _pasteService.RecordInteraction(paste, user, request.Reaction.Value);
if (created == null)
return StatusCode(500, new { success = false, message = "Could not update reaction." });
}
}
else if (existingInteraction != null)
{
var removed = await _pasteService.RemoveInteraction(paste, user);
if (!removed)
return StatusCode(500, new { success = false, message = "Could not remove reaction." });
}
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." });
var updatedPaste = await _pasteService.Get(id);
if (updatedPaste == null)
return StatusCode(500, new { success = false, message = "Could not load updated paste." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var updatedInteraction = await _pasteService.GetUserInteraction(updatedPaste, user.UUID);
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
report.Type = reportType;
report.Description = request.Description;
var updatedReport = await _reportService.UpdateReport(report);
if (updatedReport == null)
return StatusCode(500, new { success = false, message = "An error occurred while updating the report." });
return Ok(new { success = true, message = "Report updated successfully." });
}
[HttpDelete]
[Route("{id}/report/{reportId}")]
[Authorize(Policy = "AuthAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeletePasteReport(string id, int reportId)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser();
if (user == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
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);
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
return Ok(new { success = true, message = "Report deleted successfully." });
return Ok(
new
{
success = true,
reaction = new PasteReactionResponseDto
{
PasteID = updatedPaste.ID,
Likes = updatedPaste.PositiveInteractionCount,
Dislikes = updatedPaste.NegativeInteractionCount,
UserReaction = updatedInteraction?.Type,
},
}
);
}
[HttpGet]
@@ -382,20 +378,176 @@ namespace SharpbinV3.Server.Controllers
public async Task<IActionResult> GetRecentPastes()
{
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,
UUID = p.UUID,
CreatedAt = p.CreatedAt,
Title = p.Title,
StoredSize = p.StoredSize,
OriginalSize = p.OriginalSize,
IsCompressed = p.IsCompressed,
Views = p.Views,
Syntax = p.Syntax,
Visibility = p.Visibility,
ExpiresAt = p.ExpiresAt,
EditedAt = p.EditedAt,
Author =
p.User != null && p.User.Visibility == 0
? new UserSimpleDto
{
UID = p.User.UID,
UUID = p.User.UUID,
Username = p.User.Username,
DisplayName = p.User.DisplayName,
Visibility = p.User.Visibility,
Roles = p.User.Roles,
IsBanned = p.User.IsBanned,
}
: null,
})
);
}
[HttpGet]
[EnableRateLimiting("NoLimit")]
[Route("{id}/comments")]
public async Task<IActionResult> GetComments(string id)
{
var paste = await _pasteService.Get(id);
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
return NotFound(new { success = false, message = "Paste not found" });
var comments = await _commentService.GetCommentsByPaste(paste);
Dictionary<long, Interaction>? userInteractionMap = null;
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user != null)
userInteractionMap = await _commentService.GetUserInteractions(comments.Select(c => c.Id).ToList(), user.UUID);
return Ok(new { success = true, comments = comments.Select(c => ToCommentResponse(c, userInteractionMap)) });
}
[HttpPost]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[Route("{id}/comments")]
public async Task<IActionResult> CreateComment(string id, [FromBody] CreateCommentDto request)
{
if (string.IsNullOrWhiteSpace(request.Content))
return BadRequest(new { success = false, message = "Comment content cannot be empty." });
var paste = await _pasteService.Get(id);
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
return NotFound(new { success = false, message = "Paste not found" });
if (Encoding.UTF8.GetByteCount(request.Content) > 5000)
return BadRequest(new { success = false, message = "Comment content exceeds maximum size of 5000 bytes." });
if (request.ParentCommentID.HasValue)
{
ID = p.ID,
UUID = p.UUID,
Title = p.Title,
Size = p.Size,
TrueSize = p.TrueSize,
IsCompressed = p.IsCompressed,
Views = p.Views,
Syntax = p.Syntax,
Visibility = p.Visibility,
ExpiresAt = p.ExpiresAt,
EditedAt = p.EditedAt
}));
var parent = await _commentService.GetCommentByID(request.ParentCommentID.Value, paste.PID);
if (parent == null)
return BadRequest(new { success = false, message = "Parent comment not found for this paste." });
}
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return Unauthorized(new { success = false, message = "User not authenticated." });
var comment = await _commentService.CreateComment(user, paste, request.Content, request.ParentCommentID);
var created = await _commentService.GetCommentByID(comment.Id);
if (created == null)
return StatusCode(500, new { success = false, message = "Failed to load created comment." });
var userInteractionMap = new Dictionary<long, Interaction>();
return Ok(new { success = true, comment = ToCommentResponse(created, userInteractionMap) });
}
[HttpPost]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[Route("{id}/comments/{commentId}/reaction")]
public async Task<IActionResult> ReactToComment(string id, long commentId, [FromBody] ReactToCommentDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
return NotFound(new { success = false, message = "Paste not found" });
var comment = await _commentService.GetCommentByID(commentId, paste.PID);
if (comment == null)
return NotFound(new { success = false, message = "Comment not found for this paste." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return Unauthorized(new { success = false, message = "User not authenticated." });
if (request.Reaction.HasValue)
{
var result = await _commentService.UpsertInteraction(comment, user, request.Reaction.Value);
if (result == null)
return StatusCode(500, new { success = false, message = "Could not save reaction." });
}
else
{
await _commentService.RemoveInteraction(comment, user);
}
var updated = await _commentService.GetCommentByID(commentId);
if (updated == null)
return StatusCode(500, new { success = false, message = "Could not load updated comment." });
var interactionMap = await _commentService.GetUserInteractions([commentId], user.UUID);
Interaction? userReaction = null;
if (interactionMap.TryGetValue(commentId, out var mappedReaction))
userReaction = mappedReaction;
return Ok(
new
{
success = true,
reaction = new CommentReactionResponseDto
{
CommentID = updated.Id,
Likes = updated.PositiveInteractionCount,
Dislikes = updated.NegativeInteractionCount,
UserReaction = userReaction,
},
}
);
}
[HttpDelete]
[Authorize(Policy = "JwtOnly")]
[Route("{id}/comments/{commentId}")]
public async Task<IActionResult> DeleteComment(string id, long commentId, bool hardDelete = false)
{
var paste = await _pasteService.Get(id);
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
return NotFound(new { success = false, message = "Paste not found" });
var comment = await _commentService.GetCommentByID(commentId, paste.PID);
if (comment == null)
return NotFound(new { success = false, message = "Comment not found for this paste." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return Unauthorized(new { success = false, message = "User not authenticated." });
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (comment.UserUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this comment." });
if (hardDelete && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to hard delete this comment." });
bool result;
if (hardDelete)
result = await _commentService.HardDeleteComment(comment);
else
result = await _commentService.DeleteComment(comment);
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the comment." });
return Ok(new { success = true, message = "Comment deleted successfully." });
}
[HttpGet]
@@ -403,19 +555,63 @@ namespace SharpbinV3.Server.Controllers
[Route("info")]
public IActionResult GetCreatePasteOptions()
{
return Ok(new PasteOptionsDto
return Ok(
new PasteOptionsDto
{
Syntaxes = [.. _pasteSettings.ValidSyntaxLanguages],
Visibilities =
[
new() { Value = 0, DisplayName = "Public" },
new() { Value = 1, DisplayName = "Unlisted" },
new() { Value = 2, DisplayName = "Private" },
],
MaxTitleLength = _pasteSettings.MaxTitleLength,
MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes,
RequiresVerification = _pasteSettings.RequiresVerification,
}
);
}
private CommentResponseDto ToCommentResponse(Comment comment, Dictionary<long, Interaction>? userInteractionMap)
{
string? content = null;
if (comment.Content != null)
{
Syntaxes = _pasteSettings.ValidSyntaxLanguages,
Visibilities =
[
new() { Value = 0, DisplayName = "Public" },
new() { Value = 1, DisplayName = "Unlisted" },
new() { Value = 2, DisplayName = "Private" }
],
MaxTitleLength = _pasteSettings.MaxTitleLength,
MaxPasteSize = _pasteSettings.MaxPasteSizeInBytes,
RequiresVerification = _pasteSettings.RequiresVerfication
});
var bytes = comment.IsCompressed ? _compressionService.Decompress(comment.Content) : comment.Content;
content = Encoding.UTF8.GetString(bytes);
}
Interaction? userReaction = null;
if (userInteractionMap != null && userInteractionMap.TryGetValue(comment.Id, out var mappedReaction))
userReaction = mappedReaction;
return new CommentResponseDto
{
Id = comment.Id,
ParentCommentID = comment.ParentCommentID,
Content = content,
StoredSize = comment.StoredSize,
OriginalSize = comment.OriginalSize,
IsCompressed = comment.IsCompressed,
CreatedAt = comment.CreatedAt,
UpdatedAt = comment.UpdatedAt,
Likes = comment.PositiveInteractionCount,
Dislikes = comment.NegativeInteractionCount,
UserReaction = userReaction,
Author =
comment.User != null && comment.User.Visibility == 0
? new UserSimpleDto
{
UID = comment.User.UID,
UUID = comment.User.UUID,
Username = comment.User.Username,
DisplayName = comment.User.DisplayName,
Visibility = comment.User.Visibility,
Roles = comment.User.Roles,
IsBanned = comment.User.IsBanned,
}
: null,
};
}
}
}
+389 -109
View File
@@ -2,69 +2,79 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.Report;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification;
namespace SharpbinV3.Server.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ReportController(ReportService reportService) : Controller
public class ReportController(
ReportService reportService,
PasteService pasteService,
UserService userService,
VerificationService verificationService
) : Controller
{
private readonly ReportService _reportService = reportService;
private readonly PasteService _pasteService = pasteService;
private readonly UserService _userService = userService;
private readonly VerificationService _verificationService = verificationService;
[Route("{reportId:int}")]
[HttpGet]
[EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportById(int reportId)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
var user = HttpContext.GetJwtUser()!;
var report = await reportService.GetReportByID(reportId);
var report = await _reportService.GetReportByID(reportId);
if (report is null)
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)
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
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
ReporterUsername = Username,
ReporterDisplayName = DisplayName,
TargetType = report.TargetType,
PasteId = report.Paste?.ID,
PasteTitle = report.Paste?.Title,
UserUUID = report.UserUUID,
TargetUsername = report.User?.Username,
TargetDisplayName = report.User?.DisplayName
});
return Ok(
new ReportResponseDto
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
ReporterUsername = Username,
ReporterDisplayName = DisplayName,
TargetType = report.TargetType,
PasteId = report.Paste?.ID,
PasteTitle = report.Paste?.Title,
UserUUID = report.UserUUID,
TargetUsername = report.User?.Username,
TargetDisplayName = report.User?.DisplayName,
}
);
}
[Route("{reportId:int}")]
[HttpPatch]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to update reports." });
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
var user = HttpContext.GetJwtUser()!;
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
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);
if (report is null)
return NotFound(new { success = false, message = "Report not found." });
@@ -88,27 +98,29 @@ namespace SharpbinV3.Server.Controllers
report.Description = request.Description;
report.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var updated = await reportService.UpdateReport(report);
var (Username, DisplayName) = await reportService.GetReporterInfo(updated.ReporterUUID);
var updated = await _reportService.UpdateReport(report);
var (Username, DisplayName) = await _reportService.GetReporterInfo(updated.ReporterUUID);
return Ok(new ReportResponseDto
{
ReportID = updated.ReportID,
Type = updated.Type,
Status = updated.Status,
Description = updated.Description,
CreatedAt = updated.CreatedAt,
UpdatedAt = updated.UpdatedAt,
ReporterUUID = updated.ReporterUUID,
ReporterUsername = Username,
ReporterDisplayName = DisplayName,
TargetType = updated.TargetType,
PasteId = updated.Paste?.ID,
PasteTitle = updated.Paste?.Title,
UserUUID = updated.UserUUID,
TargetUsername = updated.User?.Username,
TargetDisplayName = updated.User?.DisplayName
});
return Ok(
new ReportResponseDto
{
ReportID = updated.ReportID,
Type = updated.Type,
Status = updated.Status,
Description = updated.Description,
CreatedAt = updated.CreatedAt,
UpdatedAt = updated.UpdatedAt,
ReporterUUID = updated.ReporterUUID,
ReporterUsername = Username,
ReporterDisplayName = DisplayName,
TargetType = updated.TargetType,
PasteId = updated.Paste?.ID,
PasteTitle = updated.Paste?.Title,
UserUUID = updated.UserUUID,
TargetUsername = updated.User?.Username,
TargetDisplayName = updated.User?.DisplayName,
}
);
}
[Route("options")]
@@ -123,48 +135,41 @@ namespace SharpbinV3.Server.Controllers
[Route("pastes")]
[HttpGet]
[EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
var user = HttpContext.GetJwtUser()!;
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
var query = request with
{
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100),
UserUUID = null
};
var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null };
var reports = await reportService.GetPasteReports(query);
var totalCount = await reportService.GetReportCount(query);
var reports = await _reportService.GetPasteReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
return Ok(
new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
});
);
}
[Route("users")]
[HttpGet]
[EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
var user = HttpContext.GetJwtUser()!;
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
var query = request with
@@ -172,41 +177,42 @@ namespace SharpbinV3.Server.Controllers
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100),
PastePID = null,
PasteId = null
PasteId = null,
};
var reports = await reportService.GetUserReports(query);
var totalCount = await reportService.GetReportCount(query);
var reports = await _reportService.GetUserReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
return Ok(
new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
});
);
}
[Route("all")]
[HttpGet]
[EnableRateLimiting("Sliding")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> GetAllReports(
[FromQuery] Guid? reporterUuid,
[FromQuery] ReportTargetType? targetType,
[FromQuery] ReportType? type,
[FromQuery] ReportStatus? status,
[FromQuery] int page = 1,
[FromQuery] int pageSize = 20)
[FromQuery] int pageSize = 20
)
{
var user = HttpContext.GetJwtUser();
if (user is null)
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
var user = HttpContext.GetJwtUser()!;
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
var query = new ReportQuery
@@ -216,23 +222,297 @@ namespace SharpbinV3.Server.Controllers
Type = type,
Status = status,
Page = Math.Max(page, 1),
PageSize = Math.Clamp(pageSize, 1, 100)
PageSize = Math.Clamp(pageSize, 1, 100),
};
var reports = await reportService.GetReports(query);
var totalCount = await reportService.GetReportCount(query);
var reports = await _reportService.GetReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
return Ok(
new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
});
);
}
[HttpPost("pastes/{id}/report")]
[HttpPost("/api/paste/{id}/report")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var user = HttpContext.GetJwtUser()!;
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }))
return BadRequest(new { success = false, message = "Verification failed." });
Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description);
if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
return Ok(
new
{
success = true,
message = "Paste reported successfully.",
report = new ReportResponseDto
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType,
UserUUID = report.UserUUID,
},
}
);
}
[HttpPatch("pastes/{id}/report/{reportId}")]
[HttpPatch("/api/paste/{id}/report/{reportId}")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
report.Type = reportType;
report.Description = request.Description;
var updatedReport = await _reportService.UpdateReport(report);
if (updatedReport == null)
return StatusCode(500, new { success = false, message = "An error occurred while updating the report." });
return Ok(new { success = true, message = "Report updated successfully." });
}
[HttpDelete("pastes/{id}/report/{reportId}")]
[HttpDelete("/api/paste/{id}/report/{reportId}")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeletePasteReport(string id, int reportId)
{
var paste = await _pasteService.Get(id);
if (paste == null)
return NotFound(new { success = false, message = "Paste not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
return NotFound(new { success = false, message = "Report not found." });
var user = HttpContext.GetJwtUser()!;
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." });
bool result = await _reportService.DeleteReport(report);
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
return Ok(new { success = true, message = "Report deleted successfully." });
}
[HttpPost("users/{uuid}/report")]
[HttpPost("/api/user/{uuid}/report")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
{
var reporter = HttpContext.GetJwtUser()!;
var reportedUser = await _userService.GetByUUID(uuid);
if (reportedUser == null)
return NotFound(new { success = false, message = "User not found." });
if (reportedUser.UUID == reporter.UUID)
return BadRequest(new { success = false, message = "You cannot report yourself." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }))
return Unauthorized(new { success = false, message = "Invalid verification token." });
Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description);
if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while creating the report." });
return Ok(
new
{
success = true,
message = "User reported successfully.",
report = new ReportResponseDto
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType,
UserUUID = report.UserUUID,
},
}
);
}
[HttpPatch("users/{uuid}/report/{reportId}")]
[HttpPatch("/api/user/{uuid}/report/{reportId}")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
{
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
return NotFound(new { success = false, message = "Report not found." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
report.Type = reportType;
report.Description = request.Description ?? report.Description;
var updatedReport = await _reportService.UpdateReport(report);
if (updatedReport == null)
return StatusCode(500, new { success = false, message = "An error occurred while updating the report." });
return Ok(new { success = true, message = "Report updated successfully." });
}
[HttpDelete("users/{uuid}/report/{reportId}")]
[HttpDelete("/api/user/{uuid}/report/{reportId}")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
{
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
return NotFound(new { success = false, message = "Report not found." });
var result = await _reportService.DeleteReport(report);
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
return Ok(new { success = true, message = "Report deleted successfully." });
}
[HttpGet("users/{uuid}/reports")]
[HttpGet("/api/user/{uuid}/reports")]
[Authorize(Policy = "JwtOnly")]
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
{
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
if (!jwtUser.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
var reports = await _reportService.GetUserReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(
new
{
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
);
}
[HttpGet("users/{uuid}/reports/submitted")]
[HttpGet("/api/user/{uuid}/reports/submitted")]
[Authorize(Policy = "JwtOnly")]
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
{
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var isOwner = user.UUID == jwtUser.UUID;
var hasPrivilegedRole = jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator);
if (!isOwner && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
var query = request with { ReporterUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
var reports = await _reportService.GetReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(
new
{
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
}
);
}
}
}
+169 -267
View File
@@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.DTOs.Report;
@@ -19,8 +20,14 @@ namespace SharpbinV3.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UserController(UserService userService, AppDbContext db, TotpVerificationProvider totp,
VerificationService verificationService, ReportService reportServer, IOptions<AuthSettings> authSettings) : ControllerBase
public class UserController(
UserService userService,
AppDbContext db,
TotpVerificationProvider totp,
VerificationService verificationService,
ReportService reportServer,
IOptions<AuthSettings> authSettings
) : ControllerBase
{
private readonly UserService _userService = userService;
private readonly AppDbContext _db = db;
@@ -47,56 +54,124 @@ namespace SharpbinV3.Server.Controllers
[Authorize]
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
{
var userUUID = HttpContext.User?.FindFirst("uuid")?.Value;
if (userUUID is null)
return Unauthorized(new { success = false, message = "Invalid token." });
var userUUID = HttpContext.User.FindFirst("uuid")!.Value;
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
}
[HttpGet("uuid/{uuid}/requirements")]
[Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> GetUserActionRequirements(Guid uuid, [FromQuery] SecurityAction action)
{
var jwtUser = HttpContext.GetJwtUser()!;
var targetUser = await _userService.GetByUUID(uuid);
if (targetUser == null)
return NotFound(new { success = false, message = "User not found." });
if (
(targetUser.Roles.HasFlag(Role.Admin) && !jwtUser.Roles.HasFlag(Role.Admin))
|| (!jwtUser.Roles.HasFlag(Role.Admin) && targetUser.UUID != jwtUser.UUID)
)
return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." });
if (action == SecurityAction.UpdateRoles && !jwtUser.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." });
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
{
return Ok(
new
{
success = true,
action,
requiresTotp = false,
blocked = true,
message = "2FA is required to perform this action.",
}
);
}
return Ok(
new
{
success = true,
action,
requiresTotp = jwtUser.TotpEnabled,
blocked = false,
message = jwtUser.TotpEnabled ? "TOTP verification is required." : "No TOTP verification required.",
}
);
}
[HttpPatch("uuid/{uuid}")]
[Authorize]
[Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Strict")]
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var jwtUser = HttpContext.GetJwtUser()!;
var reqUser = await _userService.GetByUUID(uuid);
if (reqUser == null)
return NotFound(new { success = false, message = "User not found." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
if ((user.Roles.Contains(255) && !jwtUser.Roles.Contains(255)) || (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID))
if (
(user.Roles.HasFlag(Role.Admin) && !reqUser.Roles.HasFlag(Role.Admin))
|| (!reqUser.Roles.HasFlag(Role.Admin) && user.UUID != reqUser.UUID)
)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
bool isSensitiveUpdate =
(updatedUser.Roles.HasValue && updatedUser.Roles.Value != user.Roles) // updating roles
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != user.IsBanned) // updating ban status
|| (
updatedUser.Email != null && updatedUser.Email != user.Email // updating email
);
if (reqUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA && isSensitiveUpdate)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
if (isSensitiveUpdate && jwtUser.TotpEnabled)
{
if (
string.IsNullOrEmpty(updatedUser.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = reqUser.UUID, Code = updatedUser.TotpCode })
)
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
if (user.Roles.HasFlag(Role.Admin) && !reqUser.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (
updatedUser.Roles.HasValue
&& user.Roles.HasFlag(Role.Admin)
&& !updatedUser.Roles.Value.HasFlag(Role.Admin)
&& reqUser.UID > user.UID
)
// prevents demoting of other older admins by newer admins
// allows self demotion in case of compromisation
{
return StatusCode(403, new { success = false, message = "You cannot remove the admin role from this user." });
}
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self
if (reqUser.Roles.HasFlag(Role.Admin) || user.UUID == reqUser.UUID)
{
user.Email = updatedUser.Email ?? user.Email;
user.Visibility = updatedUser.Visibility ?? user.Visibility;
}
if (jwtUser.Roles.Contains(255))
if (reqUser.Roles.HasFlag(Role.Admin))
{
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled)
{
if (string.IsNullOrEmpty(updatedUser.TotpCode) || !await _totp.VerifyAsync(new VerificationContext
{
UserUUID = jwtUser.UUID,
Code = updatedUser.TotpCode
}))
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
user.Roles = updatedUser.Roles ?? user.Roles;
user.IsBanned = updatedUser.IsBanned ?? user.IsBanned;
}
await _db.SaveChangesAsync();
@@ -104,41 +179,39 @@ namespace SharpbinV3.Server.Controllers
}
[HttpDelete("uuid/{uuid}")]
[Authorize(Policy = "AuthAndNotBanned")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var jwtUser = HttpContext.GetJwtUser()!;
var user = await _userService.GetByUUID(uuid);
if (user == null)
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." });
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." });
if (user.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You cannot delete an admin user." });
if (jwtUser.TotpEnabled)
{
if (string.IsNullOrEmpty(dto.TotpCode) || !await _totp.VerifyAsync(new VerificationContext
{
UserUUID = jwtUser.UUID,
Code = dto.TotpCode
}))
if (
string.IsNullOrEmpty(dto.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = dto.TotpCode })
)
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
else
{
if (string.IsNullOrEmpty(dto.Token) || !await _verificationService.VerifyAsync(new VerificationContext
{
Token = dto.Token,
Ip = HttpContext.GetRequestIP()
}))
if (
string.IsNullOrEmpty(dto.Token)
|| !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() })
)
{
return Unauthorized(new { message = "Invalid verification token." });
}
@@ -149,199 +222,16 @@ namespace SharpbinV3.Server.Controllers
return Ok(new { message = "User deleted successfully." });
}
[HttpPost]
[Route("{uuid}/report")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
{
var reporter = HttpContext.GetJwtUser();
if (reporter == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var reportedUser = await _userService.GetByUUID(uuid);
if (reportedUser == null)
return NotFound(new { success = false, message = "User not found." });
if (reportedUser.UUID == reporter.UUID)
return BadRequest(new { success = false, message = "You cannot report yourself." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext
{
Token = request.VerificationToken,
Ip = HttpContext.GetRequestIP()
}))
return Unauthorized(new { success = false, message = "Invalid verification token." });
Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description);
if (report == null)
return StatusCode(500, new { success = false, message = "An error occurred while creating the report." });
return Ok(new
{
success = true,
message = "User reported successfully.",
report = new ReportResponseDto
{
ReportID = report.ReportID,
Type = report.Type,
Status = report.Status,
Description = report.Description,
CreatedAt = report.CreatedAt,
UpdatedAt = report.UpdatedAt,
ReporterUUID = report.ReporterUUID,
TargetType = report.TargetType,
UserUUID = report.UserUUID
}
});
}
[HttpPatch]
[Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
return NotFound(new { success = false, message = "Report not found." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
report.Type = reportType;
report.Description = request.Description ?? report.Description;
await _db.SaveChangesAsync();
return Ok(new { success = true, message = "Report updated successfully." });
}
[HttpDelete]
[Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var report = await _reportService.GetReportByID(reportId);
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
return NotFound(new { success = false, message = "Report not found." });
var result = await _reportService.DeleteReport(report);
if (!result)
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
return Ok(new { success = true, message = "Report deleted successfully." });
}
[HttpGet]
[Authorize]
[Route("{uuid}/reports")]
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
if (!jwtUser.Roles.Any(r => r == 1 || r == 255))
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
var query = request with
{
UserUUID = user.UUID,
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100)
};
var reports = await _reportService.GetUserReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
}
});
}
[HttpGet]
[Authorize]
[Route("{uuid}/reports/submitted")]
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
{
var jwtUser = HttpContext.GetJwtUser();
if (jwtUser == null)
return Unauthorized(new { success = false, message = "Invalid token." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var isOwner = user.UUID == jwtUser.UUID;
var hasPrivilegedRole = jwtUser.Roles.Any(r => r == 1 || r == 255);
if (!isOwner && !hasPrivilegedRole)
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
var query = request with
{
ReporterUUID = user.UUID,
Page = Math.Max(request.Page, 1),
PageSize = Math.Clamp(request.PageSize, 1, 100)
};
var reports = await _reportService.GetReports(query);
var totalCount = await _reportService.GetReportCount(query);
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
return Ok(new
{
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages
}
});
}
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
{
var isAuthenticatedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isAuthenticatedUser)
{
if (user.Visibility == 2)
if (user.Visibility == Visibility.Private && (!user.Roles.HasFlag(Role.Admin) || !user.Roles.HasFlag(Role.Moderator)))
return NotFound();
else if (user.Visibility != 1)
pasteQuery = pasteQuery.Where(p => p.Visibility == 0);
else if (user.Visibility != Visibility.Unlisted)
pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
}
if (page < 1)
@@ -360,14 +250,15 @@ namespace SharpbinV3.Server.Controllers
{
ID = p.ID,
UUID = p.UUID,
CreatedAt = p.CreatedAt,
Title = p.Title,
Syntax = p.Syntax,
Size = p.Size,
TrueSize = p.TrueSize,
OriginalSize = p.OriginalSize,
StoredSize = p.StoredSize,
Views = p.Views,
Visibility = p.Visibility,
EditedAt = p.EditedAt,
ExpiresAt = p.ExpiresAt
ExpiresAt = p.ExpiresAt,
})
.ToListAsync();
@@ -376,59 +267,70 @@ namespace SharpbinV3.Server.Controllers
Page = page,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = totalPages
TotalPages = totalPages,
};
if (isAuthenticatedUser)
{
var reports = await _reportService.GetReports(new ReportQuery
{
ReporterUUID = user.UUID,
Page = page,
PageSize = pageSize
});
var reports = await _reportService.GetReports(
new ReportQuery
{
ReporterUUID = user.UUID,
Page = page,
PageSize = pageSize,
}
);
var reportsCount = await _reportService.GetReportCountByReporter(user.UUID);
return Ok(new
return Ok(
new
{
User = new UserResponseDto
{
UID = user.UID,
Username = user.Username,
UUID = user.UUID,
CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName,
Email = user.Email,
EmailVerified = user.EmailVerified,
LastLogin = user.LastLogin,
Roles = user.Roles,
IsBanned = user.IsBanned,
Visibility = user.Visibility,
},
Pastes = pastes,
Reports = reports,
Pagination = pagination,
ReportsPagination = new
{
Page = page,
PageSize = pageSize,
TotalCount = reportsCount,
TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize),
},
}
);
}
return Ok(
new
{
User = new UserResponseDto
User = new UserSimpleDto
{
UID = user.UID,
Username = user.Username,
UUID = user.UUID,
CreatedAt = user.CreatedAt,
DisplayName = user.DisplayName,
Email = user.Email,
LastLogin = user.LastLogin,
Roles = user.Roles,
Visibility = user.Visibility
IsBanned = user.IsBanned,
Visibility = user.Visibility,
},
Pastes = pastes,
Reports = reports,
Pagination = pagination,
ReportsPagination = new
{
Page = page,
PageSize = pageSize,
TotalCount = reportsCount,
TotalPages = (int)Math.Ceiling(reportsCount / (double)pageSize)
}
});
}
return Ok(new
{
User = new UserSimpleDto
{
UID = user.UID,
Username = user.Username,
UUID = user.UUID,
DisplayName = user.DisplayName,
Roles = user.Roles,
Visibility = user.Visibility
},
Pastes = pastes,
Pagination = pagination
});
}
);
}
}
}
@@ -0,0 +1,10 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class ApiKeyListItemDto
{
public required string Name { get; set; }
public required Guid UUID { get; set; }
public required long CreatedAt { get; set; }
public long? LastUsedAt { get; set; }
}
}
@@ -0,0 +1,10 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class ApiKeyResponseDto
{
public required string Key { get; set; }
public required string Name { get; set; }
public required Guid UUID { get; set; }
public required long CreatedAt { get; set; }
}
}
@@ -0,0 +1,7 @@
namespace SharpbinV3.Server.DTOs.ApiKey
{
public sealed class CreateApiKeyRequest
{
public required string Name { get; set; }
}
}
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Auth
{
[Required]
public required string Token { get; set; }
[Required]
public required string RefreshToken { get; set; }
}
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Auth
{
[JsonPropertyName("success")]
public bool Success { get; set; }
[JsonPropertyName("error-codes")]
public string[]? ErrorCodes { get; set; }
}
@@ -0,0 +1,53 @@
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.User;
namespace SharpbinV3.Server.DTOs.Paste
{
public class CreateCommentDto
{
public string Content { get; set; } = string.Empty;
public long? ParentCommentID { get; set; }
}
public class ReactToCommentDto
{
public Interaction? Reaction { get; set; }
}
public class ReactToPasteDto
{
public Interaction? Reaction { get; set; }
}
public class CommentResponseDto
{
public long Id { get; set; }
public long? ParentCommentID { get; set; }
public string? Content { get; set; }
public long StoredSize { get; set; }
public long OriginalSize { get; set; }
public bool IsCompressed { get; set; }
public long CreatedAt { get; set; }
public long? UpdatedAt { get; set; }
public int Likes { get; set; }
public int Dislikes { get; set; }
public Interaction? UserReaction { get; set; }
public UserSimpleDto? Author { get; set; }
}
public class CommentReactionResponseDto
{
public long CommentID { get; set; }
public int Likes { get; set; }
public int Dislikes { get; set; }
public Interaction? UserReaction { get; set; }
}
public class PasteReactionResponseDto
{
public string PasteID { get; set; } = string.Empty;
public int Likes { get; set; }
public int Dislikes { get; set; }
public Interaction? UserReaction { get; set; }
}
}
@@ -1,3 +1,4 @@
using SharpbinV3.Server.Data.Enums;
using SharpbinV3.Server.DTOs.User;
namespace SharpbinV3.Server.DTOs.Paste
@@ -6,16 +7,20 @@ namespace SharpbinV3.Server.DTOs.Paste
{
public string ID { get; set; } = string.Empty;
public Guid UUID { get; set; }
public long CreatedAt { get; set; }
public string? Title { get; set; }
public string? Syntax { get; set; }
public long Size { get; set; }
public long TrueSize { get; set; }
public long StoredSize { get; set; }
public long OriginalSize { get; set; }
public bool IsCompressed { get; set; }
public int Views { get; set; }
public int Visibility { get; set; }
public Visibility Visibility { get; set; }
public long? EditedAt { get; set; }
public long ExpiresAt { get; set; }
public int? ReportCount { get; set; }
public int Likes { get; set; }
public int Dislikes { get; set; }
public Interaction? UserReaction { get; set; }
public UserSimpleDto? Author { get; set; }
}
@@ -23,10 +28,12 @@ namespace SharpbinV3.Server.DTOs.Paste
{
public string ID { get; set; } = string.Empty;
public Guid UUID { get; set; }
public long CreatedAt { get; set; }
public bool IsCompressed { get; set; }
public long Size { get; set; }
public long TrueSize { get; set; }
public long StoredSize { get; set; }
public long OriginalSize { get; set; }
public long ExpiresAt { get; set; }
public Visibility Visibility { get; set; }
}
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 string? Title { get; set; }
public string? Syntax { get; set; }
public int? Visibility { get; set; }
public Visibility? Visibility { get; set; }
public long? ExpiresAt { get; set; }
}
}
+2 -1
View File
@@ -7,8 +7,9 @@ namespace SharpbinV3.Server.DTOs.Report
[Required]
[MinLength(12), MaxLength(1000)]
public string Description { get; set; } = string.Empty;
[Required]
public string ReportType { get; set; } = string.Empty; // e.g., "Spam", "Abuse", etc.
public string ReportType { get; set; } = string.Empty;
public string ReportStatus { get; set; } = "Open";
public string? VerificationToken { get; set; }
}
@@ -6,7 +6,7 @@ namespace SharpbinV3.Server.DTOs.Report
{
public Guid? ReporterUUID { get; init; }
public Guid? UserUUID { get; init; }
public int? PastePID { get; init; }
public long? PastePID { get; init; }
public string? PasteId { get; init; }
public ReportTargetType? TargetType { get; init; }
public ReportType? Type { get; init; }
@@ -6,6 +6,7 @@ namespace SharpbinV3.Server.DTOs.Report
{
public string? Status { get; set; }
public string? Type { get; set; }
[MaxLength(1000)]
public string? Description { get; set; }
}
@@ -7,6 +7,7 @@ namespace SharpbinV3.Server.DTOs.User
[StringLength(50, MinimumLength = 3)]
public string? Username { get; set; }
public string? Email { get; set; }
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
public string? Token { get; set; }
+21 -7
View File
@@ -3,7 +3,7 @@ using System.Text.RegularExpressions;
namespace SharpbinV3.Server.DTOs
{
public partial class RegisterUserDto
public partial class RegisterUserDto : IValidatableObject
{
[Required]
[StringLength(50, MinimumLength = 3)]
@@ -18,22 +18,32 @@ namespace SharpbinV3.Server.DTOs
public string? DisplayName { get; set; }
public string? Token { get; set; }
public IEnumerable<ValidationResult> Validate()
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (!ValidateUsername().IsMatch(Username))
results.Add(new ValidationResult("Username can only contain letters, numbers, underscores, and dots.", [nameof(Username)]));
if (!ValidatePassword().IsMatch(Password))
results.Add(new ValidationResult("Password should have at least 8 characters, including uppercase, lowercase, and digits.", [nameof(Password)]));
results.Add(
new ValidationResult(
"Password should have at least 8 characters, including uppercase, lowercase, and digits.",
[nameof(Password)]
)
);
if (DisplayName != null)
if (DisplayName != null && DisplayName.Length > 0)
{
if (DisplayName.Length < 3 || DisplayName.Length > 26)
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)]));
if (!ValidateUsername().IsMatch(DisplayName))
results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)]));
if (!ValidateDisplayname().IsMatch(DisplayName))
results.Add(
new ValidationResult(
"DisplayName can only contain alphanumeric characters, underscores, periods, and spaces (no leading or trailing spaces).",
[nameof(DisplayName)]
)
);
}
if (Email != null)
if (Email != null && Email.Length > 0)
{
var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(Email))
@@ -44,6 +54,10 @@ namespace SharpbinV3.Server.DTOs
[GeneratedRegex("^[A-Za-z0-9_.]+$")]
private static partial Regex ValidateUsername();
[GeneratedRegex("^[A-Za-z0-9_.]+(?: [A-Za-z0-9_.]+)*$")]
private static partial Regex ValidateDisplayname();
[GeneratedRegex("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$")]
public static partial Regex ValidatePassword();
}
+23 -21
View File
@@ -1,53 +1,55 @@
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs
{
public partial class UpdateUserDto
public partial class UpdateUserDto : IValidatableObject
{
public string? DisplayName { get; set; }
public string? Email { get; set; }
public int? Visibility { get; set; } = 0;
public int[]? Roles { get; set; }
public Visibility? Visibility { get; set; } = Data.Enums.Visibility.Public;
public Role? Roles { get; set; }
public bool? IsBanned { get; set; }
public string? TotpCode { get; set; }
public IEnumerable<ValidationResult> Validate()
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var results = new List<ValidationResult>();
if (DisplayName != null)
if (DisplayName != null && DisplayName.Length > 0)
{
if (DisplayName.Length < 3 || DisplayName.Length > 26)
results.Add(new ValidationResult("DisplayName must be between 3 and 26 characters.", [nameof(DisplayName)]));
if (!ValidateDisplayname().IsMatch(DisplayName))
results.Add(new ValidationResult("DisplayName can only contain letters, numbers, underscores, and dots.", [nameof(DisplayName)]));
results.Add(
new ValidationResult(
"DisplayName can only contain alphanumeric characters, underscores, periods, and spaces (no leading or trailing spaces).",
[nameof(DisplayName)]
)
);
}
if (Email != null)
if (Email != null && Email.Length > 0)
{
var emailAttribute = new EmailAddressAttribute();
if (!emailAttribute.IsValid(Email))
results.Add(new ValidationResult("Invalid email format.", [nameof(Email)]));
}
if (Visibility != null)
if (Visibility != null && Visibility.HasValue)
{
if (Visibility < 0 || Visibility > 2)
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)]));
if (!Enum.IsDefined(typeof(Visibility), Visibility.Value))
results.Add(new ValidationResult($"Invalid visibility: {Visibility.Value}.", [nameof(Visibility)]));
}
if (Roles != null)
if (Roles != null && Roles.HasValue)
{
if (Roles.Length == 0)
results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)]));
int[] validRoles = [0, 1, 255, 403];
foreach (var role in Roles)
{
if (!validRoles.Contains(role))
results.Add(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)]));
}
int validBits = Enum.GetValues(typeof(Role)).Cast<Role>().Aggregate(0, (acc, role) => acc | (int)role);
if ((((int)Roles.Value) & validBits) != (int)Roles.Value || Roles.Value == 0)
results.Add(new ValidationResult($"Invalid role: {Roles.Value}.", [nameof(Roles)]));
}
return results;
}
[GeneratedRegex("^[A-Za-z0-9_.]+$")]
[GeneratedRegex("^[A-Za-z0-9_.]+(?: [A-Za-z0-9_.]+)*$")]
private static partial Regex ValidateDisplayname();
}
}
@@ -1,18 +1,24 @@
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.DTOs.User
{
public class UserSimpleDto
{
public int? UID { get; set; }
public long? UID { get; set; }
public Guid UUID { get; set; }
public long CreatedAt { get; set; }
public string Username { get; set; } = string.Empty;
public string? DisplayName { get; set; }
public int[] Roles { get; set; } = [];
public int Visibility { get; set; }
public Role Roles { get; set; } = Role.User;
public bool IsBanned { get; set; } = false;
public Visibility Visibility { get; set; }
}
public class UserResponseDto : UserSimpleDto
{
public string? Email { get; set; }
public bool EmailVerified { get; set; } = false;
public long? LastLogin { get; set; }
}
}
+41
View File
@@ -7,10 +7,15 @@ namespace SharpbinV3.Server.Data
{
public DbSet<User> Users => Set<User>();
public DbSet<Paste> Pastes => Set<Paste>();
public DbSet<PasteInteraction> PasteInteractions => Set<PasteInteraction>();
public DbSet<PasteView> PasteViews => Set<PasteView>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
public DbSet<Report> Reports => Set<Report>();
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
public DbSet<EmailVerificationToken> EmailVerificationTokens => Set<EmailVerificationToken>();
public DbSet<Comment> Comments => Set<Comment>();
public DbSet<CommentInteraction> CommentInteractions => Set<CommentInteraction>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -56,6 +61,42 @@ namespace SharpbinV3.Server.Data
.WithMany(u => u.Reports)
.HasForeignKey(r => r.UserUUID)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Report>()
.HasOne<Comment>()
.WithMany(c => c.Reports)
.HasForeignKey(r => r.CommentID)
.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);
modelBuilder.Entity<Comment>()
.HasOne(c => c.ParentComment)
.WithMany(c => c.Replies)
.HasForeignKey(c => c.ParentCommentID)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<CommentInteraction>()
.HasOne(ci => ci.Comment)
.WithMany(c => c.Interactions)
.HasForeignKey(ci => ci.CommentID)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<PasteInteraction>()
.HasOne(pi => pi.Paste)
.WithMany(p => p.Interactions)
.HasForeignKey(pi => pi.PasteID)
.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,37 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SharpbinV3.Server.Data.Entities
{
public class Comment
{
[Key]
public long Id { get; set; }
public long PastePID { get; set; }
public long? ParentCommentID { get; set; }
[MaxLength(5000)]
public byte[]? Content { get; set; } = null!; // compressed & decompressed server side, if deleted then null
public long StoredSize { get; set; }
public long OriginalSize { get; set; }
public bool IsCompressed { get; set; } = false;
public Guid UserUUID { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
public long? UpdatedAt { get; set; }
public Paste Paste { get; set; } = null!;
public User User { get; set; } = null!;
public Comment? ParentComment { get; set; }
public List<CommentInteraction> Interactions { get; set; } = [];
public List<Comment> Replies { get; set; } = [];
public List<Report> Reports { get; set; } = [];
[NotMapped]
public int PositiveInteractionCount { get; set; }
[NotMapped]
public int NegativeInteractionCount { get; set; }
}
}
@@ -0,0 +1,20 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.Data.Entities
{
[Index(nameof(CommentID), nameof(UserUUID), IsUnique = true)]
[Index(nameof(CommentID), nameof(Type))]
public class CommentInteraction
{
[Key]
public long Id { get; set; }
public long CommentID { get; set; }
public Guid UserUUID { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
public Interaction Type { get; set; }
public Comment Comment { get; set; } = null!;
}
}
@@ -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;
}
}
+19 -8
View File
@@ -1,19 +1,23 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data.Enums;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SharpbinV3.Server.Data.Entities
{
[Index(nameof(PID), IsUnique = true)]
[Index(nameof(UUID), IsUnique = true)]
[Index(nameof(UUID))]
[Index(nameof(ID), IsUnique = true)]
[Index(nameof(AuthorUUID))]
[Index(nameof(ExpiresAt))]
[Index(nameof(Visibility))]
[Index(nameof(Syntax))]
[Index(nameof(Views))]
[Index(nameof(StoredSize))]
public sealed class Paste
{
[Key]
public int PID { get; set; }
public required Guid UUID { get; set; } // uuid v7 includes timestamp, this counts as created at
public long PID { get; set; }
public required Guid UUID { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public required string ID { get; set; }
public string? Title { get; set; }
@@ -23,17 +27,24 @@ namespace SharpbinV3.Server.Data.Entities
public long? EditedAt { get; set; }
public required byte[] Content { get; set; }
public long Size { get; set; } // stored size (may be compressed)
public long TrueSize { get; set; } // uncompressed size
public long StoredSize { get; set; }
public long OriginalSize { get; set; }
public bool IsCompressed { get; set; } = false;
public int Views { 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 List<PasteView> PasteViews { get; set; } = [];
public List<Report> Reports { get; set; } = [];
public List<Comment> Comments { get; set; } = [];
public List<PasteInteraction> Interactions { get; set; } = [];
[NotMapped]
public int PositiveInteractionCount { get; set; }
[NotMapped]
public int NegativeInteractionCount { get; set; }
}
}
@@ -0,0 +1,20 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using SharpbinV3.Server.Data.Enums;
namespace SharpbinV3.Server.Data.Entities
{
[Index(nameof(PasteID), nameof(UserUUID), IsUnique = true)]
[Index(nameof(PasteID), nameof(Type))]
public class PasteInteraction
{
[Key]
public long Id { get; set; }
public long PasteID { get; set; }
public Guid UserUUID { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
public Interaction Type { get; set; }
public Paste Paste { get; set; } = null!;
}
}
+2 -1
View File
@@ -8,7 +8,8 @@ namespace SharpbinV3.Server.Data.Entities
{
[Key]
public int Id { get; set; }
public int PastePID { get; set; }
public long PastePID { get; set; }
[MaxLength(64)]
public string ViewerHash { get; set; } = null!;
public long ViewedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
+6 -7
View File
@@ -25,8 +25,9 @@ namespace SharpbinV3.Server.Data.Entities
public Guid ReporterUUID { get; set; }
public ReportTargetType TargetType { get; set; }
public int? PastePID { get; set; }
public long? PastePID { get; set; }
public Guid? UserUUID { get; set; }
public long? CommentID { get; set; }
public Paste? Paste { get; set; }
public User? User { get; set; }
@@ -36,22 +37,20 @@ namespace SharpbinV3.Server.Data.Entities
public enum ReportStatus
{
Open,
InProgress,
Resolved,
Closed
}
public enum ReportType
{
Spam,
Abuse,
InappropriateContent,
CopyrightViolation,
IllegalContent,
Fraud,
Other
}
public enum ReportTargetType
{
Paste,
User
User,
Comment
}
}
+23 -4
View File
@@ -1,27 +1,46 @@
using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data.Enums;
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
[Flags]
public enum Role
{
User = 1,
Moderator = 2,
Admin = 4
}
[Index(nameof(UID))]
[Index(nameof(UUID), IsUnique = true)]
[Index(nameof(Username), IsUnique = true)]
public sealed class User
{
public int? UID { get; set; }
public long? UID { get; set; }
[Key]
public required Guid UUID { get; set; } = Guid.CreateVersion7(); // uuid v7 includes timestamp
public required Guid UUID { get; set; } = Guid.CreateVersion7();
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public required string Username { get; set; }
public required string PasswordHash { get; set; }
public string? Email { get; set; }
public bool EmailVerified { get; set; } = false;
public string? DisplayName { get; set; }
public long? LastLogin { get; set; }
public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public Role Roles { get; set; } = Role.User;
public bool IsBanned { get; set; } = false;
public Visibility Visibility { get; set; } = Visibility.Public;
public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = [];
public List<Report> Reports { get; set; } = [];
public List<ApiKey> ApiKeys { get; set; } = [];
public List<EmailVerificationToken> EmailVerificationTokens { get; set; } = [];
public List<Comment> Comments { get; set; } = [];
public UserTotp? Totp { get; set; }
}
}
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.Data.Enums
{
public enum Interaction
{
Positive = 1,
Negative = 2
}
}
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.Data.Enums
{
public enum SecurityAction
{
UpdateRoles = 1,
DeleteUser = 2
}
}
@@ -0,0 +1,9 @@
namespace SharpbinV3.Server.Data.Enums
{
public enum Visibility
{
Public = 0,
Unlisted = 1,
Private = 2
}
}

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