Compare commits

...
Author SHA1 Message Date
dependabot[bot] 18e8154248 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: [@humanfs/node](https://github.com/humanwhocodes/humanfs/tree/HEAD/packages/node) and [fflate](https://github.com/101arrowz/fflate).


Updates `@humanfs/node` from 0.16.7 to 0.16.8
- [Release notes](https://github.com/humanwhocodes/humanfs/releases)
- [Changelog](https://github.com/humanwhocodes/humanfs/blob/main/packages/node/CHANGELOG.md)
- [Commits](https://github.com/humanwhocodes/humanfs/commits/node-v0.16.8/packages/node)

Updates `fflate` from 0.7.4 to 0.7.5
- [Release notes](https://github.com/101arrowz/fflate/releases)
- [Changelog](https://github.com/101arrowz/fflate/blob/master/CHANGELOG.md)
- [Commits](https://github.com/101arrowz/fflate/commits)

---
updated-dependencies:
- dependency-name: "@humanfs/node"
  dependency-version: 0.16.8
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: fflate
  dependency-version: 0.7.5
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-04 22:23:22 +00:00
whoswhip 4e8187c186 Merge pull request #24 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-275026e82a
chore(deps-dev): bump the npm_and_yarn group across 1 directory with 3 updates
2026-09-04 18:21:27 -04:00
dependabot[bot] 5c8f81b951 chore(deps-dev): bump the npm_and_yarn group across 1 directory with 3 updates
Bumps the npm_and_yarn group with 3 updates in the /SharpbinV3.Client directory: [brace-expansion](https://github.com/juliangruber/brace-expansion), [js-yaml](https://github.com/nodeca/js-yaml) and [postcss-selector-parser](https://github.com/postcss/postcss-selector-parser).


Updates `brace-expansion` from 1.1.12 to 1.1.18
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.12...v1.1.18)

Updates `js-yaml` from 4.2.0 to 4.3.2
- [Changelog](https://github.com/nodeca/js-yaml/blob/4.3.2/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.2.0...4.3.2)

Updates `postcss-selector-parser` from 7.1.1 to 7.1.5
- [Release notes](https://github.com/postcss/postcss-selector-parser/releases)
- [Changelog](https://github.com/postcss/postcss-selector-parser/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss-selector-parser/compare/v7.1.1...7.1.5)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.18
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: js-yaml
  dependency-version: 4.3.2
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: postcss-selector-parser
  dependency-version: 7.1.5
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-03 03:23:33 +00:00
whoswhip e8f2050eb1 chore(deps): update npm packages, add sharp types 2026-09-02 23:21:48 -04:00
whoswhip db492054f7 Merge pull request #22 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-360cad5ee5
chore(deps): bump dompurify from 3.4.9 to 3.4.11 in /SharpbinV3.Client in the npm_and_yarn group across 1 directory
2026-07-16 17:35:46 -04:00
dependabot[bot] 936d74facf chore(deps): bump dompurify
Bumps the npm_and_yarn group with 1 update in the /SharpbinV3.Client directory: [dompurify](https://github.com/cure53/DOMPurify).


Updates `dompurify` from 3.4.9 to 3.4.11
- [Release notes](https://github.com/cure53/DOMPurify/releases)
- [Commits](https://github.com/cure53/DOMPurify/compare/3.4.9...3.4.11)

---
updated-dependencies:
- dependency-name: dompurify
  dependency-version: 3.4.11
  dependency-type: direct:production
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-06 17:12:03 +00:00
whoswhip 500a6cfe76 Merge pull request #21 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-cfff62663e
chore(deps): bump the npm_and_yarn group across 1 directory with 2 updates
2026-07-06 13:10:48 -04:00
whoswhip 1bfc5dbbc4 style: improve comments overall styling 2026-06-21 23:24:15 -04:00
whoswhip 6cadc0b74d feat: improve rate limit partition keys + less strict limits 2026-06-18 21:46:43 -04:00
whoswhip 6ed2974e42 feat: allow staff members to see user's unlisted pastes; show dislikes in the paste lists 2026-06-18 21:28:48 -04:00
whoswhip d4976ac9aa feat: password resets
fix: frontend docker file
chore: format via csharpier again
2026-06-18 21:15:34 -04:00
whoswhip 67ccee736a chore: format via csharpier 2026-06-17 22:32:31 -04:00
whoswhip 045a1934d8 fix: add docker entrypoint sccript 2026-06-17 22:27:44 -04:00
whoswhip d16f1f872f fix: lower vulnerabilities + harden docker setup
also includes a github workflow
2026-06-17 22:18:55 -04:00
whoswhip 4f5ca9a069 chore: bump rate limits 2026-06-17 22:06:18 -04:00
whoswhip 6a7b8653dc fix: multiple vulnerabilities 2026-06-17 21:43:41 -04:00
whoswhip 6c810b07b7 fix: enhance user update permissions and authentication checks 2026-06-17 21:32:40 -04:00
whoswhip df39f2bd46 chore: format code via prettier & csharpier 2026-06-17 20:28:58 -04:00
whoswhip f2c67ae367 fix: prevent admins and moderators from being reported 2026-06-17 20:27:59 -04:00
dependabot[bot] a41048afe7 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: [dompurify](https://github.com/cure53/DOMPurify) and [js-yaml](https://github.com/nodeca/js-yaml).


Updates `dompurify` from 3.4.0 to 3.4.9
- [Release notes](https://github.com/cure53/DOMPurify/releases)
- [Commits](https://github.com/cure53/DOMPurify/compare/3.4.0...3.4.9)

Updates `js-yaml` from 4.1.1 to 4.2.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/commits)

---
updated-dependencies:
- dependency-name: dompurify
  dependency-version: 3.4.9
  dependency-type: direct:production
  dependency-group: npm_and_yarn
- dependency-name: js-yaml
  dependency-version: 4.2.0
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-16 18:06:48 +00:00
whoswhip ed582afe0e Merge pull request #20 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-c3db33d60f
chore(deps): bump the npm_and_yarn group across 1 directory with 2 updates
2026-06-16 13:58:35 -04:00
dependabot[bot] 3b8039e036 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: [esbuild](https://github.com/evanw/esbuild) and [ws](https://github.com/websockets/ws).


Removes `esbuild`

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

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-15 16:44:39 +00:00
whoswhip 7a4c0a9b4d Merge pull request #19 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-f148cc1241
chore(deps): bump esbuild from 0.27.2 to 0.27.7 in /SharpbinV3.Client in the npm_and_yarn group across 1 directory
2026-06-15 12:42:47 -04:00
whoswhip 61efbf8b04 fix: show uncompressed size in stats
also renamed variables to make it more readable
2026-06-14 12:40:19 -04:00
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
119 changed files with 11208 additions and 2200 deletions
+2
View File
@@ -0,0 +1,2 @@
# These are supported funding model platforms
ko_fi: whoswhip
+35
View File
@@ -0,0 +1,35 @@
name: CI
on:
pull_request:
push:
branches:
- main
jobs:
backend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: 10.0.x
- run: dotnet restore SharpbinV3.Server/SharpbinV3.Server.csproj
- run: dotnet build SharpbinV3.Server/SharpbinV3.Server.csproj --configuration Release --no-restore
frontend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: SharpbinV3.Client
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
cache-dependency-path: SharpbinV3.Client/package-lock.json
- run: npm ci
- run: npm run check
- run: npm run lint
- run: npm run build
+13 -3
View File
@@ -10,7 +10,17 @@ RUN npm run build
FROM node:20-alpine as runner
WORKDIR /app
COPY --from=build /app .
RUN apk add --no-cache wget
ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=5173
COPY package.json package-lock.json ./
RUN apk add --no-cache wget libstdc++ \
&& apk add --no-cache --virtual .build-deps python3 make g++ \
&& npm ci --omit=dev \
&& npm cache clean --force \
&& apk del .build-deps
COPY --from=build --chown=node:node /app/build ./build
RUN chown -R node:node /app
EXPOSE 5173
CMD ["npm", "run", "preview", "--", "--host", "0.0.0.0", "--port", "5173"]
USER node
CMD ["node", "build"]
+846 -870
View File
File diff suppressed because it is too large Load Diff
+8 -7
View File
@@ -18,14 +18,15 @@
"@eslint/compat": "^1.4.0",
"@eslint/js": "^9.39.1",
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/kit": "^2.50.0",
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17",
"@sveltejs/kit": "^2.60.1",
"@sveltejs/vite-plugin-svelte": "^7.1.2",
"@tailwindcss/vite": "^4.3.1",
"@types/better-sqlite3": "^7.6.13",
"@types/jsdom": "^27.0.0",
"@types/node": "^22",
"@types/papaparse": "^5.5.2",
"@types/qrcode": "^1.5.6",
"@types/sharp": "^0.31.1",
"conventional-changelog": "^7.1.1",
"conventional-changelog-angular": "^8.1.0",
"eslint": "^9.39.1",
@@ -35,13 +36,13 @@
"prettier": "^3.7.4",
"prettier-plugin-svelte": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.7.2",
"svelte": "^5.53.5",
"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": "^8.0.16"
},
"dependencies": {
"@fontsource/inter": "^5.2.8",
@@ -50,7 +51,7 @@
"@resvg/resvg-js": "^2.6.2",
"@sveltejs/adapter-node": "^5.4.0",
"better-sqlite3": "^12.8.0",
"dompurify": "^3.3.2",
"dompurify": "^3.4.12",
"hash-wasm": "^4.12.0",
"highlight.js": "^11.8.0",
"jsdom": "^27.4.0",
@@ -59,6 +60,6 @@
"qrcode": "^1.5.4",
"satori": "^0.26.0",
"satori-html": "^0.3.2",
"sharp": "^0.34.5"
"sharp": "^0.35.0"
}
}
@@ -4,28 +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 dropdownListElement: HTMLDivElement;
let dropdownMaxHeight = '12rem';
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;
@@ -64,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'}
>
@@ -91,7 +104,7 @@
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}
onkeydown={handleKeyDown}
/>
</div>
{/if}
@@ -102,7 +115,7 @@
{#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'}
@@ -4,47 +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 inputMaxLength: number | null = null;
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 multiselectInitialized = 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 = {
@@ -63,34 +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();
}
$: if (show && mode === 'multiselect' && !multiselectInitialized) {
multiselectInitialized = true;
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
}
function resetModal() {
inputValue =
initialValue !== null
@@ -212,7 +205,8 @@
return null;
}
async function handleSubmit() {
async function handleSubmit(event: Event) {
event.preventDefault();
if (mode === 'report') {
await submitReport();
return;
@@ -308,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',
@@ -394,17 +389,44 @@
}
}
$: 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/20 backdrop-blur-xs">
<form
on:submit|preventDefault={handleSubmit}
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">
@@ -448,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
@@ -463,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}
@@ -543,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
@@ -15,9 +15,13 @@
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 =
@@ -73,7 +77,7 @@
>Profile</a
>
<button
on:click={logout}
onclick={logout}
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
>Logout</button
>
@@ -104,7 +108,7 @@
</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}
>
@@ -126,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 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;
}}
@@ -153,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
@@ -162,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}
@@ -12,17 +12,24 @@
Lock,
EyeOff,
Globe,
HatGlasses
HatGlasses,
ThumbsUp
} from '@lucide/svelte';
import { syntaxes } from '$lib/consts';
import type { Paste } from '$lib/types/paste';
export let paste: Paste;
export let now: Date;
export let showUser: boolean = true;
export let compact: boolean = false;
interface Props {
paste: Paste;
now: Date;
showUser?: boolean;
compact?: boolean;
}
const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext'];
let { paste, now, showUser = true, compact = false }: Props = $props();
let syntax = $derived(syntaxes[paste.syntax] ?? syntaxes['plaintext']);
let netLikes = $derived(paste.likes - paste.dislikes);
let netLikeText = $derived(`${formatNumber(netLikes)} Like${netLikes === 1 ? '' : 's'}`);
</script>
{#if compact}
@@ -46,7 +53,7 @@
{#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()}
{new Date(paste.createdAt).toLocaleDateString()}
{/if}
{:else}
Creation date unknown
@@ -79,19 +86,29 @@
{/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 class="flex flex-wrap items-center gap-x-3 gap-y-1">
<span class="flex items-center gap-2">
<Eye class="h-4 w-4" />
{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}
</span>
<span
class="flex items-center gap-2"
use:tooltip={`${formatNumber(paste.likes)} likes, ${formatNumber(paste.dislikes)} dislikes`}
>
<ThumbsUp class="h-4 w-4" />
{netLikeText}
</span>
</div>
</div>
<div>
<div
class="flex items-center gap-2"
use:tooltip={paste.isCompressed ? `Compressed Size: ${formatBytes(paste.size)}` : ''}
use:tooltip={paste.isCompressed
? `Compressed Size: ${formatBytes(paste.storedSize)}`
: ''}
>
<FileBox class="h-4 w-4" />
{formatBytes(paste.trueSize)}
{formatBytes(paste.originalSize)}
</div>
<div class="flex items-center gap-2">
<Code class="h-4 w-4" />
@@ -130,13 +147,19 @@
{/if}
</span>
</div>
{#if paste.editedAt}
{#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>Edited {dateToRelativeString(new Date(paste.editedAt), true, false, now)}</span>
<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}
@@ -163,19 +186,28 @@
</div>
{/if}
</div>
<div>
<div class="flex items-center gap-2 text-sm text-neutral-400">
<div class="grid grid-cols-[auto_auto] gap-x-4 gap-y-1 text-sm text-neutral-400">
<div class="flex items-center gap-2">
<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)}` : ''}
class="flex items-center gap-2"
use:tooltip={`${formatNumber(paste.likes)} likes, ${formatNumber(paste.dislikes)} dislikes`}
>
<ThumbsUp class="h-4 w-4" />
<span>{netLikeText}</span>
</div>
<div
class="flex items-center gap-2"
use:tooltip={paste.isCompressed
? `Compressed Size: ${formatBytes(paste.storedSize)}`
: ''}
>
<FileBox class="h-4 w-4" />
<span>{formatBytes(paste.trueSize)}</span>
<span>{formatBytes(paste.originalSize)}</span>
</div>
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
<div class="flex items-center gap-2">
<Code class="h-4 w-4" />
<span>{syntax.name}</span>
</div>
@@ -0,0 +1,290 @@
<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, Reply, Quote } 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="rounded border border-transparent 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-sm">
{#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-xs text-neutral-400"
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-500={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-1.5">
<button
type="button"
class="flex h-7 min-w-10 items-center justify-center gap-1 rounded px-2 text-xs {node.userReaction !==
1
? 'text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600'
: 'bg-green-950 text-green-200 hover:bg-green-900 active:bg-green-800'} disabled:cursor-not-allowed disabled:hover:bg-transparent"
class:border-green-700={node.userReaction === 1}
onclick={() => onReact(node.id, 1, node.userReaction)}
disabled={reactingIds[node.id] || !$user}
aria-label="Like comment"
title="Like"
>
<ThumbsUp class="h-3.5 w-3.5" />
{node.likes}
</button>
<button
type="button"
class="flex h-7 min-w-10 items-center justify-center gap-1 rounded px-2 text-xs {node.userReaction !==
2
? 'text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600'
: 'bg-red-950 text-red-200 hover:bg-red-900 active:bg-red-800'} disabled:cursor-not-allowed disabled:hover:bg-transparent"
class:border-red-700={node.userReaction === 2}
onclick={() => onReact(node.id, 2, node.userReaction)}
disabled={reactingIds[node.id] || !$user}
aria-label="Dislike comment"
title="Dislike"
>
<ThumbsDown class="h-3.5 w-3.5" />
{node.dislikes}
</button>
{#if $user}
{#if !replyOpen}
<button
type="button"
class="flex h-7 items-center gap-1 rounded px-2 text-xs text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600"
onclick={() => {
openReply(node.content ? `> ${node.content.replace(/\n/g, '\n> ')}\n\n` : '');
}}
>
<Quote class="h-3.5 w-3.5" />
Quote
</button>
{/if}
<button
type="button"
class="flex h-7 items-center gap-1 rounded px-2 text-xs text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600"
onclick={() => {
if (replyOpen) {
replyOpen = false;
replyError = '';
replyText = '';
return;
}
openReply('');
}}
>
<Reply class="h-3.5 w-3.5" />
{replyOpen ? 'Cancel' : 'Reply'}
</button>
{#if node.author?.uuid === $user.uuid || hasRole($user.roles, 4) || hasRole($user.roles, 2)}
<div class="ml-auto flex items-center gap-1">
<button
type="button"
class="flex h-7 w-7 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600"
onclick={() => handleDelete(false)}
disabled={deleting}
aria-label="Delete comment"
title="Delete"
>
<Trash2 class="h-3.5 w-3.5" />
</button>
{#if hasRole($user.roles, roles.Moderator) || hasRole($user.roles, roles.Admin)}
<button
type="button"
class="flex h-7 w-7 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600"
onclick={() => handleDelete(true)}
disabled={deleting}
aria-label="Hard delete comment"
title="Hard delete"
>
<Shredder class="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}
submitLabel="Reply"
submittingLabel="Replying..."
compact
/>
{#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-700 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,307 @@
<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';
import { RefreshCw } from '@lucide/svelte';
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-700 bg-neutral-900 p-4">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-2">
<h2 class="text-lg font-semibold text-neutral-100">Comments</h2>
<span
class="rounded border border-neutral-700 bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300"
>
{comments.length}
</span>
</div>
<button
type="button"
class="flex h-8 items-center gap-2 rounded px-2 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
onclick={refreshComments}
disabled={loading}
aria-label="Refresh comments"
>
<RefreshCw class="h-3.5 w-3.5 {loading ? 'animate-spin' : ''}" />
{loading ? 'Refreshing' : 'Refresh'}
</button>
</div>
{#if $user}
<div class="mb-5">
<RichTextEditor
bind:value={newComment}
placeholder="Add a comment..."
onSubmit={submitTopLevelComment}
disabled={posting}
submitting={posting}
compact
/>
</div>
{:else}
<div class="mb-4 rounded border border-neutral-700 bg-neutral-800 p-3 text-sm text-neutral-300">
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-700 bg-neutral-800 p-3 text-sm text-neutral-300">
Loading comments...
</div>
{:else if threadedComments.length === 0}
<div class="rounded border border-neutral-700 bg-neutral-800 p-3 text-sm text-neutral-300">
No comments yet.
</div>
{:else}
<div class="space-y-2">
{#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,234 @@
<script lang="ts">
import { Bold, Italic, CodeXml, Quote, Send, Eye, Pencil } from '@lucide/svelte';
import { parseCommentMarkdown } from '$lib/utils/markdown';
interface Props {
class?: string;
value?: string;
placeholder?: string;
disabled?: boolean;
submitting?: boolean;
compact?: boolean;
submitLabel?: string;
submittingLabel?: string;
onSubmit?: (value: string) => void | Promise<void>;
}
let {
class: className = '',
value = $bindable(''),
placeholder = 'Write a comment...',
disabled = false,
submitting = false,
compact = 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));
const editorMinHeight = $derived(compact ? 'min-h-20' : 'min-h-24');
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 overflow-hidden rounded border border-neutral-700 bg-neutral-900 shadow-sm {className}"
>
{#if mode === 'raw'}
<textarea
bind:this={editor}
class="{editorMinHeight} w-full resize-y border-0 bg-neutral-900 p-3 font-mono text-sm text-neutral-100 placeholder:text-neutral-400 focus:bg-neutral-800/60"
{placeholder}
maxlength={5000}
disabled={isDisabled}
bind:value
onkeydown={handleKeydown}
></textarea>
{:else}
<div class="{editorMinHeight} w-full overflow-auto bg-neutral-900 p-3 text-sm text-neutral-100">
{#if value.trim().length === 0}
<div class="text-neutral-400">{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 border-t border-neutral-700 bg-neutral-800 p-2 md:flex-row md:items-center md:gap-0"
>
<div class="flex items-center gap-1">
<button
type="button"
class="flex h-8 w-8 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
onclick={addBold}
disabled={isDisabled || mode === 'preview'}
aria-label="Bold"
title="Bold"
>
<Bold class="h-4 w-4" />
</button>
<button
type="button"
class="flex h-8 w-8 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
onclick={addItalic}
disabled={isDisabled || mode === 'preview'}
aria-label="Italic"
title="Italic"
>
<Italic class="h-4 w-4" />
</button>
<button
type="button"
class="flex h-8 w-8 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
onclick={addQuote}
disabled={isDisabled || mode === 'preview'}
aria-label="Quote"
title="Quote"
>
<Quote class="h-4 w-4" />
</button>
<button
type="button"
class="flex h-8 w-8 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
onclick={addCode}
disabled={isDisabled || mode === 'preview'}
aria-label="Inline code"
title="Inline code"
>
<CodeXml class="h-4 w-4" />
</button>
</div>
<div class="flex flex-col items-stretch gap-2 md:ml-auto md:flex-row md:items-center">
<button
type="button"
class="flex h-8 w-full items-center justify-center gap-2 rounded px-3 text-sm text-neutral-200 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500 md:w-auto"
onclick={toggleMode}
disabled={isDisabled}
>
{#if mode === 'preview'}
<Pencil class="h-4 w-4" />
{:else}
<Eye class="h-4 w-4" />
{/if}
{mode === 'preview' ? 'Raw' : 'Preview'}
</button>
<button
type="button"
class="flex h-8 w-full items-center justify-center gap-2 rounded border border-neutral-600 bg-neutral-700 px-3 text-sm font-medium text-neutral-100 hover:border-neutral-500 hover:bg-neutral-600 disabled:cursor-not-allowed disabled:border-neutral-700 disabled:bg-neutral-800 disabled:text-neutral-500 md:w-auto"
onclick={submit}
disabled={!canSubmit}
>
<Send class="h-4 w-4" />
{submitting ? submittingLabel : submitLabel}
</button>
</div>
</div>
</div>
@@ -10,11 +10,15 @@
import User from '@lucide/svelte/icons/user';
import type { PasteEmbedProps } from './pasteEmbed';
export let title: PasteEmbedProps['title'];
export let uploader: PasteEmbedProps['uploader'];
export let metadata: PasteEmbedProps['metadata'];
export let previewLines: PasteEmbedProps['previewLines'];
export let isEncrypted: PasteEmbedProps['isEncrypted'];
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,
+28
View File
@@ -0,0 +1,28 @@
import { apiUrl } from '$lib/server/api';
const methodsWithoutBody = new Set(['GET', 'HEAD']);
export async function proxyBackendRequest(
prefix: string,
path: string,
request: Request,
url: URL
) {
const targetUrl = new URL(`${prefix}/${path}`.replace(/\/+$/, ''), apiUrl);
targetUrl.search = url.search;
const headers = new Headers(request.headers);
headers.delete('host');
const init: RequestInit = {
method: request.method,
headers,
redirect: 'manual'
};
if (!methodsWithoutBody.has(request.method)) {
init.body = await request.arrayBuffer();
}
return fetch(targetUrl, init);
}
+1 -35
View File
@@ -1,39 +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;
maxInputLength?: number;
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,
@@ -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;
};
+7 -2
View File
@@ -1,18 +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;
}
+1 -1
View File
@@ -28,4 +28,4 @@ export const reportTypeLabels = ['CopyrightViolation', 'IllegalContent', 'Fraud'
export const reportStatusLabels = ['Open', 'Closed'] as const;
export const reportTargetLabels = ['Paste', 'User'] as const;
export const reportTargetLabels = ['Paste', 'User', 'Comment'] as const;
+1
View File
@@ -7,6 +7,7 @@ export interface User {
username: string;
displayName: string | null;
email: string | null;
emailVerified: boolean;
lastLogin: number | null;
roles: number; // bitfield; 5 = User | Admin
isBanned: boolean;
+164 -53
View File
@@ -13,43 +13,122 @@ 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';
let refreshPromise: Promise<void> | null = null;
let lastRefreshAttempt = 0;
let refreshFailureCount = 0;
let refreshIntervalId: ReturnType<typeof setInterval> | null = null;
let listenersRegistered = false;
export function getToken() {
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;
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;
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 {
@@ -64,27 +143,18 @@ 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 now = Date.now();
if (exp - now >= 2 * 60 * 1000) return;
if (refreshPromise) {
await refreshPromise;
const payload = decodeJwtPayload(token);
const expClaim = payload ? parseNumberClaim(payload.exp) : null;
if (expClaim === null) {
await queueRefresh(token, refreshToken);
return;
}
const timeSinceLastAttempt = now - lastRefreshAttempt;
const minDelay = getBackoffDelay(refreshFailureCount);
if (timeSinceLastAttempt < minDelay) return;
const exp = expClaim * 1000;
const now = Date.now();
refreshPromise = performRefresh(token, refreshToken);
try {
await refreshPromise;
} finally {
refreshPromise = null;
}
if (exp - now >= 2 * 60 * 1000) return;
await queueRefresh(token, refreshToken);
}
async function performRefresh(token: string, refreshToken: string) {
@@ -96,21 +166,30 @@ async function performRefresh(token: string, refreshToken: string) {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, refreshToken })
});
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 (res.status === 400 || res.status === 401 || res.status === 403) {
if (isPermanentRefreshFailure(res.status, data?.message)) {
clearTokens();
}
return;
}
const data = await res.json();
if (data.success && data.token?.token && data.token?.refreshToken) {
if (data?.success && data.token?.token && data.token?.refreshToken) {
setTokens(data.token.token, data.token.refreshToken);
} else {
refreshFailureCount++;
if (!data.success) {
if (isPermanentRefreshFailure(res.status, data?.message)) {
clearTokens();
}
}
@@ -121,7 +200,27 @@ async function performRefresh(token: string, refreshToken: string) {
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) {
@@ -133,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
});
}
@@ -148,19 +254,24 @@ export function clearServerTokens(cookies: Cookies) {
}
export function getUserFromToken(token: string): JWTUser | null {
try {
const payload = JSON.parse(atob(token.split('.')[1]));
return {
uuid: payload.uuid,
username: payload.username,
displayname: payload.displayname,
totpEnabled: payload.totp_enabled === 'True',
roles: typeof payload.roles === 'string' ? parseInt(payload.roles, 10) : payload.roles,
isBanned: payload.is_banned === 'True'
};
} catch {
return null;
}
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;
+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]);
}
+193
View File
@@ -2,6 +2,7 @@ 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';
@@ -138,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;
}
-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 & 4) !== 0;
const alreadyAdmin = (currentRoles & 4) !== 0;
return nextHasAdmin && !alreadyAdmin;
}
@@ -1,4 +1,5 @@
import hljs from 'highlight.js';
import { escapeHtml } from '../utils/html';
type HighlightRequest = {
id: number;
@@ -11,9 +12,6 @@ type HighlightResponse = {
html: string;
};
const escapeHtml = (value: string) =>
value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
self.onmessage = (event: MessageEvent<HighlightRequest>) => {
const { id, code, lang } = event.data;
let html = '';
+10 -8
View File
@@ -1,13 +1,15 @@
import type { LayoutServerLoad } from './$types';
import { error } from '@sveltejs/kit';
export const load: LayoutServerLoad = async ({ fetch, url }) => {
try {
const res = await fetch('/api/auth/info');
const pasteOptionsRes = await fetch('/api/paste/info');
const options = await res.json();
const pasteOptions = await pasteOptionsRes.json();
return { options, pasteOptions, url: url.href };
} catch {
return { options: null, pasteOptions: null, url: url.href };
const res = await fetch('/api/auth/info');
const pasteOptionsRes = await fetch('/api/paste/info');
if (!res.ok || !pasteOptionsRes.ok) {
throw error(503, 'Failed to load site configuration.');
}
const options = await res.json();
const pasteOptions = await pasteOptionsRes.json();
return { options, pasteOptions, url: url.href };
};
+72 -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,35 +56,49 @@
};
}
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>
<svelte:head>
<link rel="icon" href={favicon} />
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/')}
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/' || page.url.pathname === '/forgot-password')}
<script
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
async
@@ -58,7 +108,7 @@
</svelte:head>
<Navbar {data} />
<slot />
{@render children?.()}
<Footer />
<ModalHost />
+78 -48
View File
@@ -18,37 +18,47 @@
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 markdownConatiner: HTMLDivElement;
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';
@@ -59,11 +69,11 @@
}
function resize(markdown: boolean = false) {
if ((!markdown && !textArea) || (markdown && !markdownConatiner)) return;
const element = markdown ? markdownConatiner : textArea;
if (!element) return;
let h: number;
let max: number;
let element = markdown ? markdownConatiner : textArea;
element.style.height = 'auto';
h = element.scrollHeight;
@@ -106,17 +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 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();
@@ -216,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
@@ -228,7 +258,7 @@
>
<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)"
@@ -258,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 =
@@ -276,19 +306,19 @@
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) => {
ondrop={(e) => {
requestAnimationFrame(() => resize());
e.preventDefault();
isDragging = false;
@@ -360,7 +390,7 @@
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>
@@ -369,7 +399,7 @@
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>
@@ -433,7 +463,7 @@
<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);
@@ -446,7 +476,7 @@
<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" />
@@ -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)}`);
}
@@ -161,7 +161,7 @@ export const GET: RequestHandler = async ({ params, fetch }) => {
const content = rawContent || 'No content available.';
const created = paste.createdAt ? new Date(paste.createdAt) : extractDateFromUUIDv7(paste.uuid);
const metadata: PasteEmbedProps['metadata'] = [
{ icon: 'size', value: formatBytes(paste.trueSize) },
{ icon: 'size', value: formatBytes(paste.originalSize) },
{
icon: 'views',
value: `${formatNumber(paste.views)} view${paste.views === 1 ? '' : 's'}`
@@ -1,5 +1,6 @@
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 { apiUrl, viewInternalApiKey } from '$lib/server/api';
import { error } from '@sveltejs/kit';
@@ -46,12 +47,22 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent
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
+228 -81
View File
@@ -24,7 +24,10 @@
CalendarCog,
Flag,
ArrowUp,
HatGlasses
HatGlasses,
MessageCircle,
ThumbsUp,
ThumbsDown
} from '@lucide/svelte/icons/index';
import {
formatBytes,
@@ -42,40 +45,70 @@
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, 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';
import type { Paste, PasteReaction } from '$lib/types/paste';
import HighlightWorker from '$lib/workers/highlight.worker?worker';
export let data: PageData;
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;
@@ -173,8 +206,6 @@
} else {
try {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
@@ -183,8 +214,6 @@
}
} 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;
@@ -215,19 +244,18 @@
const rows = results.data as string[][];
const [header, ...body] = rows;
const escape = (v: string) =>
v.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
const tableHtml = `
<table class="csv-table">
<thead>
<tr>
${header.map((c) => `<th>${c ? escape(c) : ''}</th>`).join('')}
${header.map((c) => `<th>${c ? escapeHtml(c) : ''}</th>`).join('')}
</tr>
</thead>
<tbody>
${body
.map((row) => `<tr>${row.map((c) => `<td>${c ? escape(c) : ''}</td>`).join('')}</tr>`)
.map(
(row) => `<tr>${row.map((c) => `<td>${c ? escapeHtml(c) : ''}</td>`).join('')}</tr>`
)
.join('')}
</tbody>
</table>
@@ -289,7 +317,7 @@
editLoading = false;
return;
}
data.content = rawContent;
updatePageContent(rawContent);
decryptedContent = rawContent;
await renderPaste(rawContent);
}
@@ -320,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.';
@@ -334,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') {
@@ -490,12 +563,12 @@
}
});
$: if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderPaste();
$: reportSiteKey =
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null;
$: pasteImageUrl =
data?.paste && data?.url ? `${new URL(data.url).origin}/${data.paste.id}.jpg` : 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 />
@@ -507,15 +580,22 @@
: '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 ${syntaxes[data.paste.syntax].name} 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" />
@@ -526,7 +606,11 @@
<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() ?? ''}
@@ -584,7 +668,9 @@
<div
class="flex"
use:tooltip={`${
data.paste.isCompressed ? `Compressed Size: ${formatBytes(data.paste.size)}` : ''
data.paste.isCompressed
? `Compressed Size: ${formatBytes(data.paste.storedSize)}`
: ''
}${
data.paste.visibility === 2
? ` • Decrypted Size: ${formatBytes(decryptedContent ? new TextEncoder().encode(decryptedContent).length : 0)}`
@@ -592,7 +678,7 @@
}`}
>
<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>
@@ -730,6 +816,33 @@
? 's'
: ''}</span
>
<button
type="button"
class="ml-4 rounded border px-2 py-0.5 text-sm transition-colors disabled:cursor-not-allowed! disabled:opacity-60 {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:cursor-not-allowed! disabled:opacity-60 {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>
@@ -739,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 }}
@@ -760,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'
});
@@ -787,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);
@@ -797,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 }}
@@ -812,28 +926,49 @@
>
{/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 || hasRole($user.roles, 2) || hasRole($user.roles, 4))}
@@ -842,20 +977,22 @@
<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();
@@ -877,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}
@@ -911,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>
@@ -949,16 +1094,18 @@
class={data.paste.syntax === 'markdown'
? 'markdown rounded-b-md bg-neutral-800 p-4'
: data.paste.syntax === 'csv'
? 'csv-container scrollbar overflow-x-auto overflow-y-auto scrollbar-thumb-neutral-600 scrollbar-track-neutral-800'
? 'csv-container scrollbar scrollbar-thumb-neutral-600 scrollbar-track-neutral-800 overflow-x-auto overflow-y-auto'
: '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>
@@ -0,0 +1,13 @@
import { proxyBackendRequest } from '$lib/server/proxy';
import type { RequestHandler } from './$types';
const handle: RequestHandler = ({ params, request, url }) => {
return proxyBackendRequest('/api', params.path, request, url);
};
export const GET = handle;
export const POST = handle;
export const PUT = handle;
export const PATCH = handle;
export const DELETE = handle;
export const OPTIONS = handle;
@@ -0,0 +1,123 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { extractError } from '$lib/utils/misc';
import { onMount } from 'svelte';
import type { PageData } from './$types';
let email = $state('');
let error = $state('');
let message = $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',
size: 'flexible',
appearence: 'interaction-only'
});
}
};
if (window.turnstile) {
render();
} else {
window.addEventListener('turnstile:loaded', render, { once: true });
}
return () => {
window.removeEventListener('turnstile:loaded', render);
};
});
async function submit(event: Event) {
event.preventDefault();
error = '';
message = '';
const body: { email: string; token?: string } = { email };
if (data.options?.cf_turnstile_site_key && window.turnstile) {
const token = window.turnstile.getResponse();
if (token) body.token = token;
}
const res = await fetch('/api/auth/password/forgot', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
if (window.turnstile) window.turnstile.reset();
error = extractError(json) || 'Request failed.';
return;
}
if (window.turnstile) window.turnstile.reset();
message = json.message || 'If an account exists for that email, a reset link has been sent.';
email = '';
}
</script>
<svelte:head>
<title>Forgot Password - Sharpbin</title>
<meta name="description" content="Request a password reset link for your Sharpbin account." />
</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-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-2 text-center text-3xl font-bold">Forgot Password</h1>
<p class="mb-6 text-center text-sm text-neutral-400">
Enter the email address on your account and we’ll send a reset link if one exists.
</p>
<form onsubmit={submit} class="space-y-4">
<input
type="email"
placeholder="Email"
bind:value={email}
autocomplete="email"
required
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 data.options?.cf_turnstile_site_key}
<div class="cf-turnstile w-full"></div>
{/if}
<button
type="submit"
class="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"
>
Send Reset Link
</button>
{#if error}
<div
class="rounded border border-red-900 bg-red-950 p-2 text-sm whitespace-pre-line text-red-200"
>
{error}
</div>
{/if}
{#if message}
<div
class="rounded border border-green-900 bg-green-950 p-2 text-sm whitespace-pre-line text-green-200"
>
{message}
</div>
{/if}
</form>
<p class="mt-4 text-center text-sm text-neutral-400">
<a
href={resolve('/login')}
class="text-neutral-200 transition-colors duration-200 hover:text-white">Back to login</a
>
</p>
</div>
</main>
@@ -0,0 +1,12 @@
import { apiUrl } from '$lib/server/api';
import { json } from '@sveltejs/kit';
export const GET = async () => {
const res = await fetch(`${apiUrl}/health`);
if (!res.ok) {
return json({ status: 'unhealthy', backend: res.status }, { status: 503 });
}
return json({ status: 'ok' });
};
+4
View File
@@ -121,3 +121,7 @@ select {
.markdown th {
background-color: #2a2a2a;
}
button {
cursor: pointer;
}
@@ -5,12 +5,16 @@
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 = () => {
@@ -35,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
@@ -96,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"
@@ -122,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;
@@ -154,5 +159,11 @@
class="text-neutral-200 transition-colors duration-200 hover:text-white">Register</a
>
</p>
<p class="mt-2 text-center text-sm text-neutral-400">
<a
href={resolve('/forgot-password')}
class="text-neutral-200 transition-colors duration-200 hover:text-white">Forgot password?</a
>
</p>
</div>
</main>
@@ -0,0 +1,6 @@
import { proxyBackendRequest } from '$lib/server/proxy';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = ({ request, url }) => {
return proxyBackendRequest('/openapi', '', request, url);
};
@@ -0,0 +1,6 @@
import { proxyBackendRequest } from '$lib/server/proxy';
import type { RequestHandler } from './$types';
export const GET: RequestHandler = ({ params, request, url }) => {
return proxyBackendRequest('/openapi', params.path, request, url);
};
@@ -15,10 +15,14 @@ export const GET: RequestHandler = async ({ params, request }) => {
statusText: 'Not Found'
});
}
const content = await res.text();
return new Response(content, {
headers: {
'Content-Type': 'text/plain; charset=utf-8'
}
const responseHeaders = new Headers(res.headers);
responseHeaders.delete('content-encoding');
responseHeaders.delete('content-length');
responseHeaders.delete('transfer-encoding');
return new Response(await res.arrayBuffer(), {
status: res.status,
statusText: res.statusText,
headers: responseHeaders
});
};
@@ -4,17 +4,12 @@ import { extractError } from '$lib/utils/misc';
import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ fetch, request }) => {
try {
const headers = new Headers(request.headers);
const res = await fetch('/api/paste/recent', { headers });
if (!res.ok) {
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
throw error(res.status, errorMsg);
}
const recentPastes: Paste[] = await res.json();
return { recentPastes };
} catch (error) {
console.error(error);
return { recentPastes: [] };
const headers = new Headers(request.headers);
const res = await fetch('/api/paste/recent', { headers });
if (!res.ok) {
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
throw error(res.status, errorMsg);
}
const recentPastes: Paste[] = await res.json();
return { recentPastes };
};
@@ -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
@@ -8,27 +8,31 @@
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 showPassword = false;
let passwordFocused = $state(false);
let showPassword = $state(false);
let passwordChecks = {
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 = () => {
@@ -71,9 +75,12 @@
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 = '';
@@ -143,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"
@@ -179,15 +186,15 @@
placeholder="Password"
bind:value={password}
required
on:focus={() => (passwordFocused = true)}
on:blur={() => (passwordFocused = false)}
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"
on:click={() => (showPassword = !showPassword)}
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"
>
@@ -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,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,25 @@
import { apiUrl } from '$lib/server/api';
import { extractError } from '$lib/utils/misc';
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ url, request }) => {
const token = url.searchParams.get('token');
if (!token) {
throw error(400, 'Reset token is required.');
}
const headers = new Headers(request.headers);
const res = await fetch(`${apiUrl}/api/auth/password/reset-info?token=${token}`, { headers });
const json = await res.json().catch(() => null);
if (!res.ok) {
const message = extractError(json);
throw error(res.status, message ?? 'Request failed');
}
return {
token,
username: typeof json?.username === 'string' ? json.username : undefined,
requiresTotp: Boolean(json?.requiresTotp)
};
};
@@ -0,0 +1,231 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { extractError } from '$lib/utils/misc';
import { Check, X } from '@lucide/svelte';
import { slide, fade } from 'svelte/transition';
import type { PageData } from './$types';
interface Props {
data: PageData;
}
let { data }: Props = $props();
let password = $state('');
let confirmPassword = $state('');
let totpCode = $state('');
let error = $state('');
let message = $state('');
let complete = $state(false);
let loading = $state(false);
let passwordFocused = $state(false);
let passwordChecks = $state({
minLength: false,
maxLength: false,
upper: false,
lower: false,
number: false
});
let passwordValid = $state(false);
function validatePassword(pw: string) {
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.minLength &&
passwordChecks.maxLength &&
passwordChecks.upper &&
passwordChecks.lower &&
passwordChecks.number;
}
$effect(() => {
validatePassword(password);
});
async function submit(event: Event) {
event.preventDefault();
error = '';
message = '';
if (!password || !confirmPassword) {
error = 'Both password fields are required.';
return;
}
if (password !== confirmPassword) {
error = 'Passwords do not match.';
return;
}
if (!passwordValid) {
error =
'Password should have at least 8 characters, no more than 128 characters, including uppercase, lowercase, and digits.';
return;
}
loading = true;
try {
const res = await fetch('/api/auth/password/reset', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
token: data.token,
newPassword: password,
...(data.requiresTotp ? { totpCode } : {})
})
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
error = extractError(json) || 'Password reset failed.';
return;
}
complete = true;
message = json.message || 'Password reset successfully.';
} finally {
loading = false;
}
}
</script>
<svelte:head>
<title>Reset Password - Sharpbin</title>
<meta name="description" content="Set a new password for your Sharpbin account." />
</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-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
{#if complete}
<h1 class="mb-2 text-center text-3xl font-bold">Password Reset</h1>
<p class="text-center text-sm text-neutral-400">{message}</p>
<p class="mt-4 text-center text-sm text-neutral-400">
<a
href={resolve('/login')}
class="text-neutral-200 transition-colors duration-200 hover:text-white">Back to login</a
>
</p>
{:else}
<h1 class="mb-2 text-center text-3xl font-bold">Reset Password</h1>
<p class="mb-6 text-center text-sm text-neutral-400">
{#if data.username}
Reset the password for {data.username}.
{:else}
Set a new password for your account.
{/if}
</p>
<form onsubmit={submit} class="space-y-4">
<input
type="password"
placeholder="New password"
bind:value={password}
autocomplete="new-password"
required
onfocus={() => (passwordFocused = true)}
onblur={() => (passwordFocused = false)}
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 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.minLength
? 'text-green-400'
: 'text-red-400'}"
>
{#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'
: 'text-red-400'}"
>
{#if passwordChecks.upper}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
At least one uppercase letter
</li>
<li
class="flex items-center gap-2 {passwordChecks.lower
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.lower}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
At least one lowercase letter
</li>
<li
class="flex items-center gap-2 {passwordChecks.number
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.number}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
At least one number
</li>
</ul>
{/if}
<input
type="password"
placeholder="Confirm new password"
bind:value={confirmPassword}
autocomplete="new-password"
required
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
class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
>
Passwords do not match.
</div>
{/if}
{#if data.requiresTotp}
<input
type="text"
placeholder="TOTP Code"
bind:value={totpCode}
maxlength="6"
inputmode="numeric"
pattern="[0-9]*"
required
oninput={(e) => {
if (e.target instanceof HTMLInputElement) {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
totpCode = e.target.value;
}
}}
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}
<button
type="submit"
disabled={loading || !passwordValid || password !== confirmPassword}
class="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:opacity-50"
>
{loading ? 'Updating...' : 'Reset Password'}
</button>
{#if error}
<div
class="rounded border border-red-900 bg-red-950 p-2 text-sm whitespace-pre-line text-red-200"
>
{error}
</div>
{/if}
</form>
{/if}
</div>
</main>
@@ -3,11 +3,17 @@
import { formatBytes, formatNumber, tooltip } from '$lib/utils/misc';
import { FileText, Users, Database, TrendingUp } from '@lucide/svelte';
export let data: PageData;
$: stats = data.stats.stats;
interface Props {
data: PageData;
}
$: dailyData = stats.pastes.daily || [];
$: maxCount = Math.max(...dailyData.map((d: { count: number; date: number }) => d.count), 5);
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'];
@@ -75,11 +81,11 @@
<p
class="text-2xl font-bold"
use:tooltip={[
`${stats.pastes.trueTotalSizeInBytes != stats.pastes.totalSizeInBytes ? `Uncompressed Size: ${formatBytes(stats.pastes.trueTotalSizeInBytes)}` : ''}`,
`${stats.pastes.totalStoredSizeInBytes != stats.pastes.totalOriginalSizeInBytes ? `Uncompressed Size: ${formatBytes(stats.pastes.totalOriginalSizeInBytes)}` : ''}`,
true
]}
>
{formatBytes(stats.pastes.totalSizeInBytes)}
{formatBytes(stats.pastes.totalStoredSizeInBytes)}
</p>
</div>
</div>
@@ -77,7 +77,7 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
if (token && !asGuest && canModerate && (!reportsSubmitted || !isOwner)) {
headers.set('Authorization', `Bearer ${token}`);
const submittedRes = await fetch(`${apiUrl}/api/user/${user.uuid}/reports/submitted`, {
const submittedRes = await fetch(`${apiUrl}/api/report/users/${user.uuid}/reports/submitted`, {
headers: headers
});
if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
@@ -85,7 +85,7 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
if (token && !asGuest && !isOwner && canModerate) {
headers.set('Authorization', `Bearer ${token}`);
const r = await fetch(`${apiUrl}/api/user/${user.uuid}/reports`, {
const r = await fetch(`${apiUrl}/api/report/users/${user.uuid}/reports`, {
headers: headers
});
if (r.ok) reportsTarget = await r.json();
File diff suppressed because it is too large Load Diff
+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/
+263 -3
View File
@@ -52,16 +52,33 @@ namespace SharpbinV3.Server.Controllers
var existingUser = await _userService.GetByUsername(request.Username);
if (existingUser != null)
return Conflict(new { success = false, message = "Username already exists." });
if (!string.IsNullOrEmpty(request.Email))
var normalizedEmail = UserService.NormalizeEmail(request.Email);
if (normalizedEmail != null)
{
var existingEmailUser = await _userService.GetByEmail(request.Email);
var existingEmailUser = await _userService.GetByEmail(normalizedEmail);
if (existingEmailUser != null)
return Conflict(new { success = false, message = "Email already in use." });
}
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);
User user;
try
{
user = await _authService.CreateUser(request.Username, request.Password, normalizedEmail, request.DisplayName);
}
catch (DbUpdateException)
{
if (await _userService.GetByUsername(request.Username) != null)
return Conflict(new { success = false, message = "Username already exists." });
if (normalizedEmail != null && await _userService.GetByEmail(normalizedEmail) != null)
return Conflict(new { success = false, message = "Email already in use." });
throw;
}
if (!string.IsNullOrWhiteSpace(user.Email))
await _authService.SendEmailVerification(user);
@@ -166,6 +183,7 @@ namespace SharpbinV3.Server.Controllers
{
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
registration_enabled = authSettings.Registration_Enabled,
admins_require_2fa = authSettings.Admins_Require_2FA,
}
);
}
@@ -337,5 +355,247 @@ namespace SharpbinV3.Server.Controllers
else
return BadRequest(new { success = false, message });
}
[HttpPost]
[EnableRateLimiting("Strict")]
[Route("password/forgot")]
public async Task<IActionResult> RequestPasswordReset([FromBody] PasswordResetRequestDto request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (!await _verification.VerifyAsync(new VerificationContext { Token = request.Token, Ip = HttpContext.GetRequestIP() }))
return BadRequest(new { success = false, message = "Verification failed." });
var result = await _authService.RequestPasswordResetForEmail(request.Email);
if (!result.success)
return Ok(new { success = true, message = "If an account exists for that email, a reset link has been sent." });
return Ok(new { success = true, message = result.message });
}
[HttpGet]
[Route("password/reset-info")]
public async Task<IActionResult> GetPasswordResetInfo([FromQuery] string token)
{
var info = await _authService.GetPasswordResetTokenInfo(token);
if (!info.success || info.user == null)
return BadRequest(new { success = false, message = info.message });
if (info.blocked)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
return Ok(
new
{
success = true,
username = info.username,
requiresTotp = info.requiresTotp,
}
);
}
[HttpPost]
[Route("password/reset")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ResetPassword([FromBody] PasswordResetDto request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var result = await _authService.ResetPasswordWithToken(request.Token, request.NewPassword, request.TotpCode);
if (!result.success)
{
if (result.message == "2FA is required to perform this action.")
return StatusCode(403, new { success = false, message = result.message });
return BadRequest(new { success = false, message = result.message });
}
return Ok(new { success = true, message = result.message });
}
[HttpPost]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[Route("password/change")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ChangePassword([FromBody] PasswordChangeDto request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var result = await _authService.ChangeOwnPassword(user, request.CurrentPassword, request.NewPassword, request.TotpCode);
if (!result.success)
{
if (result.message == "2FA is required to perform this action.")
return StatusCode(403, new { success = false, message = result.message });
return BadRequest(new { success = false, message = result.message });
}
return Ok(new { success = true, message = result.message });
}
[HttpPost]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[Route("password/admin-reset-link/{uuid}")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> AdminGeneratePasswordResetLink(Guid uuid, [FromBody] AdminPasswordResetLinkDto request)
{
var jwtUser = HttpContext.GetJwtUser()!;
if (!jwtUser.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." });
var targetUser = await _userService.GetByUUID(uuid);
if (targetUser == null)
return NotFound(new { success = false, message = "User not found." });
if (jwtUser.TotpEnabled)
{
if (
string.IsNullOrWhiteSpace(request.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = request.TotpCode })
)
{
return Unauthorized(new { success = false, message = "Invalid TOTP code." });
}
}
else if (options.Value.Admins_Require_2FA)
{
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
}
var result = await _authService.GeneratePasswordResetLink(targetUser, sendEmail: !string.IsNullOrWhiteSpace(targetUser.Email));
if (!result.success)
{
if (result.retryAfter.HasValue)
{
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
return StatusCode(
StatusCodes.Status429TooManyRequests,
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return BadRequest(
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return Ok(
new
{
success = true,
message = result.message,
resetLink = result.resetLink,
}
);
}
[HttpPost]
[Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Sensitive")]
[Route("email/resend-verification")]
public async Task<IActionResult> ResendEmailVerification()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var result = await _authService.ResendEmailVerification(user);
if (!result.success)
{
if (result.retryAfter.HasValue)
{
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
return StatusCode(
StatusCodes.Status429TooManyRequests,
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return BadRequest(
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return Ok(new { success = true, message = result.message });
}
[HttpPost]
[Authorize(Policy = "JwtOnly")]
[EnableRateLimiting("Sensitive")]
[Route("email/change")]
public async Task<IActionResult> ChangeEmail([FromBody] ChangeEmailDto request)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
return BadRequest(new { success = false, message = "User not found." });
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
if (totpEnabled)
{
if (
string.IsNullOrWhiteSpace(request.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = request.TotpCode })
)
{
return Unauthorized(new { success = false, message = "Invalid TOTP code." });
}
}
var result = await _authService.RequestEmailChange(user, request.Email);
if (!result.success)
{
if (result.retryAfter.HasValue)
{
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
return StatusCode(
StatusCodes.Status429TooManyRequests,
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return BadRequest(
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
return Ok(new { success = true, message = result.message });
}
}
}
+258 -101
View File
@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
@@ -18,17 +19,21 @@ namespace SharpbinV3.Server.Controllers
[ApiController]
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;
@@ -83,8 +88,8 @@ namespace SharpbinV3.Server.Controllers
UUID = paste.UUID,
CreatedAt = paste.CreatedAt,
IsCompressed = paste.IsCompressed,
Size = paste.Size,
TrueSize = paste.TrueSize,
StoredSize = paste.StoredSize,
OriginalSize = paste.OriginalSize,
ExpiresAt = paste.ExpiresAt,
Visibility = paste.Visibility,
}
@@ -101,6 +106,9 @@ namespace SharpbinV3.Server.Controllers
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.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator)))
@@ -119,8 +127,8 @@ namespace SharpbinV3.Server.Controllers
UUID = paste.UUID,
CreatedAt = paste.CreatedAt,
Title = paste.Title,
Size = paste.Size,
TrueSize = paste.TrueSize,
StoredSize = paste.StoredSize,
OriginalSize = paste.OriginalSize,
IsCompressed = paste.IsCompressed,
Views = paste.Views,
Syntax = paste.Syntax,
@@ -128,6 +136,9 @@ namespace SharpbinV3.Server.Controllers
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
@@ -168,6 +179,10 @@ namespace SharpbinV3.Server.Controllers
string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (content == null || id == null)
return StatusCode(400, new { success = false, message = "Invalid request." });
if (Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
return BadRequest(
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
);
var paste = await _pasteService.Get(id);
if (paste == null)
@@ -231,8 +246,8 @@ namespace SharpbinV3.Server.Controllers
UUID = newPaste.UUID,
CreatedAt = newPaste.CreatedAt,
Title = newPaste.Title,
Size = newPaste.Size,
TrueSize = newPaste.TrueSize,
OriginalSize = newPaste.OriginalSize,
StoredSize = newPaste.StoredSize,
IsCompressed = newPaste.IsCompressed,
Views = newPaste.Views,
Syntax = newPaste.Syntax,
@@ -269,6 +284,8 @@ 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." });
@@ -281,9 +298,9 @@ namespace SharpbinV3.Server.Controllers
)
return Unauthorized(new { success = false, message = "Invalid API key." });
if (paste.AuthorUUID != HttpContext.GetJwtUser()?.UUID)
if (paste.AuthorUUID.HasValue && paste.AuthorUUID == HttpContext.GetJwtUser()?.UUID)
return Ok(new { success = true, message = "View not recorded for author's own paste." });
if (paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && paste.Visibility != 0)
if (paste.ExpiresAt != 0 && 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);
@@ -297,113 +314,69 @@ namespace SharpbinV3.Server.Controllers
}
[HttpPost]
[Route("{id}/report")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
[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" });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null)
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." });
if (
!await _verificationService.VerifyAsync(
new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
)
)
return BadRequest(new { success = false, message = "Verification failed." });
var existingInteraction = await _pasteService.GetUserInteraction(paste, user.UUID);
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." });
if (request.Reaction.HasValue)
{
if (existingInteraction == null)
{
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." });
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 updatedPaste = await _pasteService.Get(id);
if (updatedPaste == null)
return StatusCode(500, new { success = false, message = "Could not load updated paste." });
var updatedInteraction = await _pasteService.GetUserInteraction(updatedPaste, user.UUID);
return Ok(
new
{
success = true,
message = "Paste reported successfully.",
report = new ReportResponseDto
reaction = new PasteReactionResponseDto
{
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,
PasteID = updatedPaste.ID,
Likes = updatedPaste.PositiveInteractionCount,
Dislikes = updatedPaste.NegativeInteractionCount,
UserReaction = updatedInteraction?.Type,
},
}
);
}
[HttpPatch]
[Route("{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]
[Route("{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." });
}
[HttpGet]
[Route("recent")]
public async Task<IActionResult> GetRecentPastes()
@@ -416,14 +389,16 @@ namespace SharpbinV3.Server.Controllers
UUID = p.UUID,
CreatedAt = p.CreatedAt,
Title = p.Title,
Size = p.Size,
TrueSize = p.TrueSize,
StoredSize = p.StoredSize,
OriginalSize = p.OriginalSize,
IsCompressed = p.IsCompressed,
Views = p.Views,
Syntax = p.Syntax,
Visibility = p.Visibility,
ExpiresAt = p.ExpiresAt,
EditedAt = p.EditedAt,
Likes = p.PositiveInteractionCount,
Dislikes = p.NegativeInteractionCount,
Author =
p.User != null && p.User.Visibility == 0
? new UserSimpleDto
@@ -441,6 +416,146 @@ namespace SharpbinV3.Server.Controllers
);
}
[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)
{
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]
[EnableRateLimiting("NoLimit")]
[Route("info")]
@@ -462,5 +577,47 @@ namespace SharpbinV3.Server.Controllers
}
);
}
private CommentResponseDto ToCommentResponse(Comment comment, Dictionary<long, Interaction>? userInteractionMap)
{
string? content = null;
if (comment.Content != null)
{
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,
};
}
}
}
+306 -12
View File
@@ -2,16 +2,28 @@
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")]
@@ -20,7 +32,7 @@ namespace SharpbinV3.Server.Controllers
{
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." });
@@ -28,7 +40,7 @@ namespace SharpbinV3.Server.Controllers
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
@@ -62,7 +74,7 @@ namespace SharpbinV3.Server.Controllers
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." });
@@ -86,8 +98,8 @@ 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
@@ -132,8 +144,8 @@ namespace SharpbinV3.Server.Controllers
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
@@ -168,8 +180,8 @@ namespace SharpbinV3.Server.Controllers
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
@@ -213,8 +225,8 @@ namespace SharpbinV3.Server.Controllers
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
@@ -230,5 +242,287 @@ namespace SharpbinV3.Server.Controllers
}
);
}
[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." });
if (reportedUser.Roles.HasFlag(Role.Admin) || reportedUser.Roles.HasFlag(Role.Moderator))
return BadRequest(new { success = false, message = "You cannot report staff members." });
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,
},
}
);
}
}
}
+151 -187
View File
@@ -22,6 +22,7 @@ namespace SharpbinV3.Server.Controllers
[Route("api/[controller]")]
public class UserController(
UserService userService,
AuthService authService,
AppDbContext db,
TotpVerificationProvider totp,
VerificationService verificationService,
@@ -30,6 +31,7 @@ namespace SharpbinV3.Server.Controllers
) : ControllerBase
{
private readonly UserService _userService = userService;
private readonly AuthService _authService = authService;
private readonly AppDbContext _db = db;
private readonly TotpVerificationProvider _totp = totp;
private readonly VerificationService _verificationService = verificationService;
@@ -59,6 +61,51 @@ namespace SharpbinV3.Server.Controllers
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(Policy = "JwtOnly")]
[EnableRateLimiting("Strict")]
@@ -68,41 +115,66 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(ModelState);
var jwtUser = HttpContext.GetJwtUser()!;
var actorUser = await _userService.GetByUUID(jwtUser.UUID);
if (actorUser == null)
return Unauthorized(new { success = false, message = "User not authenticated." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
var targetUser = await _userService.GetByUUID(uuid);
if (targetUser == null)
return NotFound(new { success = false, message = "User not found." });
if (
(user.Roles.HasFlag(Role.Admin) && !jwtUser.Roles.HasFlag(Role.Admin))
|| (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
)
var actorIsAdmin = actorUser.Roles.HasFlag(Role.Admin);
var isSelfUpdate = targetUser.UUID == actorUser.UUID;
if ((targetUser.Roles.HasFlag(Role.Admin) && !actorIsAdmin) || (!actorIsAdmin && !isSelfUpdate))
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
if ((updatedUser.Roles.HasValue || updatedUser.IsBanned.HasValue) && !actorIsAdmin)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (updatedUser.Email != null)
return BadRequest(new { success = false, message = "Use the email change endpoint to update email addresses." });
bool isSensitiveUpdate =
(updatedUser.Roles.HasValue && updatedUser.Roles.Value != targetUser.Roles) // updating roles
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != targetUser.IsBanned); // updating ban status
if (actorIsAdmin && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA && isSensitiveUpdate)
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
if (jwtUser.Roles.HasFlag(Role.Admin) || user.UUID == jwtUser.UUID) // only admins or self
if (isSensitiveUpdate && jwtUser.TotpEnabled)
{
user.Email = updatedUser.Email ?? user.Email;
user.Visibility = updatedUser.Visibility ?? user.Visibility;
}
if (jwtUser.Roles.HasFlag(Role.Admin))
{
if (jwtUser.TotpEnabled)
if (
string.IsNullOrEmpty(updatedUser.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = actorUser.UUID, Code = updatedUser.TotpCode })
)
{
if (
string.IsNullOrEmpty(updatedUser.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = updatedUser.TotpCode })
)
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
user.Roles = updatedUser.Roles ?? user.Roles;
user.IsBanned = updatedUser.IsBanned ?? user.IsBanned;
if (
updatedUser.Roles.HasValue
&& targetUser.Roles.HasFlag(Role.Admin)
&& !updatedUser.Roles.Value.HasFlag(Role.Admin)
&& !isSelfUpdate
&& actorUser.UID > targetUser.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." });
}
targetUser.DisplayName = updatedUser.DisplayName ?? targetUser.DisplayName;
if (actorIsAdmin || isSelfUpdate)
{
targetUser.Visibility = updatedUser.Visibility ?? targetUser.Visibility;
}
if (actorIsAdmin)
{
targetUser.Roles = updatedUser.Roles ?? targetUser.Roles;
targetUser.IsBanned = updatedUser.IsBanned ?? targetUser.IsBanned;
}
await _db.SaveChangesAsync();
@@ -122,8 +194,12 @@ namespace SharpbinV3.Server.Controllers
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." });
var isSelfDelete = user.UUID == jwtUser.UUID;
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)
{
@@ -135,199 +211,85 @@ namespace SharpbinV3.Server.Controllers
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
else
else if (isSelfDelete && user.EmailVerified && !string.IsNullOrWhiteSpace(user.Email))
{
if (
string.IsNullOrEmpty(dto.Token)
|| !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() })
)
if (string.IsNullOrEmpty(dto.Token) || !await _authService.VerifyAccountDeletionToken(user, dto.Token))
{
return Unauthorized(new { message = "Invalid verification token." });
return Unauthorized(new { message = "Invalid account deletion verification token." });
}
}
var deletedEmail = user.EmailVerified ? user.Email : null;
var deletedUsername = user.Username;
_db.Users.Remove(user);
await _db.SaveChangesAsync();
if (!string.IsNullOrWhiteSpace(deletedEmail))
await _authService.SendAccountDeletedNotification(deletedEmail, deletedUsername);
return Ok(new { message = "User deleted successfully." });
}
[HttpPost]
[Route("{uuid}/report")]
[EnableRateLimiting("Sensitive")]
[HttpPost("uuid/{uuid}/delete-verification")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
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]
[Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
public async Task<IActionResult> RequestDeleteVerification(Guid uuid)
{
var jwtUser = HttpContext.GetJwtUser()!;
if (jwtUser.UUID != uuid)
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
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." });
if (user.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You cannot delete an admin user." });
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (jwtUser.TotpEnabled)
return BadRequest(new { success = false, message = "Use TOTP to delete this account." });
report.Type = reportType;
report.Description = request.Description ?? report.Description;
if (!user.EmailVerified || string.IsNullOrWhiteSpace(user.Email))
return BadRequest(new { success = false, message = "A verified email address is required for email deletion verification." });
await _db.SaveChangesAsync();
return Ok(new { success = true, message = "Report updated successfully." });
}
[HttpDelete]
[Route("{uuid}/report/{reportId}")]
[EnableRateLimiting("Sensitive")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
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]
[Authorize(Policy = "JwtOnly")]
[Route("{uuid}/reports")]
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
var result = await _authService.RequestAccountDeletionVerification(user);
if (!result.success)
{
if (result.retryAfter.HasValue)
{
Reports = reports,
Pagination = new
{
query.Page,
query.PageSize,
TotalCount = totalCount,
TotalPages = totalPages,
},
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
return StatusCode(
StatusCodes.Status429TooManyRequests,
new
{
success = false,
message = result.message,
retryAfter = result.retryAfter,
}
);
}
);
}
[HttpGet]
[Authorize(Policy = "JwtOnly")]
[Route("{uuid}/reports/submitted")]
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
{
var jwtUser = HttpContext.GetJwtUser()!;
return BadRequest(new { success = false, message = result.message });
}
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,
},
}
);
return Ok(new { success = true, message = result.message });
}
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
{
var isAuthenticatedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
var isRequestedUser = HttpContext.User?.FindFirst("uuid")?.Value == user.UUID.ToString();
var requester = HttpContext.GetJwtUser();
var requesterIsStaff = requester != null && (requester.Roles.HasFlag(Role.Admin) || requester.Roles.HasFlag(Role.Moderator));
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
if (!isAuthenticatedUser)
if (!isRequestedUser)
{
if (user.Visibility == Visibility.Private && (!user.Roles.HasFlag(Role.Admin) || !user.Roles.HasFlag(Role.Moderator)))
if (user.Visibility == Visibility.Private && !requesterIsStaff)
return NotFound();
if (requesterIsStaff)
pasteQuery = pasteQuery.Where(p => p.Visibility != Visibility.Private);
else if (user.Visibility == Visibility.Unlisted)
pasteQuery = pasteQuery.Where(p => p.Visibility != Visibility.Private);
else if (user.Visibility != Visibility.Unlisted)
pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
}
@@ -351,12 +313,14 @@ namespace SharpbinV3.Server.Controllers
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,
Likes = p.Interactions.Count(i => i.Type == Interaction.Positive),
Dislikes = p.Interactions.Count(i => i.Type == Interaction.Negative),
})
.ToListAsync();
@@ -368,7 +332,7 @@ namespace SharpbinV3.Server.Controllers
TotalPages = totalPages,
};
if (isAuthenticatedUser)
if (isRequestedUser)
{
var reports = await _reportService.GetReports(
new ReportQuery
@@ -0,0 +1,7 @@
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class AdminPasswordResetLinkDto
{
public string? TotpCode { get; set; }
}
}
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class ChangeEmailDto
{
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
public string? TotpCode { get; set; }
}
}
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class PasswordChangeDto
{
[Required]
public string CurrentPassword { get; set; } = string.Empty;
[Required]
[StringLength(128, MinimumLength = 8)]
public string NewPassword { get; set; } = string.Empty;
public string? TotpCode { get; set; }
}
}
@@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class PasswordResetDto
{
[Required]
public string Token { get; set; } = string.Empty;
[Required]
[StringLength(128, MinimumLength = 8)]
public string NewPassword { get; set; } = string.Empty;
public string? TotpCode { get; set; }
}
}
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class PasswordResetRequestDto
{
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
public string? Token { 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; }
}
}
@@ -10,14 +10,17 @@ namespace SharpbinV3.Server.DTOs.Paste
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 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; }
}
@@ -27,8 +30,8 @@ namespace SharpbinV3.Server.DTOs.Paste
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; }
}
@@ -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; }
+2 -1
View File
@@ -8,8 +8,9 @@ namespace SharpbinV3.Server.DTOs.User
public string? Username { get; set; }
public string? Email { get; set; }
[Required]
[StringLength(128, MinimumLength = 6)]
public string? Password { get; set; }
public required string Password { get; set; }
public string? Token { get; set; }
public string? TotpCode { get; set; }
}
+1 -1
View File
@@ -9,7 +9,7 @@ namespace SharpbinV3.Server.DTOs
{
public string? DisplayName { get; set; }
public string? Email { get; set; }
public Visibility? Visibility { get; set; } = Data.Enums.Visibility.Public;
public Visibility? Visibility { get; set; }
public Role? Roles { get; set; }
public bool? IsBanned { get; set; }
public string? TotpCode { get; set; }
@@ -5,7 +5,7 @@ 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;
+31
View File
@@ -7,12 +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)
{
@@ -40,6 +43,10 @@ namespace SharpbinV3.Server.Data
.HasIndex(r => r.TokenHash)
.IsUnique();
modelBuilder.Entity<User>()
.HasIndex(u => u.Email)
.IsUnique()
.HasFilter("\"Email\" IS NOT NULL");
modelBuilder.Entity<UserTotp>()
.HasOne(t => t.User)
@@ -59,6 +66,12 @@ namespace SharpbinV3.Server.Data
.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)
@@ -70,6 +83,24 @@ namespace SharpbinV3.Server.Data
.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);
}
}
}
@@ -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!;
}
}
@@ -17,6 +17,7 @@ namespace SharpbinV3.Server.Data.Entities
public required Guid UserUUID { get; set; }
public User User { get; set; } = null!;
public required string TokenHash { get; set; }
public string? TargetEmail { get; set; }
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public long ExpiresAt { get; set; }
public required EmailTokenType Type { get; set; }
+13 -7
View File
@@ -1,22 +1,21 @@
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(Size))]
[Index(nameof(StoredSize))]
public sealed class Paste
{
[Key]
public int PID { get; set; }
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; }
@@ -28,8 +27,8 @@ 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; }
@@ -40,5 +39,12 @@ namespace SharpbinV3.Server.Data.Entities
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();
+5 -2
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; }
@@ -48,6 +49,8 @@ namespace SharpbinV3.Server.Data.Entities
public enum ReportTargetType
{
Paste,
User
User,
Comment
}
}
+3 -1
View File
@@ -15,9 +15,10 @@ namespace SharpbinV3.Server.Data.Entities
[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();
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
@@ -39,6 +40,7 @@ namespace SharpbinV3.Server.Data.Entities
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,9 @@
namespace SharpbinV3.Server.Data.Enums
{
public enum SecurityAction
{
UpdateRoles = 1,
DeleteUser = 2,
GeneratePasswordResetLink = 3
}
}
+7 -1
View File
@@ -8,7 +8,13 @@ RUN dotnet publish SharpbinV3.Server.csproj -c Release -o /app/out
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app/out .
COPY SharpbinV3.Server/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN apt-get update && apt-get install -y wget && rm -rf /var/lib/apt/lists/*
RUN useradd --create-home --uid 10001 appuser \
&& mkdir -p /app/data \
&& chown -R appuser:appuser /app \
&& chmod +x /usr/local/bin/docker-entrypoint.sh
ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080
ENTRYPOINT ["dotnet", "SharpbinV3.Server.dll"]
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["dotnet", "SharpbinV3.Server.dll"]
@@ -0,0 +1,4 @@
<h2>Account Deleted</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Your Sharpbin account and all associated data have been permanently deleted.</p>
<p>No further action is needed.</p>
@@ -0,0 +1,6 @@
<h2>Confirm Account Deletion</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>A request was made to permanently delete your Sharpbin account and all associated data.</p>
<p>Use this verification code to confirm account deletion:</p>
<div class="link-box">{{DELETE_TOKEN}}</div>
<p>This code expires in 24 hours. If you did not request this, do not share this code.</p>
@@ -0,0 +1,5 @@
<h2>Email Change Requested</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Your Sharpbin account email is being changed from <strong>{{OLD_EMAIL}}</strong> to <strong>{{NEW_EMAIL}}</strong>.</p>
<p>If you made this change, no action is needed.</p>
<p>If you did not request this change, secure your account immediately by changing your password and reviewing your active sessions.</p>
@@ -0,0 +1,5 @@
<h2>Email Address Changed</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Your Sharpbin account email was changed from <strong>{{OLD_EMAIL}}</strong> to <strong>{{NEW_EMAIL}}</strong>.</p>
<p>If you made this change, no action is needed.</p>
<p>If you did not make this change, secure your account immediately by changing your password and reviewing your active sessions.</p>
@@ -0,0 +1,5 @@
<h2>Password Changed</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>The password for your Sharpbin account was just changed.</p>
<p>If you made this change, no action is needed.</p>
<p>If you did not make this change, secure your account immediately by changing your password again and reviewing active sessions.</p>
@@ -0,0 +1,12 @@
<h2>Reset Your Password</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>We received a request to reset the password for your Sharpbin account.</p>
<p style="text-align: center;">
<a href="{{RESET_URL}}" class="button">Reset Password</a>
</p>
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
<div class="link-box">
<a href="{{RESET_URL}}">{{RESET_URL}}</a>
</div>
<p><strong>This link will expire in 24 hours.</strong></p>
<p>If you didn't request a password reset, you can ignore this email.</p>
@@ -0,0 +1,12 @@
<h2>Verify Your New Email Address</h2>
<p>Hi <strong>{{USERNAME}}</strong>,</p>
<p>Confirm this email address for your Sharpbin account by clicking the button below.</p>
<p style="text-align: center;">
<a href="{{VERIFICATION_URL}}" class="button">Verify Email Address</a>
</p>
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
<div class="link-box">
<a href="{{VERIFICATION_URL}}">{{VERIFICATION_URL}}</a>
</div>
<p><strong>This link will expire in 24 hours.</strong></p>
<p>If you did not request this change, you can ignore this email.</p>
@@ -17,6 +17,25 @@ namespace SharpbinV3.Server.Extensions
"X-ProxyUser-IP",
];
public static readonly string[] BotUserAgents =
[
"bot",
"crawl",
"spider",
"slurp",
"mediapartners-google",
"adsbot-google",
"googlebot",
"bingbot",
"yandexbot",
"duckduckbot",
"baiduspider",
"sogou",
"exabot",
"facebot",
"ia_archiver",
];
private const string ApiKeyContextKey = "ApiKey";
private static string? GetClaimValue(IEnumerable<Claim> claims, params string[] claimTypes)
@@ -110,5 +129,11 @@ namespace SharpbinV3.Server.Extensions
}
return context.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
}
public static bool IsKnownBot(this HttpContext context)
{
var userAgent = context.Request.Headers.UserAgent.FirstOrDefault()?.ToLower() ?? "";
return BotUserAgents.Any(userAgent.Contains);
}
}
}
@@ -0,0 +1,615 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260424085542_InteractionsAndComments")]
partial class InteractionsAndComments
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("Size")
.HasColumnType("INTEGER");
b.Property<long>("TrueSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID");
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID");
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,243 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class InteractionsAndComments : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Pastes_PID",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_Size",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_UUID",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_Visibility",
table: "Pastes");
migrationBuilder.RenameColumn(
name: "TrueSize",
table: "Pastes",
newName: "StoredSize");
migrationBuilder.RenameColumn(
name: "Size",
table: "Pastes",
newName: "OriginalSize");
migrationBuilder.AddColumn<long>(
name: "CommentID",
table: "Reports",
type: "INTEGER",
nullable: true);
migrationBuilder.CreateTable(
name: "Comments",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
PastePID = table.Column<long>(type: "INTEGER", nullable: false),
ParentCommentID = table.Column<long>(type: "INTEGER", nullable: true),
Content = table.Column<byte[]>(type: "BLOB", maxLength: 5000, nullable: true),
Size = table.Column<long>(type: "INTEGER", nullable: false),
TrueSize = table.Column<long>(type: "INTEGER", nullable: false),
IsCompressed = table.Column<bool>(type: "INTEGER", nullable: false),
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
UpdatedAt = table.Column<long>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Comments", x => x.Id);
table.ForeignKey(
name: "FK_Comments_Comments_ParentCommentID",
column: x => x.ParentCommentID,
principalTable: "Comments",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Comments_Pastes_PastePID",
column: x => x.PastePID,
principalTable: "Pastes",
principalColumn: "PID",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Comments_Users_UserUUID",
column: x => x.UserUUID,
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "PasteInteractions",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
PasteID = table.Column<long>(type: "INTEGER", nullable: false),
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
Type = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PasteInteractions", x => x.Id);
table.ForeignKey(
name: "FK_PasteInteractions_Pastes_PasteID",
column: x => x.PasteID,
principalTable: "Pastes",
principalColumn: "PID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "CommentInteractions",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
CommentID = table.Column<long>(type: "INTEGER", nullable: false),
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
Type = table.Column<int>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CommentInteractions", x => x.Id);
table.ForeignKey(
name: "FK_CommentInteractions_Comments_CommentID",
column: x => x.CommentID,
principalTable: "Comments",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Reports_CommentID",
table: "Reports",
column: "CommentID");
migrationBuilder.CreateIndex(
name: "IX_Pastes_StoredSize",
table: "Pastes",
column: "StoredSize");
migrationBuilder.CreateIndex(
name: "IX_Pastes_UUID",
table: "Pastes",
column: "UUID");
migrationBuilder.CreateIndex(
name: "IX_CommentInteractions_CommentID",
table: "CommentInteractions",
column: "CommentID");
migrationBuilder.CreateIndex(
name: "IX_Comments_ParentCommentID",
table: "Comments",
column: "ParentCommentID");
migrationBuilder.CreateIndex(
name: "IX_Comments_PastePID",
table: "Comments",
column: "PastePID");
migrationBuilder.CreateIndex(
name: "IX_Comments_UserUUID",
table: "Comments",
column: "UserUUID");
migrationBuilder.CreateIndex(
name: "IX_PasteInteractions_PasteID",
table: "PasteInteractions",
column: "PasteID");
migrationBuilder.AddForeignKey(
name: "FK_Reports_Comments_CommentID",
table: "Reports",
column: "CommentID",
principalTable: "Comments",
principalColumn: "Id",
onDelete: ReferentialAction.SetNull);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Reports_Comments_CommentID",
table: "Reports");
migrationBuilder.DropTable(
name: "CommentInteractions");
migrationBuilder.DropTable(
name: "PasteInteractions");
migrationBuilder.DropTable(
name: "Comments");
migrationBuilder.DropIndex(
name: "IX_Reports_CommentID",
table: "Reports");
migrationBuilder.DropIndex(
name: "IX_Pastes_StoredSize",
table: "Pastes");
migrationBuilder.DropIndex(
name: "IX_Pastes_UUID",
table: "Pastes");
migrationBuilder.DropColumn(
name: "CommentID",
table: "Reports");
migrationBuilder.RenameColumn(
name: "StoredSize",
table: "Pastes",
newName: "TrueSize");
migrationBuilder.RenameColumn(
name: "OriginalSize",
table: "Pastes",
newName: "Size");
migrationBuilder.CreateIndex(
name: "IX_Pastes_PID",
table: "Pastes",
column: "PID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Pastes_Size",
table: "Pastes",
column: "Size");
migrationBuilder.CreateIndex(
name: "IX_Pastes_UUID",
table: "Pastes",
column: "UUID",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Pastes_Visibility",
table: "Pastes",
column: "Visibility");
}
}
}
@@ -0,0 +1,621 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260424090002_IndexInteractions")]
partial class IndexInteractions
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("Size")
.HasColumnType("INTEGER");
b.Property<long>("TrueSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID", "Type");
b.HasIndex("CommentID", "UserUUID")
.IsUnique();
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID", "Type");
b.HasIndex("PasteID", "UserUUID")
.IsUnique();
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany()
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,74 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class IndexInteractions : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_PasteInteractions_PasteID",
table: "PasteInteractions");
migrationBuilder.DropIndex(
name: "IX_CommentInteractions_CommentID",
table: "CommentInteractions");
migrationBuilder.CreateIndex(
name: "IX_PasteInteractions_PasteID_Type",
table: "PasteInteractions",
columns: new[] { "PasteID", "Type" });
migrationBuilder.CreateIndex(
name: "IX_PasteInteractions_PasteID_UserUUID",
table: "PasteInteractions",
columns: new[] { "PasteID", "UserUUID" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_CommentInteractions_CommentID_Type",
table: "CommentInteractions",
columns: new[] { "CommentID", "Type" });
migrationBuilder.CreateIndex(
name: "IX_CommentInteractions_CommentID_UserUUID",
table: "CommentInteractions",
columns: new[] { "CommentID", "UserUUID" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_PasteInteractions_PasteID_Type",
table: "PasteInteractions");
migrationBuilder.DropIndex(
name: "IX_PasteInteractions_PasteID_UserUUID",
table: "PasteInteractions");
migrationBuilder.DropIndex(
name: "IX_CommentInteractions_CommentID_Type",
table: "CommentInteractions");
migrationBuilder.DropIndex(
name: "IX_CommentInteractions_CommentID_UserUUID",
table: "CommentInteractions");
migrationBuilder.CreateIndex(
name: "IX_PasteInteractions_PasteID",
table: "PasteInteractions",
column: "PasteID");
migrationBuilder.CreateIndex(
name: "IX_CommentInteractions_CommentID",
table: "CommentInteractions",
column: "CommentID");
}
}
}
@@ -0,0 +1,623 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260424091805_RenameCommentSizes")]
partial class RenameCommentSizes
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID", "Type");
b.HasIndex("CommentID", "UserUUID")
.IsUnique();
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID", "Type");
b.HasIndex("PasteID", "UserUUID")
.IsUnique();
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Comments")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Comments");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class RenameCommentSizes : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "TrueSize",
table: "Comments",
newName: "StoredSize");
migrationBuilder.RenameColumn(
name: "Size",
table: "Comments",
newName: "OriginalSize");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "StoredSize",
table: "Comments",
newName: "TrueSize");
migrationBuilder.RenameColumn(
name: "OriginalSize",
table: "Comments",
newName: "Size");
}
}
}
@@ -0,0 +1,626 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260614000001_NormalizeUsernames")]
partial class NormalizeUsernames
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID", "Type");
b.HasIndex("CommentID", "UserUUID")
.IsUnique();
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID", "Type");
b.HasIndex("PasteID", "UserUUID")
.IsUnique();
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Comments")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Comments");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class NormalizeUsernames : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@"UPDATE Users SET Username = lower(Username);");
migrationBuilder.CreateIndex(
name: "IX_Users_Username",
table: "Users",
column: "Username",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_Username",
table: "Users");
}
}
}
@@ -0,0 +1,629 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260618030444_EmailChangeTokens")]
partial class EmailChangeTokens
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID", "Type");
b.HasIndex("CommentID", "UserUUID")
.IsUnique();
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TargetEmail")
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID", "Type");
b.HasIndex("PasteID", "UserUUID")
.IsUnique();
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Comments")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Comments");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class EmailChangeTokens : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "TargetEmail",
table: "EmailVerificationTokens",
type: "TEXT",
nullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "TargetEmail",
table: "EmailVerificationTokens");
}
}
}
@@ -0,0 +1,633 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SharpbinV3.Server.Data;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260618231408_uniqueEmails")]
partial class uniqueEmails
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("KeyHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long?>("LastUsedAt")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID", "Type");
b.HasIndex("CommentID", "UserUUID")
.IsUnique();
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TargetEmail")
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("UUID");
b.HasIndex("UserUUID");
b.ToTable("EmailVerificationTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<Guid?>("AuthorUUID")
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long?>("EditedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("ID")
.HasColumnType("TEXT");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
.HasColumnType("TEXT");
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
b.Property<int>("Views")
.HasColumnType("INTEGER");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("PID");
b.HasIndex("AuthorUUID");
b.HasIndex("ExpiresAt");
b.HasIndex("ID")
.IsUnique();
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID");
b.HasIndex("Views");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID", "Type");
b.HasIndex("PasteID", "UserUUID")
.IsUnique();
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
.HasColumnType("INTEGER");
b.Property<string>("ViewerHash")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PastePID", "ViewerHash")
.IsUnique();
b.ToTable("PasteViews");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("ExpiresAt")
.HasColumnType("TEXT");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("ReplacedByToken")
.HasColumnType("TEXT");
b.Property<bool>("Revoked")
.HasColumnType("INTEGER");
b.Property<byte[]>("RowVersion")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("TokenHash")
.IsUnique();
b.HasIndex("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.Property<int>("ReportID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("Description")
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
.HasColumnType("TEXT");
b.Property<int>("Status")
.HasColumnType("INTEGER");
b.Property<int>("TargetType")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid?>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
.IsUnique();
b.HasIndex("ReporterUUID");
b.HasIndex("TargetType");
b.HasIndex("UserUUID");
b.ToTable("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
b.Property<bool>("EmailVerified")
.HasColumnType("INTEGER");
b.Property<bool>("IsBanned")
.HasColumnType("INTEGER");
b.Property<long?>("LastLogin")
.HasColumnType("INTEGER");
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("Visibility")
.HasColumnType("INTEGER");
b.HasKey("UUID");
b.HasIndex("Email")
.IsUnique()
.HasFilter("\"Email\" IS NOT NULL");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<byte[]>("EncryptedSecret")
.IsRequired()
.HasColumnType("BLOB");
b.HasKey("UserUUID");
b.ToTable("UserTotps");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("ApiKeys")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Comments")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("EmailVerificationTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Pastes")
.HasForeignKey("AuthorUUID")
.OnDelete(DeleteBehavior.Cascade);
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("PasteViews")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("RefreshTokens")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Reports")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.SetNull);
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithOne("Totp")
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Navigation("ApiKeys");
b.Navigation("Comments");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Reports");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class uniqueEmails : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(
"""
UPDATE "Users"
SET "Email" = NULL, "EmailVerified" = 0
WHERE "Email" IS NULL OR trim("Email") = '';
"""
);
migrationBuilder.Sql(
"""
UPDATE "Users"
SET "Email" = lower(trim("Email"))
WHERE "Email" IS NOT NULL;
"""
);
migrationBuilder.CreateIndex(
name: "IX_Users_Email",
table: "Users",
column: "Email",
unique: true,
filter: "\"Email\" IS NOT NULL");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_Users_Email",
table: "Users");
}
}
}
@@ -47,6 +47,79 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("ApiKeys");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<byte[]>("Content")
.HasMaxLength(5000)
.HasColumnType("BLOB");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long?>("ParentCommentID")
.HasColumnType("INTEGER");
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<long?>("UpdatedAt")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("ParentCommentID");
b.HasIndex("PastePID");
b.HasIndex("UserUUID");
b.ToTable("Comments");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("CommentID", "Type");
b.HasIndex("CommentID", "UserUUID")
.IsUnique();
b.ToTable("CommentInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.Property<Guid>("UUID")
@@ -59,6 +132,9 @@ namespace SharpbinV3.Server.Migrations
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("TargetEmail")
.HasColumnType("TEXT");
b.Property<string>("TokenHash")
.IsRequired()
.HasColumnType("TEXT");
@@ -81,7 +157,7 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Property<int>("PID")
b.Property<long>("PID")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
@@ -107,7 +183,10 @@ namespace SharpbinV3.Server.Migrations
b.Property<bool>("IsCompressed")
.HasColumnType("INTEGER");
b.Property<long>("Size")
b.Property<long>("OriginalSize")
.HasColumnType("INTEGER");
b.Property<long>("StoredSize")
.HasColumnType("INTEGER");
b.Property<string>("Syntax")
@@ -116,9 +195,6 @@ namespace SharpbinV3.Server.Migrations
b.Property<string>("Title")
.HasColumnType("TEXT");
b.Property<long>("TrueSize")
.HasColumnType("INTEGER");
b.Property<Guid>("UUID")
.HasColumnType("TEXT");
@@ -137,30 +213,52 @@ namespace SharpbinV3.Server.Migrations
b.HasIndex("ID")
.IsUnique();
b.HasIndex("PID")
.IsUnique();
b.HasIndex("Size");
b.HasIndex("StoredSize");
b.HasIndex("Syntax");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("UUID");
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("PasteID")
.HasColumnType("INTEGER");
b.Property<int>("Type")
.HasColumnType("INTEGER");
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("PasteID", "Type");
b.HasIndex("PasteID", "UserUUID")
.IsUnique();
b.ToTable("PasteInteractions");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("PastePID")
b.Property<long>("PastePID")
.HasColumnType("INTEGER");
b.Property<long>("ViewedAt")
@@ -231,6 +329,9 @@ namespace SharpbinV3.Server.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("CommentID")
.HasColumnType("INTEGER");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
@@ -238,7 +339,7 @@ namespace SharpbinV3.Server.Migrations
.HasMaxLength(1000)
.HasColumnType("TEXT");
b.Property<int?>("PastePID")
b.Property<long?>("PastePID")
.HasColumnType("INTEGER");
b.Property<Guid>("ReporterUUID")
@@ -261,6 +362,8 @@ namespace SharpbinV3.Server.Migrations
b.HasKey("ReportID");
b.HasIndex("CommentID");
b.HasIndex("PastePID");
b.HasIndex("ReportID")
@@ -306,7 +409,7 @@ namespace SharpbinV3.Server.Migrations
b.Property<int>("Roles")
.HasColumnType("INTEGER");
b.Property<int?>("UID")
b.Property<long?>("UID")
.HasColumnType("INTEGER");
b.Property<string>("Username")
@@ -318,11 +421,18 @@ namespace SharpbinV3.Server.Migrations
b.HasKey("UUID");
b.HasIndex("Email")
.IsUnique()
.HasFilter("\"Email\" IS NOT NULL");
b.HasIndex("UID");
b.HasIndex("UUID")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users");
});
@@ -354,6 +464,43 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "ParentComment")
.WithMany("Replies")
.HasForeignKey("ParentCommentID")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Comments")
.HasForeignKey("PastePID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
.WithMany("Comments")
.HasForeignKey("UserUUID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("ParentComment");
b.Navigation("Paste");
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.CommentInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", "Comment")
.WithMany("Interactions")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Comment");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
@@ -375,6 +522,17 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteInteraction", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Interactions")
.HasForeignKey("PasteID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Paste");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
@@ -399,6 +557,11 @@ namespace SharpbinV3.Server.Migrations
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
{
b.HasOne("SharpbinV3.Server.Data.Entities.Comment", null)
.WithMany("Reports")
.HasForeignKey("CommentID")
.OnDelete(DeleteBehavior.SetNull);
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
.WithMany("Reports")
.HasForeignKey("PastePID")
@@ -425,8 +588,21 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Comment", b =>
{
b.Navigation("Interactions");
b.Navigation("Replies");
b.Navigation("Reports");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{
b.Navigation("Comments");
b.Navigation("Interactions");
b.Navigation("PasteViews");
b.Navigation("Reports");
@@ -436,6 +612,8 @@ namespace SharpbinV3.Server.Migrations
{
b.Navigation("ApiKeys");
b.Navigation("Comments");
b.Navigation("EmailVerificationTokens");
b.Navigation("Pastes");

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