Compare commits

..
Author SHA1 Message Date
whoswhip 892624f6ac fix: properly resolve dynamic urls 2026-11-06 08:36:32 -05:00
whoswhip eed65b754e refactor: improve encryption performance and safety
also fixed some issues i saw related to dynamic urls being resolved improperly
formatted via prettier
2026-11-06 08:25:26 -05:00
whoswhip 22c144e970 chore: bump version 2026-10-18 11:59:59 -04:00
whoswhip 336990f5b8 style: separate comments from the paste container 2026-10-18 11:55:39 -04:00
whoswhip 45878d5af1 omfg, actually fix #lib imports 2026-10-18 11:47:06 -04:00
whoswhip 2c43c0b29c chore(deps): update nuget packages for security 2026-10-18 11:24:29 -04:00
whoswhip 0e3a6d97e3 fix: use node env instead of sveltekit env 2026-10-11 22:15:13 -04:00
whoswhip 878457f49d fix #lib 2026-10-10 21:32:51 -04:00
whoswhip 8d060204c8 fix: use #lib instead of $lib 2026-10-10 21:29:02 -04:00
whoswhip f2559eaad0 fix: update TypeScript configuration to extend from $app/tsconfig and adjust include/exclude paths 2026-10-10 21:04:04 -04:00
whoswhip e485b9782b fix node adapter 2026-10-10 20:33:08 -04:00
whoswhip ed7e82adc2 Merge branch 'SharpbinV3' of github.com:whoswhip/Sharpbin into SharpbinV3 2026-10-10 13:34:52 -04:00
whoswhip f8a74d415d Merge pull request #27 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-b9088de85f
chore(deps): bump the npm_and_yarn group across 1 directory with 6 updates
2026-10-10 13:33:41 -04:00
dependabot[bot] 41342efbed chore(deps): bump the npm_and_yarn group across 1 directory with 6 updates
Bumps the npm_and_yarn group with 6 updates in the /SharpbinV3.Client directory:

| Package | From | To |
| --- | --- | --- |
| [dompurify](https://github.com/cure53/DOMPurify) | `3.4.14` | `3.4.16` |
| [sharp](https://github.com/lovell/sharp) | `0.35.4` | `0.35.5` |
| [brace-expansion](https://github.com/juliangruber/brace-expansion) | `1.1.18` | `1.1.21` |
| [cookie](https://github.com/jshttp/cookie) | `0.6.0` | `2.0.1` |
| [handlebars](https://github.com/handlebars-lang/handlebars.js) | `4.7.9` | `4.7.10` |
| [source-map-js](https://github.com/7rulnik/source-map-js) | `1.2.1` | `1.2.2` |



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

Updates `sharp` from 0.35.4 to 0.35.5
- [Release notes](https://github.com/lovell/sharp/releases)
- [Commits](https://github.com/lovell/sharp/compare/v0.35.4...v0.35.5)

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

Updates `cookie` from 0.6.0 to 2.0.1
- [Release notes](https://github.com/jshttp/cookie/releases)
- [Commits](https://github.com/jshttp/cookie/compare/v0.6.0...v2.0.1)

Updates `handlebars` from 4.7.9 to 4.7.10
- [Release notes](https://github.com/handlebars-lang/handlebars.js/releases)
- [Changelog](https://github.com/handlebars-lang/handlebars.js/blob/v4.7.10/release-notes.md)
- [Commits](https://github.com/handlebars-lang/handlebars.js/compare/v4.7.9...v4.7.10)

Updates `source-map-js` from 1.2.1 to 1.2.2
- [Release notes](https://github.com/7rulnik/source-map-js/releases)
- [Changelog](https://github.com/7rulnik/source-map-js/blob/main/CHANGELOG.md)
- [Commits](https://github.com/7rulnik/source-map-js/compare/v1.2.1...v1.2.2)

---
updated-dependencies:
- dependency-name: dompurify
  dependency-version: 3.4.16
  dependency-type: direct:production
  dependency-group: npm_and_yarn
- dependency-name: sharp
  dependency-version: 0.35.5
  dependency-type: direct:production
  dependency-group: npm_and_yarn
- dependency-name: brace-expansion
  dependency-version: 1.1.21
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: cookie
  dependency-version: 2.0.1
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: handlebars
  dependency-version: 4.7.10
  dependency-type: indirect
  dependency-group: npm_and_yarn
- dependency-name: source-map-js
  dependency-version: 1.2.2
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-10 03:19:03 +00:00
whoswhip e7a28ea8c0 Merge pull request #26 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-e422db4233
chore(deps): bump devalue from 5.8.1 to 5.9.4 in /SharpbinV3.Client in the npm_and_yarn group across 1 directory
2026-10-09 23:17:00 -04:00
whoswhip e375b0a020 refactor: simplify configuration to a single env file 2026-09-26 19:40:36 -04:00
whoswhip ee8b8f239d docs: fix example secrets 2026-09-26 15:26:00 -04:00
dependabot[bot] eb331f7339 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.8.1 to 5.9.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.8.1...v5.9.4)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-26 19:20:42 +00:00
whoswhip b304d8ac9f chore: update node to 24 in ci and docker 2026-09-26 15:19:29 -04:00
whoswhip d45f253c00 fix: normalize cononical 2026-09-14 18:58:28 -04:00
whoswhip b0e9f5104c fix: remove trailing '.' in filename
firefox removes it but chrome sanitizes it to '_'
2026-09-13 18:35:24 -04:00
whoswhip da79f3713a Merge pull request #25 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/npm_and_yarn-c2134247b9
chore(deps): bump the npm_and_yarn group across 1 directory with 2 updates
2026-09-13 18:31:28 -04:00
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
109 changed files with 5852 additions and 2071 deletions
+3 -1
View File
@@ -1,6 +1,8 @@
**/.classpath
**/.dockerignore
**/.env
**/backend.env
**/frontend.env
**/.git
**/.gitignore
**/.project
@@ -27,4 +29,4 @@ README.md
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**
!.git/refs/heads/**
+26
View File
@@ -0,0 +1,26 @@
# Copy to .env in the repository root. Replace every replace_with_ value before running.
# Generate a different random value for each secret. See README.md for instructions.
# Site
Domain=example.com
Https=true
AllowedCorsOrigins__0=https://example.com
ORIGIN=https://example.com
# Authentication
JwtSettings__Secret=replace_with_a_unique_random_jwt_secret_before_running
# These Turnstile keys are for testing. Use your own site and secret keys in production.
AuthSettings__CF_Turnstile_SecretKey=1x0000000000000000000000000000000AA
AuthSettings__CF_Turnstile_SiteKey=3x00000000000000000000FF
AuthSettings__Registration_Enabled=true
AuthSettings__Admins_Require_2FA=true
AuthSettings__API_Key_HMAC_Secret=replace_with_a_unique_random_api_key_hmac_secret_before_running
# Pastes
PasteSettings__MaxTitleLength=500
PasteSettings__MaxPasteSizeInBytes=1048576
PasteSettings__EnablePasteCompression=true
PasteSettings__RequiresVerification=true
PasteSettings__View_HMAC_Secret=replace_with_a_unique_random_view_hmac_secret_before_running
# Compose passes this value to both services. No separate frontend key is needed.
PasteSettings__View_Internal_API_Key=replace_with_a_unique_random_internal_api_key_before_running
+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: 24
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
+3 -1
View File
@@ -325,4 +325,6 @@ Data
!SharpbinV3.Server/Data
.idea
**/.env
**/.env
backend.env
frontend.env
+53
View File
@@ -1,3 +1,56 @@
## [3.1.0](https://github.com/whoswhip/Sharpbin/compare/v3.0.5...v3.1.0) (2026-10-18)
### Bug Fixes
* add docker entrypoint sccript ([045a193](https://github.com/whoswhip/Sharpbin/commit/045a1934d80277b75b34d7566ea283c57a7b1e83))
* add tooltip to comment timestamp for better context ([c98e5e5](https://github.com/whoswhip/Sharpbin/commit/c98e5e53b02002ac0328947cdbabddaa60ebe877))
* allow null display name when saving display name ([20473da](https://github.com/whoswhip/Sharpbin/commit/20473da0bacc891354ef75cd05b4fdb3443ae629))
* always underline users in comments ([e239bf2](https://github.com/whoswhip/Sharpbin/commit/e239bf2ae5a4ca0f93cfc197d9658df459b87d10))
* compact paste smaller; better edited display ([e8cd93e](https://github.com/whoswhip/Sharpbin/commit/e8cd93e7bdfc47e0c105935182c7062fd191cb57))
* disable but show buttons for author or anon users ([77f6623](https://github.com/whoswhip/Sharpbin/commit/77f6623fcf6b9b50e26ce533cee7b83c26836051))
* disable styles on comment reactions ([23f0c92](https://github.com/whoswhip/Sharpbin/commit/23f0c92aed9bd8235ad1cc6b62aa3c9bf8674370))
* disabled:cursor-not-allowed on like buttons ([95a5c18](https://github.com/whoswhip/Sharpbin/commit/95a5c18dc57ad33701bbd6d9f5cfcf6a1cda6f49))
* enforce 2fa only on certain update actions ([a55268a](https://github.com/whoswhip/Sharpbin/commit/a55268afdc171d3d7f074ee008be3434e14c0482))
* enhance user update permissions and authentication checks ([6c810b0](https://github.com/whoswhip/Sharpbin/commit/6c810b07b738ca2cb0cfe87c264e26395254024b))
* handle username conflict during user creation ([f5a7aab](https://github.com/whoswhip/Sharpbin/commit/f5a7aabf42a67969baf6e307b3178e89c75a4716))
* improve paste description ([60796a8](https://github.com/whoswhip/Sharpbin/commit/60796a85fb3f287cc88d42dda7f9bc446d0d5f97))
* include '.' before extension on paste download ([ee6a6d5](https://github.com/whoswhip/Sharpbin/commit/ee6a6d5e6d3f4d5ef2fb2c8f6032e695b228fcf9))
* lower vulnerabilities + harden docker setup ([d16f1f8](https://github.com/whoswhip/Sharpbin/commit/d16f1f872fa34de460f9ee8903b4eefbe780c041))
* make cursor-not-allowed !important ([9916930](https://github.com/whoswhip/Sharpbin/commit/99169305c7b496eef51cfb5493cd3c8548f366e7))
* multiple vulnerabilities ([6a7b865](https://github.com/whoswhip/Sharpbin/commit/6a7b8653dc154366c85de32dccf242a071eebdf0))
* normalize canonical URL to prevent duplicate content issues ([ad693b2](https://github.com/whoswhip/Sharpbin/commit/ad693b28ea701554fceede1f8e30e7990240281c))
* normalize cononical ([d45f253](https://github.com/whoswhip/Sharpbin/commit/d45f253c000e834db584fed89ddb541c09f466c7))
* only show report button if logged in ([40c6ac6](https://github.com/whoswhip/Sharpbin/commit/40c6ac663f95c40a154dc56598bdfe6e59f38703))
* prevent admins and moderators from being reported ([f2c67ae](https://github.com/whoswhip/Sharpbin/commit/f2c67ae3677658efaf84811271f62c5043797460))
* prevent authors from reacting to their pas6te ([3da7f99](https://github.com/whoswhip/Sharpbin/commit/3da7f99feba4aaaa02a6e9f0c7771a548e6530c3))
* remove recipient information from warning log when email settings are incomplete ([b65d3f8](https://github.com/whoswhip/Sharpbin/commit/b65d3f8726f77f2b7260e97ba439bfea4e2ad908))
* remove trailing '.' in filename ([b0e9f51](https://github.com/whoswhip/Sharpbin/commit/b0e9f5104c92a3cb6a8965d23460c86a64595d12))
* show uncompressed size in stats ([61efbf8](https://github.com/whoswhip/Sharpbin/commit/61efbf8b0415fe159b5e777f737ee4e8b25beb02))
* sizeStored -> StoredSize in typescript paste type ([6c65a52](https://github.com/whoswhip/Sharpbin/commit/6c65a52ee06c266eeeb5519e779eb49f73be33b7))
* update robots.txt to specify allowed and disallowed paths for web crawlers ([ea634fd](https://github.com/whoswhip/Sharpbin/commit/ea634fd85135d2996e96f6a48ce2fbccbb75b7e2))
* update TypeScript configuration to extend from $app/tsconfig and adjust include/exclude paths ([f2559ea](https://github.com/whoswhip/Sharpbin/commit/f2559eaad0ac79ac2ee18f3b9388ce62b11b5543))
* use #lib instead of $lib ([8d06020](https://github.com/whoswhip/Sharpbin/commit/8d060204c890018f49147e681f94a6737ac1c4b1)), closes [#lib](https://github.com/whoswhip/Sharpbin/issues/lib)
* use node env instead of sveltekit env ([0e3a6d9](https://github.com/whoswhip/Sharpbin/commit/0e3a6d97e395c605d419c2464c3b7fccbcdd5c6f))
### Features
* add /[@username](https://github.com/username) redirect to /user/username ([70e637b](https://github.com/whoswhip/Sharpbin/commit/70e637b281ae060e40ceb6e312591276d1c68540))
* add bot detection to skip recording views for known bots ([41d4411](https://github.com/whoswhip/Sharpbin/commit/41d441135cdef6c22df34a512507ef7032009db9))
* add sub tab to the settings tab ([e20a620](https://github.com/whoswhip/Sharpbin/commit/e20a6200dd3c1f0dfe26645c625cac448dc50d76))
* allow staff members to see user's unlisted pastes; show dislikes in the paste lists ([6ed2974](https://github.com/whoswhip/Sharpbin/commit/6ed2974e42df9d10da755af6897b4eea4ee6d34a))
* **auth:** enhance token management and synchronization with user data ([2864c81](https://github.com/whoswhip/Sharpbin/commit/2864c81f83ca49032a803f8ca2ccad19a1f8d9fe))
* comments & paste/comment reactions; renames/refactors ([63b77be](https://github.com/whoswhip/Sharpbin/commit/63b77bece9b71d547d15403257da44e8597db97b))
* **comments:** implement delete comment functionality with confirmation modal ([95ca811](https://github.com/whoswhip/Sharpbin/commit/95ca811d4295759b3fc161eff9ba81c7499be254))
* **comments:** implement recursive comment deletion in HardDeleteComment method ([8d3caf5](https://github.com/whoswhip/Sharpbin/commit/8d3caf5375a8065281b917b1c24970580799a059))
* enhance SEO for home, recent, and paste pages ([edffd54](https://github.com/whoswhip/Sharpbin/commit/edffd5490fae8274293982ded81c7971b614fd28))
* improve rate limit partition keys + less strict limits ([6cadc0b](https://github.com/whoswhip/Sharpbin/commit/6cadc0b74d3b5cb340347b1fc8dbaf8f06318e5b))
* **modal:** refactor modal types and integrate security action requirements ([f82d314](https://github.com/whoswhip/Sharpbin/commit/f82d314d80dcd8e70f197c254bb4e7ba2fee67f0))
* password resets ([d4976ac](https://github.com/whoswhip/Sharpbin/commit/d4976ac9aac41cb7ad23070480862bf2cec89095))
## [3.0.5](https://github.com/whoswhip/Sharpbin/compare/v3.0.4...v3.0.5) (2026-03-31)
+44 -10
View File
@@ -26,15 +26,45 @@ The easiest way to run SharpbinV3 is using Docker Compose.
git clone https://github.com/whoswhip/Sharpbin.git
```
3. Run the following command in the root directory:
3. In the repository root, copy `.env.example` to `.env`.
4. Replace the secret placeholders and configure your domain and Turnstile keys. Set `ORIGIN` to the public frontend URL, including the scheme. For local Docker testing, use `ORIGIN=http://localhost:5173`, `Domain=localhost:5173`, `Https=false`, and `AllowedCorsOrigins__0=http://localhost:5173`.
5. Run the following command in the root directory:
```bash
docker-compose up -d
docker compose up -d --build
```
### Configuration
You can configure Sharpbin using environment variables or `appsettings.json`. When using Docker Compose, these can be set in the `docker-compose.yml` file.
Configure Sharpbin in the root `.env` file when using Docker Compose. The backend loads this file as environment variables. Compose passes only the backend URL, public origin, and shared view-recording key to the frontend.
The backend image includes `appsettings.json` with application defaults. Environment variables have priority, so you do not need to edit or mount that file for normal setup. Additional backend settings, including `EmailSettings__Host` and other SMTP settings, can be added to `.env` using their existing names.
Compose defaults the database to `/app/data/sharpbin.db`, Data Protection keys to `/app/data/keys`, and `VITE_API_URL` to `http://backend:8080`. To override them, add `ConnectionStrings__DefaultConnection`, `DATA_PROTECTION_KEY_PATH`, or `VITE_API_URL` to `.env`. Keep database and key paths under `/app/data` to use the existing persistent volume.
The example secrets are placeholders, not secure defaults. Generate a separate secret for JWT signing, API-key hashing, and view hashing, plus one shared internal API key. This command generates a 64-character random hex value; run it once for each secret:
```bash
docker run --rm node:24-alpine node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
```
or use openSSL:
```bash
openssl rand -hex 32
```
Set the shared key once as `PasteSettings__View_Internal_API_Key`. Compose supplies it to the frontend as `VIEW_INTERNAL_API_KEY`. Keep generated secrets across restarts and updates. Changing the API-key HMAC secret invalidates existing API keys.
#### Migrating an Existing Installation
1. Copy the values from `backend.env` into the root `.env` file. If `.env` already exists, merge the settings without replacing existing values blindly.
2. Copy `ORIGIN` from `frontend.env`. If it was unset, use your public frontend URL, including the scheme.
3. Keep `PasteSettings__View_Internal_API_Key` set to the existing shared key. The separate `VIEW_INTERNAL_API_KEY` entry is no longer needed for Compose.
4. Move any custom `appsettings.json` values into `.env` using `__` for nested settings. For array settings, use numbered entries such as `AllowedCorsOrigins__0`. If you need to retain a custom JSON file, add a read-only mount for it in `compose.override.yaml`.
5. Run `docker compose up -d --build`. The old `backend.env` and `frontend.env` files are no longer read by Compose.
Keep the existing database volume, Data Protection keys, and secret values. Do not regenerate secrets during this migration.
> When configuring via `appsettings.json` instead of for example `ConnectionStrings__DefaultConnection` it would be:
@@ -47,9 +77,10 @@ You can configure Sharpbin using environment variables or `appsettings.json`. Wh
#### Backend (SharpbinV3.Server)
- `Domain`: The domain your instance of Sharpbin will be hosted at (e.g., example.com)
- `Https`: Whether or not your instance is behind https. Used when sendings emails.
- `Https`: Whether the public instance uses HTTPS. Used when generating email links; this does not enable TLS on the server.
- `AllowedCorsOrigins__0`: An allowed browser origin for the backend API (e.g., `https://example.com`). Use numbered entries for additional origins.
- `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=/app/data/sharpbin.db`).
- `JwtSettings__Secret`: A secure string used for signing JWT tokens.
- `JwtSettings__Secret`: A random secret of 32-128 characters used for signing JWT tokens.
- `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key.
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
- `AuthSettings__Registration_Enabled`:**true**: Enables/disables registration.
@@ -60,14 +91,17 @@ You can configure Sharpbin using environment variables or `appsettings.json`. Wh
- `PasteSettings__MaxPasteSizeInBytes`:**1_048_576** (1MB): Max Paste Size set in bytes.
- `PasteSettings__EnablePasteCompression`:**true**: Enables/Disables server-side paste compression.
- `PasteSettings__RequiresVerification`:**true**: Enables/Disables CAPTCHA verification when creating pastes.
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers
- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
- `PasteSettings__View_HMAC_Secret`: A required random secret of 32–128 characters used to hash viewer identifiers.
- `PasteSettings__View_Internal_API_Key`: A shared key of 32–128 characters used to authorize view recording. Compose passes it to both services.
#### Frontend (SharpbinV3.Client)
- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`).
- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.cc`)
- `VIEW_INTERNAL_API_KEY`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
- `VITE_API_URL`: The backend URL reachable from the frontend server. Defaults to `http://localhost:5050` when running directly and `http://backend:8080` in Compose. Browser requests use the frontend's `/api` proxy.
- `ORIGIN`: The public frontend URL, including its scheme (e.g., `https://example.com`). Used by the production Node server; see [SvelteKit's Node adapter documentation](https://svelte.dev/docs/kit/adapter-node#ORIGIN-PROTOCOL_HEADER-HOST_HEADER-and-PORT_HEADER).
- `VITE_ALLOWED_HOSTS`: A comma-separated list used only by Vite dev/preview (e.g., `localhost,sharpbin.cc`). Export it in the shell before starting Vite; the config reads `process.env` directly. It does not configure production host restrictions.
- `VIEW_INTERNAL_API_KEY`: The production frontend's shared view-recording key. Compose sets it from `PasteSettings__View_Internal_API_Key`; do not duplicate it in the root `.env`. When running the frontend directly, set it yourself or use the existing `View_HMAC_Internal_API_Key` fallback.
When `NODE_ENV=development`, the frontend uses a fixed development-only internal key matching the backend's checked-in development configuration and ignores both environment key names. See the [client README](SharpbinV3.Client/README.md) for development and standalone production setup.
The frontend will be accessible at http://localhost:5173.
+15 -5
View File
@@ -1,5 +1,5 @@
# syntax=docker/dockerfile:1
FROM node:20-alpine as build
FROM node:24-alpine as build
ARG GIT_COMMIT_HASH
ENV GIT_COMMIT_HASH=${GIT_COMMIT_HASH}
WORKDIR /app
@@ -8,9 +8,19 @@ RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine as runner
FROM node:24-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"]
+25 -5
View File
@@ -6,7 +6,7 @@ This is the SvelteKit frontend for SharpbinV3.
### Prerequisites
- Node.js (v20 or newer recommended)
- Node.js 24
- npm
### Installation
@@ -19,11 +19,12 @@ npm install
### Environment Configuration
The frontend requires an environment variable to point to the backend API. Create a `.env` file in this directory or set the variable in your environment:
The frontend defaults to the backend at `http://localhost:5050`. SvelteKit loads `.env` files during development, but `vite.config.ts` reads shell environment variables directly for its proxy and allowed hosts:
- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`).
- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`)
- `VIEW_INTERNAL_API_KEY`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
- `VITE_API_URL`: The backend URL reachable from the frontend server. Export this in the shell when changing the development backend URL so the Vite proxy and server-side requests use the same value.
- `VITE_ALLOWED_HOSTS`: A comma-separated list of hosts for Vite dev/preview. Export this in the shell before starting Vite. It does not configure the production Node server.
In development, the frontend uses a fixed internal view-recording key matching `appsettings.Development.json`. It ignores `VIEW_INTERNAL_API_KEY` and `View_HMAC_Internal_API_Key` while `NODE_ENV=development`.
### Running in Development
@@ -35,6 +36,25 @@ npm run dev
The frontend will be available at http://localhost:5173.
### Running in Production
Docker Compose reads the root `.env` file and runs the built Node server on port 5173. Configure these values there:
- `VITE_API_URL`: Backend URL. Defaults to `http://backend:8080` in Compose.
- `ORIGIN`: Public frontend URL, such as `https://example.com` or `http://localhost:5173` for local Docker testing.
- `PasteSettings__View_Internal_API_Key`: Shared view-recording key. Compose passes it to the frontend as `VIEW_INTERNAL_API_KEY`, so you only set it once.
For a standalone Node deployment, set `VITE_API_URL`, `ORIGIN`, and `VIEW_INTERNAL_API_KEY` in the client's own `.env` file. The key must match the backend's `PasteSettings__View_Internal_API_Key`. The frontend still supports `View_HMAC_Internal_API_Key` as a fallback; it does not read the backend setting name directly.
The standalone server does not load `.env` automatically. Build the frontend, then load your environment file explicitly:
```bash
npm run build
node --env-file=.env build
```
Set `PORT=5173` in that file to use the same port as Docker; the Node adapter otherwise defaults to port 3000. See the [Node adapter documentation](https://svelte.dev/docs/kit/adapter-node#Environment-variables) for runtime configuration.
## Script Reference
- `npm run dev`: Start the Vite development server.
+1 -3
View File
@@ -6,7 +6,6 @@ import svelte from 'eslint-plugin-svelte';
import { defineConfig } from 'eslint/config';
import globals from 'globals';
import ts from 'typescript-eslint';
import svelteConfig from './svelte.config.js';
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
@@ -33,8 +32,7 @@ export default defineConfig(
parserOptions: {
projectService: true,
extraFileExtensions: ['.svelte'],
parser: ts.parser,
svelteConfig
parser: ts.parser
}
}
}
+882 -1472
View File
File diff suppressed because it is too large Load Diff
+16 -11
View File
@@ -1,7 +1,7 @@
{
"name": "sharpbinv3.client",
"private": true,
"version": "3.0.5",
"version": "3.1.0",
"type": "module",
"scripts": {
"dev": "vite dev",
@@ -17,15 +17,16 @@
"devDependencies": {
"@eslint/compat": "^1.4.0",
"@eslint/js": "^9.39.1",
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/kit": "^2.60.1",
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17",
"@sveltejs/adapter-auto": "^8.0.0",
"@sveltejs/kit": "^3.0.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",
@@ -39,18 +40,22 @@
"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.3.2"
"typescript": "^6.0.3",
"typescript-eslint": "^8.71.2",
"vite": "^8.0.16"
},
"imports": {
"#lib": "./src/lib/index.ts",
"#lib/*": "./src/lib/*"
},
"dependencies": {
"@fontsource/inter": "^5.2.8",
"@fontsource/jetbrains-mono": "^5.2.8",
"@lucide/svelte": "^0.562.0",
"@resvg/resvg-js": "^2.6.2",
"@sveltejs/adapter-node": "^5.4.0",
"@sveltejs/adapter-node": "^6.0.0",
"better-sqlite3": "^12.8.0",
"dompurify": "^3.4.0",
"dompurify": "^3.4.16",
"hash-wasm": "^4.12.0",
"highlight.js": "^11.8.0",
"jsdom": "^27.4.0",
@@ -59,6 +64,6 @@
"qrcode": "^1.5.4",
"satori": "^0.26.0",
"satori-html": "^0.3.2",
"sharp": "^0.34.5"
"sharp": "^0.35.5"
}
}
@@ -1,10 +1,10 @@
<script lang="ts">
import QRCode from 'qrcode';
import { getRefreshToken, getToken, setTokens } from '$lib/utils/auth';
import { parseTotpEnabled } from '$lib/utils/totp';
import { getRefreshToken, getToken, setTokens } from '#lib/utils/auth';
import { parseTotpEnabled } from '#lib/utils/totp';
import { tick } from 'svelte';
import { extractError } from '$lib/utils/misc';
import type { ModalItem, ModalMode } from '$lib/types/modal';
import { extractError } from '#lib/utils/misc';
import type { ModalItem, ModalMode } from '#lib/types/modal';
interface Props {
show?: boolean;
@@ -1,6 +1,6 @@
<script lang="ts">
import Modal from '$lib/components/Modal.svelte';
import { cancelModal, confirmModal, modal } from '$lib/stores/modal';
import Modal from '#lib/components/Modal.svelte';
import { cancelModal, confirmModal, modal } from '#lib/stores/modal';
let state = $derived($modal);
</script>
@@ -1,9 +1,9 @@
<script lang="ts">
import { user } from '$lib/stores/user';
import { user } from '#lib/stores/user';
import { resolve } from '$app/paths';
import { page } from '$app/state';
import { clearTokens, hasRole } from '$lib/utils/auth';
import logo from '$lib/assets/favicon.svg';
import { clearTokens, hasRole } from '#lib/utils/auth';
import logo from '#lib/assets/favicon.svg';
import type { PageData } from '../../routes/$types';
import { slide } from 'svelte/transition';
import { Menu, X } from '@lucide/svelte';
@@ -1,5 +1,5 @@
<script lang="ts">
import { tooltip, dateToRelativeString, formatNumber, formatBytes } from '$lib/utils/misc';
import { tooltip, dateToRelativeString, formatNumber, formatBytes } from '#lib/utils/misc';
import { resolve } from '$app/paths';
import {
Eye,
@@ -12,10 +12,11 @@
Lock,
EyeOff,
Globe,
HatGlasses
HatGlasses,
ThumbsUp
} from '@lucide/svelte';
import { syntaxes } from '$lib/consts';
import type { Paste } from '$lib/types/paste';
import { syntaxes } from '#lib/consts';
import type { Paste } from '#lib/types/paste';
interface Props {
paste: Paste;
@@ -27,11 +28,13 @@
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}
<a
href={resolve(`/${paste.id}`)}
href={resolve(`/[id]`, { id: paste.id })}
class="flex flex-col gap-1 rounded border border-neutral-700 bg-neutral-800 px-4 py-3 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
>
<div class="flex w-full flex-row justify-between">
@@ -83,10 +86,18 @@
{/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>
@@ -108,7 +119,7 @@
</a>
{:else}
<a
href={resolve(`/${paste.id}`)}
href={resolve(`/[id]`, { id: paste.id })}
class="flex flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
>
<span
@@ -143,7 +154,7 @@
>
<History class="h-4 w-4" />
<span>
{#if paste.editedAt > Date.now() - 86_400_000}
{#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()}
@@ -175,13 +186,20 @@
</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"
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)}`
: ''}
@@ -189,7 +207,7 @@
<FileBox class="h-4 w-4" />
<span>{formatBytes(paste.originalSize)}</span>
</div>
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
<div class="flex items-center gap-2">
<Code class="h-4 w-4" />
<span>{syntax.name}</span>
</div>
@@ -1,14 +1,14 @@
<script lang="ts">
import type { CommentReaction, CommentTreeNode } from '$lib/types/comment';
import { dateToRelativeString, tooltip } from '$lib/utils/misc';
import { parseCommentMarkdown } from '$lib/utils/markdown';
import { escapeHtml } from '$lib/utils/html';
import { user } from '$lib/stores/user';
import PasteCommentItem from '$lib/components/PasteCommentItem.svelte';
import { ThumbsUp, ThumbsDown, Trash2, Shredder } from '@lucide/svelte';
import 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';
import { hasRole, roles } from '#lib/utils/auth';
interface Props {
node: CommentTreeNode;
@@ -93,15 +93,15 @@
}
</script>
<div class="p-3">
<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-lg">
<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}`)}
href={resolve(`/user/[username]`, { username: node.author?.username})}
class="flex items-center gap-2 underline"
>
<span
@@ -113,7 +113,7 @@
{/if}
{#if node.updatedAt}
<span
class="text-sm text-neutral-500"
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
>
@@ -127,7 +127,7 @@
</div>
<div class="text-sm leading-relaxed text-neutral-200">
<div class="wrap-break-word" class:italic={isDeleted} class:text-neutral-800={isDeleted}>
<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}
@@ -151,54 +151,53 @@
{/if}
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<div class="mt-3 flex flex-wrap items-center gap-1.5">
<button
type="button"
class="h-7 min-w-12 rounded border px-2 py-1 text-xs {node.userReaction !== 1
? 'hover:bg-neutral-800 active:bg-neutral-700'
: 'hover:bg-green-800 active:bg-green-700'} disabled:cursor-not-allowed disabled:hover:bg-transparent"
class="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}
class:bg-green-900={node.userReaction === 1}
class:text-green-200={node.userReaction === 1}
class:border-neutral-700={node.userReaction !== 1}
class:text-neutral-300={node.userReaction !== 1}
onclick={() => onReact(node.id, 1, node.userReaction)}
disabled={reactingIds[node.id] || !$user}
aria-label="Like comment"
title="Like"
>
<ThumbsUp class="mr-1 inline h-3.5 w-3.5" />
<ThumbsUp class="h-3.5 w-3.5" />
{node.likes}
</button>
<button
type="button"
class="h-7 min-w-12 rounded border px-2 py-1 text-xs {node.userReaction !== 2
? 'hover:bg-neutral-800 active:bg-neutral-700'
: 'hover:bg-red-800 active:bg-red-700'} disabled:cursor-not-allowed disabled:hover:bg-transparent"
class="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}
class:bg-red-900={node.userReaction === 2}
class:text-red-200={node.userReaction === 2}
class:border-neutral-700={node.userReaction !== 2}
class:text-neutral-300={node.userReaction !== 2}
onclick={() => onReact(node.id, 2, node.userReaction)}
disabled={reactingIds[node.id] || !$user}
aria-label="Dislike comment"
title="Dislike"
>
<ThumbsDown class="mr-1 inline h-3.5 w-3.5" />
<ThumbsDown class="h-3.5 w-3.5" />
{node.dislikes}
</button>
{#if $user}
{#if !replyOpen}
<button
type="button"
class="h-7 min-w-12 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
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="h-7 min-w-12 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
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;
@@ -209,26 +208,31 @@
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">
<div class="ml-auto flex items-center gap-1">
<button
type="button"
class="h-7 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
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="inline h-3.5 w-3.5" />
<Trash2 class="h-3.5 w-3.5" />
</button>
{#if hasRole($user.roles, roles.Moderator) || hasRole($user.roles, roles.Admin)}
<button
type="button"
class="h-7 rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 active:bg-neutral-700"
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="inline h-3.5 w-3.5" />
<Shredder class="h-3.5 w-3.5" />
</button>
{/if}
</div>
@@ -245,6 +249,9 @@
onSubmit={submitReply}
disabled={replySubmitting}
submitting={replySubmitting}
submitLabel="Reply"
submittingLabel="Replying..."
compact
/>
{#if replyError}
<p class="mt-2 text-xs text-red-400">{replyError}</p>
@@ -252,7 +259,7 @@
{/if}
{#if node.children.length > 0}
<div class="mt-3 border-l border-neutral-800 pl-3">
<div class="mt-3 border-l border-neutral-700 pl-3">
{#if depth >= 3 && !showDeepReplies}
<button
type="button"
@@ -1,17 +1,18 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getToken } from '$lib/utils/auth';
import { user } from '$lib/stores/user';
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';
} 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 { openModal } from '#lib/stores/modal';
import { RefreshCw } from '@lucide/svelte';
interface Props {
pasteId: string;
@@ -236,29 +237,39 @@
}
</script>
<section id="comments-section" class="mt-6 rounded border border-neutral-800 p-4">
<section
id="comments-section"
class="mt-4 w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
>
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<h2 class="text-xl font-semibold text-neutral-100">Comments ({comments.length})</h2>
<div class="flex items-center gap-2">
<h2 class="text-lg font-semibold text-neutral-100">{comments.length} Comments</h2>
</div>
<button
type="button"
class="rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:text-neutral-100"
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"
>
{loading ? 'Refreshing...' : 'Refresh'}
<RefreshCw class="h-3.5 w-3.5 {loading ? 'animate-spin' : ''}" />
{loading ? 'Refreshing' : 'Refresh'}
</button>
</div>
{#if $user}
<RichTextEditor
bind:value={newComment}
placeholder="Write a comment..."
onSubmit={submitTopLevelComment}
disabled={posting}
submitting={posting}
/>
<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-800 p-3 text-sm text-neutral-400">
<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}
@@ -270,15 +281,15 @@
{/if}
{#if loading && comments.length === 0}
<div class="rounded border border-neutral-800 p-3 text-sm text-neutral-400">
<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-800 p-3 text-sm text-neutral-400">
<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-3">
<div class="space-y-2">
{#each threadedComments as node (node.id)}
<PasteCommentItem
{node}
@@ -1,6 +1,6 @@
<script lang="ts">
import { Bold, Italic, CodeXml, Quote } from '@lucide/svelte';
import { parseCommentMarkdown } from '$lib/utils/markdown';
import { Bold, Italic, CodeXml, Quote, Send, Eye, Pencil } from '@lucide/svelte';
import { parseCommentMarkdown } from '#lib/utils/markdown';
interface Props {
class?: string;
@@ -8,6 +8,7 @@
placeholder?: string;
disabled?: boolean;
submitting?: boolean;
compact?: boolean;
submitLabel?: string;
submittingLabel?: string;
onSubmit?: (value: string) => void | Promise<void>;
@@ -19,6 +20,7 @@
placeholder = 'Write a comment...',
disabled = false,
submitting = false,
compact = false,
submitLabel = 'Post comment',
submittingLabel = 'Posting...',
onSubmit
@@ -30,6 +32,7 @@
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();
@@ -133,11 +136,13 @@
}
</script>
<div class="mb-4 flex flex-col rounded {className}">
<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="min-h-24 w-full rounded-t border border-b-0 border-neutral-700 bg-neutral-900 p-2 font-mono text-sm text-neutral-100 outline-none"
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}
@@ -145,11 +150,9 @@
onkeydown={handleKeydown}
></textarea>
{:else}
<div
class="min-h-24 w-full rounded-t border border-b-0 border-neutral-700 bg-neutral-900 p-2 text-sm text-neutral-100"
>
<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-500">{placeholder}</div>
<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 -->
@@ -159,57 +162,71 @@
</div>
{/if}
<div
class="flex w-full flex-col gap-2 rounded-b border border-neutral-700 bg-neutral-800 p-2 md:flex-row md:gap-0"
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="rounded px-2 py-1 text-sm text-neutral-300 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-600"
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="rounded px-2 py-1 text-sm text-neutral-300 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-600"
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="rounded px-2 py-1 text-sm text-neutral-300 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-600"
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="rounded px-2 py-1 text-sm text-neutral-300 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-600"
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-5 w-5" />
<CodeXml class="h-4 w-4" />
</button>
</div>
<div class="flex flex-col items-center gap-2 md:ml-auto md:flex-row">
<div class="flex flex-col items-stretch gap-2 md:ml-auto md:flex-row md:items-center">
<button
type="button"
class="ml-auto w-full rounded border border-neutral-600 px-3 py-1 text-sm text-neutral-200 hover:border-neutral-500 hover:text-neutral-100 md:w-auto"
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="w-full rounded border border-neutral-600 px-3 py-1 text-sm text-neutral-100 hover:bg-neutral-600 disabled:cursor-not-allowed disabled:border-neutral-700 disabled:text-neutral-500 md:ml-2 md:w-auto"
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>
+1 -1
View File
@@ -1 +1 @@
// place files you want to import through the `$lib` alias in this folder.
// place files you want to import through the `#lib` alias in this folder.
+1 -1
View File
@@ -1,4 +1,4 @@
import { env } from '$env/dynamic/private';
import { env } from 'node:process';
export const apiUrl = env.VITE_API_URL ?? 'http://localhost:5050';
export const viewInternalApiKey =
+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 -1
View File
@@ -1,5 +1,5 @@
import { writable } from 'svelte/store';
import type { ModalOpenOptions, ModalState } from '$lib/types/modal';
import type { ModalOpenOptions, ModalState } from '#lib/types/modal';
const initialState: ModalState = {
show: false,
+1 -1
View File
@@ -1,6 +1,6 @@
import { writable } from 'svelte/store';
import { browser } from '$app/environment';
import type { AuthUser } from '$lib/types/user';
import type { AuthUser } from '#lib/types/user';
let initial: AuthUser | null = null;
+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;
@@ -0,0 +1,9 @@
import { argon2id } from 'hash-wasm';
self.onmessage = async (event: MessageEvent<Parameters<typeof argon2id>[0]>) => {
try {
self.postMessage(await argon2id(event.data));
} catch {
self.postMessage(null);
}
};
+2 -2
View File
@@ -1,7 +1,7 @@
import { browser } from '$app/environment';
import type { Cookies } from '@sveltejs/kit';
import { user } from '$lib/stores/user';
import type { JWTUser } from '$lib/types/user';
import { user } from '#lib/stores/user';
import type { JWTUser } from '#lib/types/user';
export const roles = {
User: 1,
+128 -19
View File
@@ -1,5 +1,3 @@
import { argon2id } from 'hash-wasm';
const BASE64_CHUNK_SIZE = 0x8000;
const SALT_LENGTH = 16;
const IV_LENGTH = 12;
@@ -9,8 +7,58 @@ const ARGON2_PARALLELISM = 1;
const ARGON2_HASH_LENGTH = 32;
const AES_KEY_LENGTH = 256;
const ENCRYPTION_AAD = 'enc-v4';
const ENCRYPTED_DATA_OVERHEAD = 60;
const ENCRYPTED_METADATA_OVERHEAD = 150;
const ENCRYPTED_DATA_OVERHEAD = SALT_LENGTH + IV_LENGTH + 16;
const MAX_ENVELOPE_LENGTH = 16 * 1024 * 1024;
const ENCRYPTION_HEADER = {
version: 5,
kdf: 'Argon2id',
memorySize: ARGON2_MEMORY_SIZE,
iterations: ARGON2_ITERATIONS,
parallelism: ARGON2_PARALLELISM,
algorithm: 'AES-GCM',
saltLength: SALT_LENGTH,
ivLength: IV_LENGTH
};
let derivingKey = false;
async function argon2id(
options: Parameters<typeof import('hash-wasm').argon2id>[0]
): Promise<Uint8Array<ArrayBuffer>> {
if (derivingKey) throw new Error('Another encryption operation is already running.');
derivingKey = true;
try {
return await new Promise((resolve, reject) => {
const worker = new Worker(new URL('./argon2.worker.ts', import.meta.url), { type: 'module' });
const finish = () => {
clearTimeout(timeout);
worker.terminate();
};
const timeout = setTimeout(() => {
finish();
reject(new Error('Key derivation timed out.'));
}, 60_000);
worker.onmessage = (event: MessageEvent<Uint8Array | null>) => {
finish();
if (event.data instanceof Uint8Array && event.data.length === ARGON2_HASH_LENGTH) {
resolve(new Uint8Array(event.data));
} else reject(new Error('Key derivation failed. The device may lack memory.'));
};
worker.onerror = (event) => {
event.preventDefault();
finish();
reject(new Error('Unable to run the encryption worker.'));
};
try {
worker.postMessage(options);
} catch (error) {
finish();
reject(error);
}
});
} finally {
derivingKey = false;
}
}
function toBase64(bytes: Uint8Array): string {
let binary = '';
@@ -29,7 +77,21 @@ function fromBase64(data: string): Uint8Array {
return bytes;
}
export function encodePasswordFragment(password: string): string {
return `u1.${toBase64(new TextEncoder().encode(password))}`;
}
export function decodePasswordFragment(fragment: string): string {
return fragment.startsWith('u1.')
? new TextDecoder('utf-8', { fatal: true }).decode(fromBase64(fragment.slice(3)))
: atob(fragment);
}
export async function encryptAES(content: string, password: string): Promise<string> {
if (!password) throw new Error('Password required for encryption.');
if (estimateEncryptedSize(content) > MAX_ENVELOPE_LENGTH) {
throw new Error('Encrypted paste exceeds the supported size limit.');
}
const enc = new TextEncoder();
const salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
@@ -56,7 +118,7 @@ export async function encryptAES(content: string, password: string): Promise<str
{
name: 'AES-GCM',
iv,
additionalData: enc.encode(ENCRYPTION_AAD)
additionalData: enc.encode(JSON.stringify(ENCRYPTION_HEADER))
},
key,
enc.encode(content)
@@ -68,14 +130,7 @@ export async function encryptAES(content: string, password: string): Promise<str
combined.set(new Uint8Array(encryptedContent), salt.byteLength + iv.byteLength);
return JSON.stringify({
version: 4,
kdf: 'Argon2id',
memorySize: ARGON2_MEMORY_SIZE,
iterations: ARGON2_ITERATIONS,
parallelism: ARGON2_PARALLELISM,
algorithm: 'AES-GCM',
saltLength: salt.byteLength,
ivLength: iv.byteLength,
...ENCRYPTION_HEADER,
data: toBase64(combined)
});
}
@@ -84,17 +139,58 @@ export function estimateEncryptedSize(content: string): number {
const rawSize = new TextEncoder().encode(content).length;
const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
const b64Size = Math.ceil(combinedSize / 3) * 4;
return b64Size + ENCRYPTED_METADATA_OVERHEAD;
return b64Size + JSON.stringify({ ...ENCRYPTION_HEADER, data: '' }).length;
}
export async function decryptAES(result: string, password: string): Promise<string | null> {
try {
const enc = new TextEncoder();
if (result.length > MAX_ENVELOPE_LENGTH) {
throw new Error('Encrypted paste exceeds the supported size limit.');
}
const parsed = JSON.parse(result);
if (!parsed || typeof parsed !== 'object' || parsed.algorithm !== 'AES-GCM') {
throw new Error('Unsupported or malformed encrypted paste.');
}
const legacyPBKDF2 =
parsed.version === 1 &&
parsed.kdf === 'PBKDF2' &&
parsed.iterations === 100000 &&
parsed.hash === 'SHA-256' &&
(parsed.saltLength === undefined || parsed.saltLength === SALT_LENGTH) &&
(parsed.ivLength === undefined || parsed.ivLength === IV_LENGTH);
const legacyArgon2 =
parsed.version === 4 && parsed.memorySize === 65536 && parsed.saltLength === 32;
const currentArgon2 =
(parsed.version === 4 || parsed.version === 5) &&
parsed.memorySize === ARGON2_MEMORY_SIZE &&
parsed.saltLength === SALT_LENGTH;
if (
!legacyPBKDF2 &&
!(
parsed.kdf === 'Argon2id' &&
parsed.iterations === ARGON2_ITERATIONS &&
parsed.parallelism === ARGON2_PARALLELISM &&
parsed.ivLength === IV_LENGTH &&
(legacyArgon2 || currentArgon2)
)
)
throw new Error('Unsupported encryption profile.');
if (
typeof parsed.data !== 'string' ||
!parsed.data.length ||
parsed.data.length % 4 !== 0 ||
!/^[A-Za-z0-9+/]*={0,2}$/.test(parsed.data)
) {
throw new Error('Malformed encrypted-paste encoding.');
}
const combined = fromBase64(parsed.data);
const saltLength = parsed.saltLength || SALT_LENGTH;
const ivLength = parsed.ivLength || IV_LENGTH;
const saltLength = parsed.saltLength ?? SALT_LENGTH;
const ivLength = parsed.ivLength ?? IV_LENGTH;
if (combined.length < saltLength + ivLength + 16) {
throw new Error('Encrypted paste is truncated.');
}
const salt = combined.slice(0, saltLength);
const iv = combined.slice(saltLength, saltLength + ivLength);
const data = combined.slice(saltLength + ivLength);
@@ -146,14 +242,27 @@ export async function decryptAES(result: string, password: string): Promise<stri
{
name: 'AES-GCM',
iv,
additionalData: enc.encode(ENCRYPTION_AAD)
additionalData: enc.encode(
parsed.version === 5
? JSON.stringify(ENCRYPTION_HEADER)
: currentArgon2
? ENCRYPTION_AAD
: ''
)
},
key,
data
);
return new TextDecoder().decode(decryptedContent);
} catch {
return null;
} catch (error) {
if (error instanceof DOMException && error.name === 'OperationError') return null;
if (
error instanceof SyntaxError ||
(error instanceof DOMException && error.name === 'InvalidCharacterError')
) {
throw new Error('Malformed encrypted paste.');
}
throw error;
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
import { marked } from 'marked';
import createDOMPurify from 'dompurify';
import type { WindowLike } from 'dompurify';
import { trustedDomains } from '$lib/consts';
import { trustedDomains } from '#lib/consts';
import { escapeHtml } from './html';
export const externalMediaWarningStorageKey = 'sharpbin:ignore-external-media-warning';
+1 -1
View File
@@ -1,4 +1,4 @@
import { syntaxes } from '$lib/consts';
import { syntaxes } from '#lib/consts';
/**
* @param bytes Bytes to format.
+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 };
};
+8 -8
View File
@@ -1,13 +1,13 @@
<script lang="ts">
import { onMount } from 'svelte';
import './layout.css';
import favicon from '$lib/assets/favicon.svg';
import Navbar from '$lib/components/Navbar.svelte';
import Footer from '$lib/components/Footer.svelte';
import ModalHost from '$lib/components/ModalHost.svelte';
import { user } from '$lib/stores/user';
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
import { parseTotpEnabled } from '$lib/utils/totp';
import favicon from '#lib/assets/favicon.svg';
import Navbar from '#lib/components/Navbar.svelte';
import Footer from '#lib/components/Footer.svelte';
import ModalHost from '#lib/components/ModalHost.svelte';
import { user } from '#lib/stores/user';
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '#lib/utils/auth';
import { parseTotpEnabled } from '#lib/utils/totp';
import { page } from '$app/state';
import type { LayoutData } from './$types';
@@ -98,7 +98,7 @@
<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
+14 -9
View File
@@ -1,20 +1,20 @@
<script lang="ts">
import type { PageData } from './$types';
import { syntaxes, expiresOptions } from '$lib/consts';
import { user } from '$lib/stores/user';
import { getToken } from '$lib/utils/auth';
import { syntaxes, expiresOptions } from '#lib/consts';
import { user } from '#lib/stores/user';
import { getToken } from '#lib/utils/auth';
import { onMount } from 'svelte';
import { fly, fade } from 'svelte/transition';
import { encryptAES, estimateEncryptedSize } from '$lib/utils/encryption';
import { encryptAES, estimateEncryptedSize, encodePasswordFragment } from '#lib/utils/encryption';
import {
formatBytes,
formatNumber,
isBinaryData,
tooltip,
syntaxFromExtension
} from '$lib/utils/misc';
import { parseMarkdown } from '$lib/utils/markdown';
import Dropdown from '$lib/components/Dropdown.svelte';
} from '#lib/utils/misc';
import { parseMarkdown } from '#lib/utils/markdown';
import Dropdown from '#lib/components/Dropdown.svelte';
import { SvelteURLSearchParams } from 'svelte/reactivity';
import { FileUp, X, Eye, EyeClosed, Dices } from '@lucide/svelte';
@@ -162,7 +162,12 @@
let body = content;
if (selectedVisibility === 2) {
body = await encryptAES(content, password);
try {
body = await encryptAES(content, password);
} catch (cause) {
error = cause instanceof Error ? cause.message : 'Encryption failed.';
return;
}
}
if (
@@ -196,7 +201,7 @@
if (response.ok) {
const result = await response.json();
if (selectedVisibility === 2) {
const passwordBase64 = btoa(password);
const passwordBase64 = encodePasswordFragment(password);
window.location.href = `/${result.id}#${passwordBase64}`;
return;
}
@@ -1,7 +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)}`);
const username = params?.username;
if (!username) throw error(404, 'User not found');
throw redirect(302, `/user/${encodeURIComponent(username)}`);
}
@@ -1,21 +1,21 @@
import { syntaxes } from '$lib/consts';
import { apiUrl } from '$lib/server/api';
import { syntaxes } from '#lib/consts';
import { apiUrl } from '#lib/server/api';
import {
getCachedOgImage,
getCacheControlHeader,
getCacheTtlSeconds,
scheduleOgImageCachePurge,
storeCachedOgImage
} from '$lib/server/og/cache';
import OgPasteEmbed from '$lib/server/og/PasteEmbed.svelte';
import type { PasteEmbedProps } from '$lib/server/og/pasteEmbed';
import type { Paste } from '$lib/types/paste';
} from '#lib/server/og/cache';
import OgPasteEmbed from '#lib/server/og/PasteEmbed.svelte';
import type { PasteEmbedProps } from '#lib/server/og/pasteEmbed';
import type { Paste } from '#lib/types/paste';
import {
dateToRelativeString,
extractDateFromUUIDv7,
formatBytes,
formatNumber
} from '$lib/utils/misc';
} from '#lib/utils/misc';
import { Resvg } from '@resvg/resvg-js';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
@@ -1,8 +1,8 @@
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 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';
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent, request }) => {
+73 -51
View File
@@ -36,24 +36,24 @@
dateToRelativeString,
tooltip,
isBinaryData
} from '$lib/utils/misc';
} from '#lib/utils/misc';
import {
getIgnoreExternalMediaWarning,
parseMarkdown,
setIgnoreExternalMediaWarning
} from '$lib/utils/markdown';
import { syntaxes, expiresOptions } from '$lib/consts';
} from '#lib/utils/markdown';
import { syntaxes, expiresOptions } from '#lib/consts';
import { resolve } from '$app/paths';
import { decryptAES, encryptAES } from '$lib/utils/encryption';
import { escapeHtml } from '$lib/utils/html';
import { decryptAES, encryptAES, decodePasswordFragment } 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, PasteReaction } from '$lib/types/paste';
import HighlightWorker from '$lib/workers/highlight.worker?worker';
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, PasteReaction } from '#lib/types/paste';
import HighlightWorker from '#lib/workers/highlight.worker?worker';
interface Props {
data: PageData;
}
@@ -100,6 +100,9 @@
let highlightRequestId = 0;
let ignoreExternalMediaWarning = false;
let iconsOnly = $state(false);
const canonicalUrl = $derived(
data.paste ? new URL(`/${data.paste.id}`, data.url).href : undefined
);
let scrollY = $state(0);
@@ -356,8 +359,8 @@
});
editMetadata = data.paste ? { ...data.paste } : null;
}
} catch {
editError = 'An error occurred while updating.';
} catch (cause) {
editError = cause instanceof Error ? cause.message : 'An error occurred while updating.';
} finally {
editLoading = false;
editing = false;
@@ -514,8 +517,20 @@
contentRendered = false;
decryptStatus = 'Preparing decryption...';
const urlHash = window.location.hash.slice(1);
let passwordFromUrl: string | null = null;
if (urlHash) {
const passwordFromUrl = atob(urlHash);
history.replaceState(
history.state,
'',
window.location.pathname + window.location.search
);
try {
passwordFromUrl = decodePasswordFragment(urlHash);
} catch {
/* empty */
}
}
if (passwordFromUrl !== null) {
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, passwordFromUrl);
if (decryptedContent === null) {
@@ -525,11 +540,10 @@
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, password);
if (decryptedContent === null) {
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
decryptError = 'Wrong password or damaged encrypted paste.';
decryptStatus = decryptError;
} else {
await renderPaste();
history.replaceState(null, '', window.location.pathname + window.location.search);
}
} else {
decryptStatus = 'Decryption canceled.';
@@ -545,8 +559,8 @@
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, password);
if (decryptedContent === null) {
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
decryptError = 'Wrong password or damaged encrypted paste.';
decryptStatus = decryptError;
} else {
await renderPaste();
}
@@ -557,7 +571,12 @@
decryptStatus = 'Rendering content...';
await renderPaste();
}
} catch {
} catch (cause) {
if (data?.paste?.visibility === 2) {
decryptStatus = cause instanceof Error ? cause.message : 'Unable to decrypt this paste.';
contentRendered = false;
return;
}
decryptStatus = 'Rendering content...';
await renderPaste();
}
@@ -590,14 +609,14 @@
name="robots"
content={data.paste.visibility === 0 ? 'index, follow' : 'noindex, nofollow'}
/>
<link rel="canonical" href={data.url} />
<link rel="canonical" href={canonicalUrl} />
{#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:url" content={canonicalUrl} />
<meta property="og:site_name" content="Sharpbin" />
{#if pasteImageUrl}
<meta property="og:image" content={pasteImageUrl} />
@@ -652,7 +671,7 @@
{#if data.paste.author}
<User class="inline-block h-4 w-4 text-neutral-400" />
<a
href={resolve(`/user/${data.paste.author.username}`)}
href={resolve(`/user/[username]`, { username: data.paste.author.username })}
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
>{data.paste.author.username}</a
>
@@ -818,30 +837,30 @@
>
<button
type="button"
class="ml-4 rounded border px-2 py-0.5 text-sm transition-colors disabled:opacity-60 disabled:cursor-not-allowed! {data
.paste.userReaction === 1
? 'border-green-700 bg-green-900 text-green-200'
: 'border-neutral-700 bg-neutral-700 text-neutral-300 hover:bg-neutral-600'}"
onclick={() => reactToPaste(1)}
disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
aria-disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
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>
<ThumbsUp class="mr-1 inline-block h-4 w-4 text-green-400" />
<span>{formatNumber(data.paste.likes)}</span>
</button>
<button
type="button"
class="rounded border px-2 py-0.5 text-sm transition-colors disabled:opacity-60 disabled:cursor-not-allowed! {data
.paste.userReaction === 2
? 'border-red-700 bg-red-900 text-red-200'
: 'border-neutral-700 bg-neutral-700 text-neutral-300 hover:bg-neutral-600'}"
onclick={() => reactToPaste(2)}
disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
aria-disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
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>
<ThumbsDown class="mr-1 inline-block h-4 w-4 text-red-400" />
<span>{formatNumber(data.paste.dislikes)}</span>
</button>
</div>
{:else}
@@ -899,10 +918,13 @@
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
const filename = data.paste?.title
? `${data.paste.title.slice(0, 100)}${extension ? `.${extension}` : ''}`
: `paste_${data.paste?.id}${extension ? `.${extension}` : ''}`;
a.href = url;
a.download = data.paste?.title
? `${data.paste.title.slice(0, 100)}.${extension}`
: `paste_${data.paste?.id}.${extension}`;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
@@ -932,7 +954,7 @@
</button>
<a
href={resolve(`/raw/${data.paste.id}`)}
href={resolve(`/raw/[id]`, { id: 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="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
@@ -1094,7 +1116,7 @@
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}
onclick={handleMarkdownClick}
@@ -1104,14 +1126,14 @@
{@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>
{/if}
</div>
<PasteComments pasteId={data.paste.id} initialComments={data.comments ?? []} />
<style>
.hljs {
background-color: var(--color-neutral-800) !important;
@@ -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' });
};
@@ -1,7 +1,7 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
import { extractError } from '$lib/utils/misc';
import { setTokens, startTokenRefreshInterval } from '#lib/utils/auth';
import { extractError } from '#lib/utils/misc';
import { onMount } from 'svelte';
import type { PageData } from './$types';
@@ -159,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);
};
@@ -1,5 +1,5 @@
import type { RequestHandler } from '@sveltejs/kit';
import { apiUrl } from '$lib/server/api';
import { apiUrl } from '#lib/server/api';
export const GET: RequestHandler = async ({ params, request }) => {
const { id } = params;
@@ -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
});
};
@@ -1,20 +1,15 @@
import type { PageServerLoad } from './$types';
import type { Paste } from '$lib/types/paste';
import { extractError } from '$lib/utils/misc';
import type { Paste } from '#lib/types/paste';
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 };
};
@@ -1,7 +1,7 @@
<script lang="ts">
import type { PageData } from './$types';
import { onMount } from 'svelte';
import Paste from '$lib/components/Paste.svelte';
import Paste from '#lib/components/Paste.svelte';
interface Props {
data: PageData;
@@ -1,7 +1,7 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
import { extractError } from '$lib/utils/misc';
import { setTokens, startTokenRefreshInterval } from '#lib/utils/auth';
import { extractError } from '#lib/utils/misc';
import { Check, X, Eye, EyeClosed } from '@lucide/svelte';
import { slide, fade } from 'svelte/transition';
import { resolve } from '$app/paths';
@@ -1,8 +1,8 @@
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { apiUrl } from '$lib/server/api';
import { getServerToken, clearServerTokens, roles, getUserFromToken } from '$lib/utils/auth';
import type { Report } from '$lib/types/report';
import { apiUrl } from '#lib/server/api';
import { getServerToken, clearServerTokens, roles, getUserFromToken } from '#lib/utils/auth';
import type { Report } from '#lib/types/report';
export const load: PageServerLoad = async ({ fetch, cookies, params, url, request }) => {
const token = getServerToken(cookies);
@@ -1,9 +1,9 @@
<script lang="ts">
import type { PageData } from './$types';
import { resolve } from '$app/paths';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
import { tooltip } from '$lib/utils/misc';
import { getToken } from '$lib/utils/auth';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '#lib/types/report';
import { tooltip } from '#lib/utils/misc';
import { getToken } from '#lib/utils/auth';
interface Props {
data: PageData;
@@ -75,7 +75,7 @@
{#if report.reporterUsername}
<a
class="text-neutral-200 hover:text-white hover:underline"
href={resolve(`/user/${report.reporterUsername}`)}
href={resolve(`/user/[username]`, { username: report.reporterUsername})}
use:tooltip={report.reporterUUID}
>
{report.reporterDisplayName || report.reporterUsername}
@@ -89,7 +89,7 @@
Target Paste:
<a
class="text-neutral-200 hover:text-white hover:underline"
href={resolve(`/${report.pasteId}`)}
href={resolve(`/[id]`, { id: report.pasteId})}
>
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
</a>
@@ -101,7 +101,7 @@
{#if report.targetUsername}
<a
class="text-neutral-200 hover:text-white hover:underline"
href={resolve(`/user/${report.targetUsername}`)}
href={resolve(`/user/[username]`, { username: report.targetUsername})}
use:tooltip={report.userUUID}
>
{report.targetDisplayName || report.targetUsername}
@@ -1,15 +1,15 @@
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { apiUrl } from '$lib/server/api';
import { apiUrl } from '#lib/server/api';
import {
getServerToken,
getUserFromToken,
clearServerTokens,
hasRole,
roles
} from '$lib/utils/auth';
import type { ReportListResponse } from '$lib/types/report';
import { extractError } from '$lib/utils/misc';
} from '#lib/utils/auth';
import type { ReportListResponse } from '#lib/types/report';
import { extractError } from '#lib/utils/misc';
function normalizeTarget(value: string | null): 'all' | 'pastes' | 'users' {
if (value === 'pastes' || value === 'users') return value;
@@ -5,8 +5,8 @@
import type { PageData } from './$types';
import { resolve } from '$app/paths';
import { goto } from '$app/navigation';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
import { tooltip } from '$lib/utils/misc';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '#lib/types/report';
import { tooltip } from '#lib/utils/misc';
import { SvelteURLSearchParams } from 'svelte/reactivity';
interface Props {
@@ -200,11 +200,11 @@
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"
onclick={() => goto(resolve(`/report/${report.reportID}`))}
onclick={() => goto(resolve(`/report/[reportId]`, { reportId: String(report.reportID)}))}
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
goto(resolve(`/report/${report.reportID}`));
goto(resolve(`/report/[reportId]`, { reportId: String(report.reportID)}));
}
}}
>
@@ -221,7 +221,7 @@
<span>{reportTargetLabels[report.targetType] ?? 'Unknown'}</span>
{#if report.pasteId}
<a
href={resolve(`/${report.pasteId}`)}
href={resolve(`/[id]`, { id: report.pasteId})}
class="text-neutral-300 hover:text-white"
onclick={stopPropagation(bubble('click'))}
>
@@ -231,7 +231,7 @@
{#if report.userUUID}
{#if report.targetUsername}
<a
href={resolve(`/user/${report.targetUsername}`)}
href={resolve(`/user/[username]`, {username: report.targetUsername})}
class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID}
onclick={stopPropagation(bubble('click'))}
@@ -244,7 +244,7 @@
{/if}
{#if report.reporterUsername}
<a
href={resolve(`/user/${report.reporterUsername}`)}
href={resolve(`/user/[username]`, { username: report.reporterUsername})}
class="text-neutral-300 hover:text-white"
use:tooltip={report.reporterUUID}
onclick={stopPropagation(bubble('click'))}
@@ -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>
@@ -1,7 +1,7 @@
import type { PageServerLoad } from './$types';
import { apiUrl } from '$lib/server/api';
import { apiUrl } from '#lib/server/api';
import { error, isHttpError } from '@sveltejs/kit';
import { extractError } from '$lib/utils/misc';
import { extractError } from '#lib/utils/misc';
export const load: PageServerLoad = async ({ fetch }) => {
try {
@@ -1,6 +1,6 @@
<script lang="ts">
import type { PageData } from './$types';
import { formatBytes, formatNumber, tooltip } from '$lib/utils/misc';
import { formatBytes, formatNumber, tooltip } from '#lib/utils/misc';
import { FileText, Users, Database, TrendingUp } from '@lucide/svelte';
interface Props {
@@ -81,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>
@@ -1,11 +1,11 @@
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { apiUrl } from '$lib/server/api';
import { getServerToken } from '$lib/utils/auth';
import type { User } from '$lib/types/user';
import type { Paste } from '$lib/types/paste';
import type { Pagination } from '$lib/types/pagination';
import type { Report, ReportListResponse } from '$lib/types/report';
import { apiUrl } from '#lib/server/api';
import { getServerToken } from '#lib/utils/auth';
import type { User } from '#lib/types/user';
import type { Paste } from '#lib/types/paste';
import type { Pagination } from '#lib/types/pagination';
import type { Report, ReportListResponse } from '#lib/types/report';
function decodeJwtRoles(token?: string | null): number {
try {
@@ -6,7 +6,7 @@
import { goto, afterNavigate } from '$app/navigation';
import { page } from '$app/state';
import type { PageData } from './$types';
import type { Pagination } from '$lib/types/pagination';
import type { Pagination } from '#lib/types/pagination';
import {
User,
CalendarDays,
@@ -14,6 +14,7 @@
Ban,
AtSign,
Pencil,
KeyRound,
Trash2,
Clock,
Hash,
@@ -29,13 +30,13 @@
tooltip,
dateToRelativeString,
extractError
} from '$lib/utils/misc';
import { getToken, hasRole, roles } from '$lib/utils/auth';
import { openModal } from '$lib/stores/modal';
import { user } from '$lib/stores/user';
} from '#lib/utils/misc';
import { clearTokens, getToken, hasRole, roles } from '#lib/utils/auth';
import { openModal } from '#lib/stores/modal';
import { user } from '#lib/stores/user';
import { onMount } from 'svelte';
import Paste from '$lib/components/Paste.svelte';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
import Paste from '#lib/components/Paste.svelte';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '#lib/types/report';
import { fade } from 'svelte/transition';
interface Props {
@@ -64,6 +65,30 @@
let interval: ReturnType<typeof setInterval> | null = null;
let isEditingDisplayName = $state(false);
let editDisplayNameValue = $state('');
let isEditingEmail = $state(false);
let editEmailValue = $state('');
let emailActionLoading = $state(false);
let emailMessage = $state('');
let emailError = $state('');
let passwordCurrentValue = $state('');
let passwordNewValue = $state('');
let passwordConfirmValue = $state('');
let passwordFocused = $state(false);
let passwordChecks = $state({
minLength: false,
maxLength: false,
upper: false,
lower: false,
number: false
});
let passwordValid = $state(false);
let passwordActionLoading = $state(false);
let passwordMessage = $state('');
let passwordError = $state('');
let passwordResetLinkValue = $state('');
let passwordResetLinkLoading = $state(false);
let passwordResetLinkMessage = $state('');
let passwordResetLinkError = $state('');
let apiKeys: { uuid: string; name: string; createdAt: string; lastUsedAt: string | null }[] =
$state([]);
@@ -76,6 +101,12 @@
let reportsSubmitted = $derived(data.reportsSubmitted);
let reportsTarget = $derived(data.reportsTarget);
let adminsRequire2FA = $derived(
Boolean(
(data as unknown as { authOptions?: { admins_require_2fa?: boolean } }).authOptions
?.admins_require_2fa
)
);
let activeTab: 'pastes' | 'reportsSubmitted' | 'reportsTarget' | 'settings' = $state('pastes');
let activeSubTab:
@@ -184,7 +215,7 @@
message?: string;
};
type SecurityAction = 'UpdateRoles' | 'DeleteUser';
type SecurityAction = 'UpdateRoles' | 'DeleteUser' | 'GeneratePasswordResetLink';
async function fetchActionSecurityRequirements(action: SecurityAction) {
const token = getToken();
@@ -248,6 +279,24 @@
).trim();
}
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(passwordNewValue);
});
async function fetchPage(pageNum: number) {
if (pageNum < 1 || pageNum > (pagination.totalPages || 1) || loading) return;
loading = true;
@@ -305,11 +354,182 @@
modalError = '';
}
async function changeEmail() {
const email = editEmailValue.trim();
if (!email) return;
let totpcode = '';
if (totpEnabled) {
totpcode = await promptTotpCode('TOTP required to change email', 'Continue');
if (!totpcode) return;
}
emailActionLoading = true;
emailMessage = '';
emailError = '';
const token = getToken();
try {
const res = await fetch('/api/auth/email/change', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
email,
...(totpcode ? { totpcode } : {})
})
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
emailError = extractError(json) || 'Failed to send verification email.';
return;
}
emailMessage = json.message || 'Verification email sent.';
isEditingEmail = false;
editEmailValue = '';
} catch {
emailError = 'Network error';
} finally {
emailActionLoading = false;
}
}
async function changePassword() {
passwordMessage = '';
passwordError = '';
const currentPassword = passwordCurrentValue;
const newPassword = passwordNewValue;
const confirmPassword = passwordConfirmValue;
if (!currentPassword || !newPassword || !confirmPassword) {
passwordError = 'Current password, new password, and confirmation are required.';
return;
}
if (newPassword !== confirmPassword) {
passwordError = 'New passwords do not match.';
return;
}
if (!passwordValid) {
passwordError =
'Password should have at least 8 characters, no more than 128 characters, including uppercase, lowercase, and digits.';
return;
}
let totpcode = '';
if (totpEnabled || adminsRequire2FA) {
if (adminsRequire2FA && !totpEnabled) {
passwordError = '2FA is required to perform this action.';
return;
}
totpcode = await promptTotpCode('TOTP required to change password', 'Continue');
if (!totpcode) return;
}
passwordActionLoading = true;
const token = getToken();
try {
const res = await fetch('/api/auth/password/change', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
currentPassword,
newPassword,
...(totpcode ? { totpCode: totpcode } : {})
})
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
passwordError = extractError(json) || 'Failed to change password.';
return;
}
clearTokens();
window.location.href = '/login';
} catch {
passwordError = 'Network error';
} finally {
passwordActionLoading = false;
}
}
async function generatePasswordResetLink() {
passwordResetLinkMessage = '';
passwordResetLinkError = '';
const token = getToken();
if (!token || !data.user?.uuid) return;
try {
const requirements = await fetchActionSecurityRequirements('GeneratePasswordResetLink');
if (requirements.blocked) {
passwordResetLinkError =
requirements.message || 'You cannot perform this action right now.';
return;
}
let totpcode = '';
if (requirements.requiresTotp) {
totpcode = await promptTotpCode('TOTP required to generate reset link', 'Continue');
if (!totpcode) return;
}
passwordResetLinkLoading = true;
const res = await fetch(`/api/auth/password/admin-reset-link/${data.user.uuid}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
...(totpcode ? { totpCode: totpcode } : {})
})
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
passwordResetLinkError = extractError(json) || 'Failed to generate password reset link.';
return;
}
passwordResetLinkValue = json.resetLink || '';
passwordResetLinkMessage = json.message || 'Password reset link generated.';
} catch {
passwordResetLinkError = 'Network error';
} finally {
passwordResetLinkLoading = false;
}
}
async function resendVerificationEmail() {
emailActionLoading = true;
emailMessage = '';
emailError = '';
const token = getToken();
try {
const res = await fetch('/api/auth/email/resend-verification', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` }
});
const json = await res.json().catch(() => ({}));
if (!res.ok) {
emailError = extractError(json) || 'Failed to resend verification email.';
return;
}
emailMessage = json.message || 'Verification email sent.';
} catch {
emailError = 'Network error';
} finally {
emailActionLoading = false;
}
}
function startEditEmail() {
editEmailValue = data.user?.email || '';
isEditingEmail = true;
emailMessage = '';
emailError = '';
}
async function handleDeleteAccount() {
loading = true;
modalError = '';
const token = getToken();
let totpcode = '';
let verificationToken = '';
if (totpEnabled) {
totpcode = String(
await openModal<string>({
@@ -325,6 +545,42 @@
loading = false;
return;
}
} else if (isOwner && data.user?.emailVerified && data.user?.email) {
const requestRes = await fetch(`/api/user/uuid/${data.user?.uuid}/delete-verification`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`
}
});
if (!requestRes.ok) {
const err = await requestRes.json().catch(() => ({}));
loading = false;
modalError = extractError(err) || 'Failed to send account deletion verification email.';
await openModal({
mode: 'confirm',
title: 'Error',
message: modalError,
confirmButtonText: 'OK',
cancelValue: true
});
return;
}
verificationToken = String(
await openModal<string>({
mode: 'prompt',
title: 'Verify Account Deletion',
message: 'Enter the account deletion code sent to your verified email.',
placeholder: 'Deletion code',
inputType: 'text',
confirmButtonText: 'Delete Account',
cancelValue: ''
})
).trim();
if (!verificationToken) {
loading = false;
return;
}
}
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
method: 'DELETE',
@@ -332,7 +588,12 @@
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: totpEnabled && totpcode ? JSON.stringify({ totpcode }) : undefined
body:
totpEnabled && totpcode
? JSON.stringify({ totpcode })
: verificationToken
? JSON.stringify({ token: verificationToken })
: undefined
});
loading = false;
if (!res.ok) {
@@ -347,6 +608,10 @@
});
return;
}
if (isOwner) {
clearTokens();
user.set(null);
}
window.location.href = '/';
}
@@ -657,7 +922,7 @@
</div>
{/if}
</div>
{#if !isOwner && !$user?.isBanned && $user}
{#if !isOwner && !$user?.isBanned && $user && (!hasRole(data.user.roles, roles.Admin) || !hasRole(data.user.roles, roles.Moderator))}
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
@@ -847,6 +1112,117 @@
{/if}
</div>
</div>
{#if isOwner}
<div class="col-span-2">
<h2 class="text-xl font-semibold text-neutral-100">Email</h2>
<p class="mb-1 text-sm text-neutral-400">
Used for account verification and security notifications.
</p>
{#if emailError}
<div
class="mb-3 rounded border border-red-900/50 bg-red-900/10 p-3 text-sm text-red-200"
>
{emailError}
</div>
{/if}
{#if emailMessage}
<div
class="mb-3 rounded border border-green-900/50 bg-green-900/10 p-3 text-sm text-green-200"
>
{emailMessage}
</div>
{/if}
<div class="rounded bg-neutral-800/50 p-3">
{#if isEditingEmail}
<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
<input
type="email"
bind:value={editEmailValue}
placeholder="you@example.com"
class="w-full border-b border-neutral-600 bg-transparent px-2 py-1 font-mono text-neutral-300 outline-none focus:border-neutral-400"
autocomplete="email"
onkeydown={(e) => {
if (e.key === 'Enter') changeEmail();
else if (e.key === 'Escape') {
isEditingEmail = false;
editEmailValue = '';
}
}}
/>
<div class="flex shrink-0 gap-2">
<button
onclick={changeEmail}
disabled={emailActionLoading || !editEmailValue.trim()}
class="flex items-center gap-1 rounded bg-green-900/50 px-3 py-2 text-xs font-medium text-green-400 transition-colors hover:bg-green-900 disabled:opacity-50"
>
{#if emailActionLoading}
<LoaderCircle class="h-4 w-4 animate-spin" />
{:else}
<Check class="h-4 w-4" />
{/if}
Send verification
</button>
<button
onclick={() => {
isEditingEmail = false;
editEmailValue = '';
}}
class="flex items-center gap-1 rounded bg-neutral-700 px-3 py-2 text-xs font-medium text-neutral-300 transition-colors hover:bg-neutral-600"
>
<X class="h-4 w-4" />
Cancel
</button>
</div>
</div>
{:else}
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div class="flex min-w-0 flex-col gap-1">
<span class="font-mono break-all text-neutral-300">
{data.user?.email || 'No email set'}
</span>
<span
class="text-sm {data.user?.emailVerified
? 'text-green-400'
: 'text-amber-400'}"
>
{data.user?.email
? data.user?.emailVerified
? 'Verified'
: 'Not verified'
: 'Add an email to enable verification'}
</span>
</div>
<div class="flex flex-wrap gap-2">
{#if data.user?.email && !data.user?.emailVerified}
<button
onclick={resendVerificationEmail}
disabled={emailActionLoading}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-50"
>
{#if emailActionLoading}
<LoaderCircle class="h-4 w-4 animate-spin" />
{:else}
<Check class="h-4 w-4" />
{/if}
Resend
</button>
{/if}
<button
onclick={startEditEmail}
disabled={emailActionLoading}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-50"
>
<Pencil class="h-4 w-4" />
{data.user?.email ? 'Change' : 'Add'}
</button>
</div>
</div>
{/if}
</div>
</div>
{/if}
{:else if isOwner && activeSubTab === 'settings:security'}
<div class="col-span-2">
<div class="space-y-4">
@@ -864,6 +1240,138 @@
{totpEnabled ? 'Manage' : 'Enable'}
</button>
</div>
<div class="rounded bg-neutral-800/50 p-4">
<div class="mb-3 flex flex-col gap-1">
<span class="font-medium text-neutral-200">Change Password</span>
<span class="text-sm text-neutral-500">
Use your current password and choose a new one.
</span>
</div>
{#if passwordError}
<div
class="mb-3 rounded border border-red-900/50 bg-red-900/10 p-3 text-sm text-red-200"
>
{passwordError}
</div>
{/if}
{#if passwordMessage}
<div
class="mb-3 rounded border border-green-900/50 bg-green-900/10 p-3 text-sm text-green-200"
>
{passwordMessage}
</div>
{/if}
<div class="grid gap-3">
<input
type="password"
bind:value={passwordCurrentValue}
placeholder="Current password"
autocomplete="current-password"
class="w-full rounded border border-neutral-700 bg-neutral-900 px-3 py-2 text-neutral-200 transition-colors outline-none focus:border-neutral-500"
/>
<input
type="password"
bind:value={passwordNewValue}
placeholder="New password"
autocomplete="new-password"
onfocus={() => (passwordFocused = true)}
onblur={() => (passwordFocused = false)}
class="w-full rounded border border-neutral-700 bg-neutral-900 px-3 py-2 text-neutral-200 transition-colors outline-none focus:border-neutral-500"
/>
{#if passwordFocused}
<ul
transition:fade
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"
bind:value={passwordConfirmValue}
placeholder="Confirm new password"
autocomplete="new-password"
class="w-full rounded border border-neutral-700 bg-neutral-900 px-3 py-2 text-neutral-200 transition-colors outline-none focus:border-neutral-500"
/>
<div class="flex items-center justify-end">
<button
onclick={changePassword}
disabled={passwordActionLoading ||
!passwordValid ||
passwordNewValue !== passwordConfirmValue}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-50"
>
{#if passwordActionLoading}
<LoaderCircle class="h-4 w-4 animate-spin" />
{:else}
<KeyRound class="h-4 w-4" />
{/if}
Change Password
</button>
</div>
</div>
</div>
</div>
</div>
{#if isOwner}
@@ -911,6 +1419,62 @@
Edit
</button>
</div>
<div class="rounded bg-neutral-800/50 p-4">
<div class="flex justify-between gap-1">
<div class="flex flex-col">
<span class="font-medium text-neutral-200">Password Reset Link</span>
<span class="text-sm text-neutral-500">
Send the user a reset link or copy one for manual delivery.
</span>
</div>
<div class="flex items-center justify-end">
<button
onclick={generatePasswordResetLink}
disabled={passwordResetLinkLoading}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-50"
>
{#if passwordResetLinkLoading}
<LoaderCircle class="h-4 w-4 animate-spin" />
{:else}
<KeyRound class="h-4 w-4" />
{/if}
Generate Reset Link
</button>
</div>
</div>
{#if passwordResetLinkError}
<div
class="mt-3 rounded border border-red-900/50 bg-red-900/10 p-3 text-sm text-red-200"
>
{passwordResetLinkError}
</div>
{/if}
{#if passwordResetLinkMessage}
<div
class="mt-3 rounded border border-green-900/50 bg-green-900/10 p-3 text-sm text-green-200"
>
{passwordResetLinkMessage}
</div>
{/if}
{#if passwordResetLinkValue}
<div class="mt-3 flex items-center gap-2 rounded bg-neutral-900/70 p-2">
<code class="flex-1 font-mono text-sm break-all text-green-300"
>{passwordResetLinkValue}</code
>
<button
class="p-1 text-neutral-400 hover:text-white"
onclick={() => {
navigator.clipboard.writeText(passwordResetLinkValue);
}}
use:tooltip={'Copy reset link'}
>
<Copy class="h-4 w-4" />
</button>
</div>
{/if}
</div>
</div>
</div>
{#if !isOwner && data.user?.roles && !hasRole(data.user.roles, roles.Admin)}
@@ -1112,11 +1676,11 @@
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"
onclick={() => goto(resolve(`/report/${report.reportID}`))}
onclick={() => goto(resolve(`/report/[reportId]`, { reportId: String(report.reportID)}))}
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
goto(resolve(`/report/${report.reportID}`));
goto(resolve(`/report/[reportId]`, { reportId: String(report.reportID)}));
}
}}
>
@@ -1133,7 +1697,7 @@
<span>{reportTargetLabels[report.targetType] ?? 'Unknown'}</span>
{#if report.pasteId}
<a
href={resolve(`/${report.pasteId}`)}
href={resolve(`/[id]`, {id:report.pasteId})}
class="text-neutral-300 hover:text-white"
onclick={stopPropagation(bubble('click'))}
>
@@ -1143,7 +1707,7 @@
{#if report.userUUID}
{#if report.targetUsername}
<a
href={resolve(`/user/${report.targetUsername}`)}
href={resolve(`/user/[username]`, { username: report.targetUsername})}
class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID}
onclick={stopPropagation(bubble('click'))}
@@ -1171,11 +1735,11 @@
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"
onclick={() => goto(resolve(`/report/${report.reportID}`))}
onclick={() => goto(resolve(`/report/[reportId]`, { reportId: String(report.reportID)}))}
onkeydown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
goto(resolve(`/report/${report.reportID}`));
goto(resolve(`/report/[reportId]`, { reportId: String(report.reportID)}));
}
}}
>
@@ -1192,7 +1756,7 @@
<span>{reportTargetLabels[report.targetType] ?? 'Unknown'}</span>
{#if report.reporterUsername}
<a
href={resolve(`/user/${report.reporterUsername}`)}
href={resolve(`/user/[username]`, { username: report.reporterUsername})}
class="text-neutral-300 hover:text-white"
use:tooltip={report.reporterUUID}
onclick={stopPropagation(bubble('click'))}
@@ -1204,7 +1768,7 @@
{/if}
{#if report.pastePID}
<a
href={resolve(`/${report.pasteId ?? report.pastePID}`)}
href={resolve(`/[id]`, { id: report.pasteId ?? ""})}
class="text-neutral-300 hover:text-white"
onclick={stopPropagation(bubble('click'))}
>
@@ -1214,7 +1778,7 @@
{#if report.userUUID}
{#if report.targetUsername}
<a
href={resolve(`/user/${report.targetUsername}`)}
href={resolve(`/user/[username]`, { username: report.targetUsername})}
class="text-neutral-300 hover:text-white"
use:tooltip={report.userUUID}
onclick={stopPropagation(bubble('click'))}
@@ -1,7 +1,7 @@
import type { RequestEvent } from '@sveltejs/kit';
import { error, redirect } from '@sveltejs/kit';
import { apiUrl } from '$lib/server/api';
import { getServerToken } from '$lib/utils/auth';
import { apiUrl } from '#lib/server/api';
import { getServerToken } from '#lib/utils/auth';
export const load = async ({ params, fetch, cookies }: RequestEvent) => {
const token = getServerToken(cookies);
@@ -1,5 +1,5 @@
import { apiUrl } from '$lib/server/api';
import { extractError } from '$lib/utils/misc';
import { apiUrl } from '#lib/server/api';
import { extractError } from '#lib/utils/misc';
import { error } from '@sveltejs/kit';
export const load = async ({ url, request }) => {
-18
View File
@@ -1,18 +0,0 @@
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://svelte.dev/docs/kit/integrations
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://svelte.dev/docs/kit/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;
+8 -3
View File
@@ -1,5 +1,7 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"extends": "$app/tsconfig",
"include": ["src", "test", "*"],
"exclude": ["src/service-worker"],
"compilerOptions": {
"rewriteRelativeImportExtensions": true,
"allowJs": true,
@@ -10,10 +12,13 @@
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
"moduleResolution": "bundler",
"paths": {
"#lib/*": ["./src/lib/*"]
}
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
// except #lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// To make changes to top-level options such as include and exclude, we recommend extending
// the generated config; see https://svelte.dev/docs/kit/configuration#typescript
+3 -1
View File
@@ -1,5 +1,7 @@
import tailwindcss from '@tailwindcss/vite';
import { sveltekit } from '@sveltejs/kit/vite';
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
@@ -14,7 +16,7 @@ const allowedHosts = process.env.VITE_ALLOWED_HOSTS
: ['localhost'];
export default defineConfig({
plugins: [tailwindcss(), sveltekit()],
plugins: [tailwindcss(), sveltekit({ adapter: adapter(), preprocess: vitePreprocess() })],
define: {
__APP_VERSION__: JSON.stringify(pkg.version),
COMMIT_HASH: JSON.stringify(process.env.GIT_COMMIT_HASH || 'unknown')
+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 });
}
}
}
@@ -179,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)
@@ -294,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);
@@ -393,6 +397,8 @@ namespace SharpbinV3.Server.Controllers
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
@@ -258,7 +258,11 @@ namespace SharpbinV3.Server.Controllers
if (!Enum.IsDefined(reportType))
return BadRequest(new { success = false, message = "Invalid report type." });
if (!await _verificationService.VerifyAsync(new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }))
if (
!await _verificationService.VerifyAsync(
new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
)
)
return BadRequest(new { success = false, message = "Verification failed." });
Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description);
@@ -360,11 +364,17 @@ namespace SharpbinV3.Server.Controllers
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() }))
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);
+100 -38
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;
@@ -113,48 +115,50 @@ namespace SharpbinV3.Server.Controllers
return BadRequest(ModelState);
var jwtUser = HttpContext.GetJwtUser()!;
var reqUser = await _userService.GetByUUID(uuid);
if (reqUser == null)
var actorUser = await _userService.GetByUUID(jwtUser.UUID);
if (actorUser == null)
return Unauthorized(new { success = false, message = "User not authenticated." });
var targetUser = await _userService.GetByUUID(uuid);
if (targetUser == null)
return NotFound(new { success = false, message = "User not found." });
var user = await _userService.GetByUUID(uuid);
if (user == null)
return NotFound(new { success = false, message = "User not found." });
var actorIsAdmin = actorUser.Roles.HasFlag(Role.Admin);
var isSelfUpdate = targetUser.UUID == actorUser.UUID;
if (
(user.Roles.HasFlag(Role.Admin) && !reqUser.Roles.HasFlag(Role.Admin))
|| (!reqUser.Roles.HasFlag(Role.Admin) && user.UUID != reqUser.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." });
bool isSensitiveUpdate =
(updatedUser.Roles.HasValue && updatedUser.Roles.Value != user.Roles) // updating roles
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != user.IsBanned) // updating ban status
|| (
updatedUser.Email != null && updatedUser.Email != user.Email // updating email
);
if ((updatedUser.Roles.HasValue || updatedUser.IsBanned.HasValue) && !actorIsAdmin)
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (reqUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA && isSensitiveUpdate)
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." });
if (isSensitiveUpdate && jwtUser.TotpEnabled)
{
if (
string.IsNullOrEmpty(updatedUser.TotpCode)
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = reqUser.UUID, Code = updatedUser.TotpCode })
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = actorUser.UUID, Code = updatedUser.TotpCode })
)
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
if (user.Roles.HasFlag(Role.Admin) && !reqUser.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
if (
updatedUser.Roles.HasValue
&& user.Roles.HasFlag(Role.Admin)
&& targetUser.Roles.HasFlag(Role.Admin)
&& !updatedUser.Roles.Value.HasFlag(Role.Admin)
&& reqUser.UID > user.UID
&& !isSelfUpdate
&& actorUser.UID > targetUser.UID
)
// prevents demoting of other older admins by newer admins
// allows self demotion in case of compromisation
@@ -162,16 +166,15 @@ namespace SharpbinV3.Server.Controllers
return StatusCode(403, new { success = false, message = "You cannot remove the admin role from this user." });
}
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
if (reqUser.Roles.HasFlag(Role.Admin) || user.UUID == reqUser.UUID)
targetUser.DisplayName = updatedUser.DisplayName ?? targetUser.DisplayName;
if (actorIsAdmin || isSelfUpdate)
{
user.Email = updatedUser.Email ?? user.Email;
user.Visibility = updatedUser.Visibility ?? user.Visibility;
targetUser.Visibility = updatedUser.Visibility ?? targetUser.Visibility;
}
if (reqUser.Roles.HasFlag(Role.Admin))
if (actorIsAdmin)
{
user.Roles = updatedUser.Roles ?? user.Roles;
user.IsBanned = updatedUser.IsBanned ?? user.IsBanned;
targetUser.Roles = updatedUser.Roles ?? targetUser.Roles;
targetUser.IsBanned = updatedUser.IsBanned ?? targetUser.IsBanned;
}
await _db.SaveChangesAsync();
@@ -191,6 +194,8 @@ 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))
@@ -206,30 +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("uuid/{uuid}/delete-verification")]
[Authorize(Policy = "JwtOnlyAndNotBanned")]
[EnableRateLimiting("Sensitive")]
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." });
if (user.Roles.HasFlag(Role.Admin))
return StatusCode(403, new { success = false, message = "You cannot delete an admin user." });
if (jwtUser.TotpEnabled)
return BadRequest(new { success = false, message = "Use TOTP to delete this account." });
if (!user.EmailVerified || string.IsNullOrWhiteSpace(user.Email))
return BadRequest(new { success = false, message = "A verified email address is required for email deletion verification." });
var result = await _authService.RequestAccountDeletionVerification(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 });
}
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);
}
@@ -259,6 +319,8 @@ namespace SharpbinV3.Server.Controllers
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();
@@ -270,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; }
}
}
+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; }
+4
View File
@@ -43,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)
@@ -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; }
+1
View File
@@ -15,6 +15,7 @@ namespace SharpbinV3.Server.Data.Entities
[Index(nameof(UID))]
[Index(nameof(UUID), IsUnique = true)]
[Index(nameof(Username), IsUnique = true)]
public sealed class User
{
public long? UID { get; set; }
@@ -3,6 +3,7 @@ namespace SharpbinV3.Server.Data.Enums
public enum SecurityAction
{
UpdateRoles = 1,
DeleteUser = 2
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>
@@ -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");
}
}
}
@@ -132,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");
@@ -418,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");
});
+37 -35
View File
@@ -190,12 +190,12 @@ namespace SharpbinV3.Server
"Sliding",
httpContext =>
RateLimitPartition.GetSlidingWindowLimiter(
httpContext.GetRequestIP(),
GetRateLimitPartitionKey(httpContext),
_ => new SlidingWindowRateLimiterOptions
{
Window = TimeSpan.FromSeconds(10),
PermitLimit = 10,
QueueLimit = 2,
PermitLimit = 15,
QueueLimit = 5,
SegmentsPerWindow = 5,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
@@ -206,13 +206,13 @@ namespace SharpbinV3.Server
"Strict",
httpContext =>
RateLimitPartition.GetTokenBucketLimiter(
httpContext.GetRequestIP(),
GetRateLimitPartitionKey(httpContext),
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 5,
TokenLimit = 15,
QueueLimit = 0,
TokensPerPeriod = 1,
ReplenishmentPeriod = TimeSpan.FromSeconds(30),
ReplenishmentPeriod = TimeSpan.FromSeconds(10),
AutoReplenishment = true,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
}
@@ -223,10 +223,10 @@ namespace SharpbinV3.Server
"Sensitive",
httpContext =>
RateLimitPartition.GetTokenBucketLimiter(
httpContext.GetRequestIP(),
GetRateLimitPartitionKey(httpContext),
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 3,
TokenLimit = 5,
QueueLimit = 0,
TokensPerPeriod = 1,
ReplenishmentPeriod = TimeSpan.FromMinutes(1),
@@ -240,13 +240,11 @@ namespace SharpbinV3.Server
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
{
var remoteIp = httpContext.GetRequestIP();
return RateLimitPartition.GetFixedWindowLimiter(
remoteIp,
GetRateLimitPartitionKey(httpContext),
_ => new FixedWindowRateLimiterOptions
{
PermitLimit = 120,
PermitLimit = 180,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 0,
@@ -257,6 +255,9 @@ namespace SharpbinV3.Server
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, cancellationToken) =>
{
if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
context.HttpContext.Response.Headers.RetryAfter = Math.Ceiling(retryAfter.TotalSeconds).ToString();
await context.HttpContext.Response.WriteAsJsonAsync(
new { success = false, Message = "Too many requests. Please try again later." },
cancellationToken: cancellationToken
@@ -276,7 +277,9 @@ namespace SharpbinV3.Server
builder.Services.AddCors(o =>
{
o.AddDefaultPolicy(p => p.WithOrigins("http://localhost:5173").AllowAnyHeader().AllowAnyMethod());
var allowedOrigins =
builder.Configuration.GetSection(nameof(AppSettings.AllowedCorsOrigins)).Get<string[]>() ?? ["http://localhost:5173"];
o.AddDefaultPolicy(p => p.WithOrigins(allowedOrigins).AllowAnyHeader().AllowAnyMethod());
});
builder
@@ -285,14 +288,15 @@ namespace SharpbinV3.Server
.SetApplicationName("SharpbinV3");
var app = builder.Build();
app.UseRateLimiter();
app.MapOpenApi();
if (app.Environment.IsDevelopment())
app.MapOpenApi();
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthentication();
app.UseRateLimiter();
app.UseAuthorization();
app.UseOutputCache();
@@ -303,21 +307,6 @@ namespace SharpbinV3.Server
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
db.Database.Migrate();
// this is temporary since the migration doesnt seem to work properly
db.Database.ExecuteSql(
$"""
CREATE TRIGGER IF NOT EXISTS Users_UID_AutoIncrement
AFTER INSERT ON Users
BEGIN
UPDATE Users
SET UID = (
SELECT IFNULL(MAX(UID), 0) + 1 FROM Users
)
WHERE rowid = NEW.rowid AND NEW.UID IS NULL;
END;
"""
);
}
app.MapHealthChecks("/health");
@@ -332,8 +321,8 @@ namespace SharpbinV3.Server
var pasteCount = await db.Pastes.CountAsync();
var userCount = await db.Users.CountAsync();
var totalPasteSize = await db.Pastes.SumAsync(p => p.StoredSize);
var trueTotalPasteSize = await db.Pastes.SumAsync(p => p.OriginalSize);
var totalStoredSize = await db.Pastes.SumAsync(p => p.StoredSize);
var totalOriginalSize = await db.Pastes.SumAsync(p => p.OriginalSize);
var dailyCounts = await db
.Pastes.Where(p => p.CreatedAt >= sevenDaysAgo)
@@ -363,8 +352,8 @@ namespace SharpbinV3.Server
{
total = pasteCount,
past7Days = pasteCountWeek,
totalSizeInBytes = totalPasteSize,
trueTotalSizeInBytes = trueTotalPasteSize,
totalStoredSizeInBytes = totalStoredSize,
totalOriginalSizeInBytes = totalOriginalSize,
daily = dailyStats,
},
users = new { total = userCount },
@@ -384,11 +373,24 @@ namespace SharpbinV3.Server
if (!string.IsNullOrEmpty(overridepath))
return new DirectoryInfo(overridepath);
var basePath = env.IsDevelopment() ? Environment.CurrentDirectory : Environment.SpecialFolder.ApplicationData.ToString();
var basePath = env.IsDevelopment() ? Environment.CurrentDirectory : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var path = Path.Combine(basePath, "SharpbinV3", "DataProtectionKeys");
return new DirectoryInfo(path);
}
static string GetRateLimitPartitionKey(HttpContext httpContext)
{
var apiKey = httpContext.GetApiKeyFromContext();
if (apiKey != null)
return $"api-key:{apiKey.UUID}";
var user = httpContext.GetJwtUser();
if (user != null)
return $"user:{user.UUID}";
return $"ip:{httpContext.GetRequestIP()}";
}
}
}
+10 -6
View File
@@ -13,14 +13,18 @@ This is the backend API for SharpbinV3, built with ASP.NET Core and Entity Frame
The server configuration is managed in `appsettings.json`. For development, ensure you have set the following in `appsettings.Development.json` or as environment variables:
- `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=/app/data/sharpbin.db`).
- `JwtSettings__Secret`: A secure string used for signing JWT tokens.
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers
- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
- `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=sharpbin.db` locally). Compose defaults to `Data Source=/app/data/sharpbin.db`.
- `JwtSettings__Secret`: A random secret of 32–128 characters used for signing JWT tokens.
- `PasteSettings__View_HMAC_Secret`: A required random secret of 32–128 characters used to hash viewer identifiers.
- `PasteSettings__View_Internal_API_Key`: A shared key of 32–128 characters used to authorize view recording. Compose passes it to both services. For standalone deployments, match the frontend's `VIEW_INTERNAL_API_KEY`.
For Docker Compose, configure the backend in the root `.env` file. The image includes `appsettings.json` defaults, and environment variables override them. No host configuration mount is required.
The development frontend uses a fixed internal key matching the checked-in `appsettings.Development.json`. Changing only the backend key will break development view recording. Use generated secrets for deployment; see the [root configuration guide](../README.md#configuration).
### Database Migrations
Apply the database migrations to initialize the SQLite database:
The backend applies database migrations automatically on startup. To apply them manually before starting it:
```bash
dotnet ef database update
@@ -34,4 +38,4 @@ Use the following command to run the server with hot reload:
dotnet watch run
```
The API will be accessible at http://localhost:5050 by default (check `Properties/launchSettings.json` or your specific configuration).
The API will be accessible at http://localhost:5050 by default (check `Properties/launchSettings.json` or your specific configuration).
+1 -1
View File
@@ -18,7 +18,7 @@ namespace SharpbinV3.Server.Services
if (string.IsNullOrEmpty(_authSettings.API_Key_HMAC_Secret))
return Utilities.ComputeSha256(input);
else
return Utilities.ComputeHmacSha256(input, _authSettings.API_Key_HMAC_Secret);
return Utilities.ComputeHmacSha256(_authSettings.API_Key_HMAC_Secret, input);
}
public async Task<ApiKey?> GetByKeyAsync(string key)
+427 -22
View File
@@ -6,8 +6,11 @@ using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
using SharpbinV3.Server.Settings;
using Bcrypt = BCrypt.Net.BCrypt;
@@ -27,6 +30,7 @@ namespace SharpbinV3.Server.Services
public sealed class AuthService(
AppDbContext db,
EmailService email,
TotpVerificationProvider totp,
IOptions<JWTSettings> jwtOptions,
IOptions<AuthSettings> authOptions,
IOptions<AppSettings> appSettings,
@@ -35,19 +39,23 @@ namespace SharpbinV3.Server.Services
{
private readonly AppDbContext _db = db;
private readonly EmailService _email = email;
private readonly TotpVerificationProvider _totp = totp;
private readonly JWTSettings _jwtSettings = jwtOptions.Value;
private readonly AuthSettings _authSettings = authOptions.Value;
private readonly AppSettings _appSettings = appSettings.Value;
private readonly ILogger _logger = logger;
private const int EmailVerificationTokenLength = 64;
private static readonly TimeSpan EmailActionCooldown = TimeSpan.FromHours(12);
private static readonly TimeSpan EmailVerificationLifetime = TimeSpan.FromDays(1);
private static readonly TimeSpan PasswordResetLifetime = TimeSpan.FromDays(1);
public async Task<User> CreateUser(string username, string password, string? email, string? displayName)
{
var user = new User
{
Username = username,
Username = UserService.NormalizeUsername(username),
PasswordHash = Bcrypt.HashPassword(password),
Email = email,
Email = UserService.NormalizeEmail(email),
DisplayName = displayName,
UUID = Guid.CreateVersion7(),
};
@@ -141,23 +149,28 @@ namespace SharpbinV3.Server.Services
var jti = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value;
var userUUID = principal.Claims.First(c => c.Type == "uuid").Value;
var userGuid = Guid.Parse(userUUID);
var tokenHash = Utilities.ComputeSha256(refreshToken);
var storedToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash);
await using var transaction = await _db.Database.BeginTransactionAsync();
var now = DateTimeOffset.UtcNow;
var revokedCount = await _db.Database.ExecuteSqlInterpolatedAsync(
$"""
UPDATE RefreshTokens
SET Used = 1, Revoked = 1
WHERE TokenHash = {tokenHash}
AND Used = 0
AND Revoked = 0
AND ExpiresAt >= {now}
AND JwtId = {jti}
AND UserUUID = {userGuid}
"""
);
if (
storedToken == null
|| storedToken.Used
|| storedToken.Revoked
|| storedToken.ExpiresAt < DateTimeOffset.UtcNow
|| storedToken.JwtId != jti
|| storedToken.UserUUID != Guid.Parse(userUUID)
)
{
if (revokedCount != 1)
return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] };
}
var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID == Guid.Parse(userUUID));
var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID == userGuid);
if (user == null)
return new CreateJWT { Success = false, Errors = ["Invalid token."] };
@@ -165,9 +178,7 @@ namespace SharpbinV3.Server.Services
if (!newTokenResult.Success)
return newTokenResult;
storedToken.Used = true;
storedToken.Revoked = true;
await _db.SaveChangesAsync();
await transaction.CommitAsync();
return newTokenResult;
}
@@ -181,8 +192,8 @@ namespace SharpbinV3.Server.Services
public async Task<User> UpdateUser(User user)
{
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
existingUser.Username = user.Username;
existingUser.Email = user.Email;
existingUser.Username = UserService.NormalizeUsername(user.Username);
existingUser.Email = UserService.NormalizeEmail(user.Email);
existingUser.DisplayName = user.DisplayName;
existingUser.Roles = user.Roles;
existingUser.LastLogin = user.LastLogin;
@@ -200,6 +211,101 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync();
}
public async Task<(bool success, string message, long? retryAfter, string? resetLink)> GeneratePasswordResetLink(
User user,
bool sendEmail = true
)
{
return await IssuePasswordResetTokenAsync(user, sendEmail: sendEmail, invalidateExisting: true, exposeLink: true);
}
public async Task<(bool success, string message, bool requiresTotp, bool blocked, string username, User? user)> GetPasswordResetTokenInfo(
string token
)
{
var tokenEntity = await GetValidPasswordResetToken(token);
if (tokenEntity == null)
return (false, "Token is expired or already used.", false, false, string.Empty, null);
var user = tokenEntity.User;
if (user == null)
return (false, "Token is expired or already used.", false, false, string.Empty, null);
var state = await GetPasswordResetTwoFactorState(user);
return (true, "Token is valid.", state.requiresTotp, state.blocked, user.Username, user);
}
public async Task<(bool success, string message)> ChangeOwnPassword(User user, string currentPassword, string newPassword, string? totpCode)
{
if (!Bcrypt.Verify(currentPassword, user.PasswordHash))
return (false, "Current password is incorrect.");
var totpState = await GetPasswordResetTwoFactorState(user);
if (totpState.blocked)
return (false, "2FA is required to perform this action.");
if (totpState.requiresTotp)
{
if (
string.IsNullOrWhiteSpace(totpCode) || !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = totpCode })
)
return (false, "Invalid TOTP code.");
}
if (!RegisterUserDto.ValidatePassword().IsMatch(newPassword))
return (false, "Password should have at least 8 characters, including uppercase, lowercase, and digits.");
var originalEmail = user.Email;
await using var transaction = await _db.Database.BeginTransactionAsync();
await ReplacePasswordAsync(user, newPassword, saveChanges: false);
await _db.SaveChangesAsync();
await transaction.CommitAsync();
if (!string.IsNullOrWhiteSpace(originalEmail))
{
await _email.SendAsync(originalEmail, "Sharpbin Password Changed", EmailTemplates.PasswordChanged(user.Username));
}
return (true, "Password updated successfully.");
}
public async Task<(bool success, string message)> ResetPasswordWithToken(string token, string newPassword, string? totpCode)
{
if (!RegisterUserDto.ValidatePassword().IsMatch(newPassword))
return (false, "Password should have at least 8 characters, including uppercase, lowercase, and digits.");
var tokenEntity = await GetValidPasswordResetToken(token);
if (tokenEntity == null || tokenEntity.User == null)
return (false, "Token is expired or already used.");
var user = tokenEntity.User;
var totpState = await GetPasswordResetTwoFactorState(user);
if (totpState.blocked)
return (false, "2FA is required to perform this action.");
if (totpState.requiresTotp)
{
if (
string.IsNullOrWhiteSpace(totpCode) || !await _totp.VerifyAsync(new VerificationContext { UserUUID = user.UUID, Code = totpCode })
)
return (false, "Invalid TOTP code.");
}
await using var transaction = await _db.Database.BeginTransactionAsync();
var originalEmail = user.Email;
tokenEntity.Used = true;
await ReplacePasswordAsync(user, newPassword, saveChanges: false);
await _db.SaveChangesAsync();
await transaction.CommitAsync();
if (!string.IsNullOrWhiteSpace(originalEmail))
{
await _email.SendAsync(originalEmail, "Sharpbin Password Changed", EmailTemplates.PasswordChanged(user.Username));
}
return (true, "Password reset successfully.");
}
public async Task<User?> GetUserFromHttpContext(HttpContext context)
{
var apiKey = context.GetApiKeyFromContext();
@@ -213,15 +319,165 @@ namespace SharpbinV3.Server.Services
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID);
}
public async Task SendEmailVerification(User user)
public async Task<(bool success, string message, long? retryAfter)> ResendEmailVerification(User user)
{
if (string.IsNullOrWhiteSpace(user.Email))
return (false, "No email address is set for this account.", null);
if (user.EmailVerified)
return (false, "Email is already verified.", null);
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.VerifyEmail);
if (cooldown > TimeSpan.Zero)
return (
false,
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another verification email.",
Utilities.TimeSpanToMilliseconds(cooldown)
);
await SendEmailVerification(user, invalidateExisting: true);
return (true, "Verification email sent.", null);
}
public async Task<(bool success, string message, long? retryAfter)> RequestPasswordResetForEmail(string email)
{
var normalizedEmail = UserService.NormalizeEmail(email);
if (normalizedEmail == null)
return (true, "If an account exists for that email, a reset link has been sent.", null);
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == normalizedEmail);
if (user == null)
return (true, "If an account exists for that email, a reset link has been sent.", null);
await IssuePasswordResetTokenAsync(user, sendEmail: true, invalidateExisting: true, exposeLink: false);
return (true, "If an account exists for that email, a reset link has been sent.", null);
}
public async Task<(bool success, string message, long? retryAfter)> RequestAccountDeletionVerification(User user)
{
if (string.IsNullOrWhiteSpace(user.Email) || !user.EmailVerified)
return (false, "A verified email address is required for email deletion verification.", null);
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.DeleteAccount);
if (cooldown > TimeSpan.Zero)
return (
false,
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another account deletion email.",
Utilities.TimeSpanToMilliseconds(cooldown)
);
await InvalidateActiveTokens(user.UUID, EmailTokenType.DeleteAccount);
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
var tokenHash = Utilities.ComputeSha256(token);
var emailBody = EmailTemplates.DeleteAccountVerification(user.Username, token);
await _email.SendAsync(user.Email, "Confirm Account Deletion - Sharpbin", emailBody);
await _db.EmailVerificationTokens.AddAsync(
new EmailVerificationToken
{
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
Type = EmailTokenType.DeleteAccount,
}
);
await _db.SaveChangesAsync();
return (true, "Account deletion verification email sent.", null);
}
public async Task<bool> VerifyAccountDeletionToken(User user, string token)
{
if (token.Length != EmailVerificationTokenLength)
return false;
var tokenHash = Utilities.ComputeSha256(token);
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var tokenEntity = await _db.EmailVerificationTokens.FirstOrDefaultAsync(t =>
t.UserUUID == user.UUID && t.TokenHash == tokenHash && t.Type == EmailTokenType.DeleteAccount && !t.Used && t.ExpiresAt >= now
);
if (tokenEntity == null)
return false;
tokenEntity.Used = true;
await _db.SaveChangesAsync();
return true;
}
public async Task SendAccountDeletedNotification(string email, string username)
{
if (string.IsNullOrWhiteSpace(email))
return;
await _email.SendAsync(email, "Sharpbin Account Deleted", EmailTemplates.AccountDeleted(username));
}
public async Task<(bool success, string message, long? retryAfter)> RequestEmailChange(User user, string requestedEmail)
{
var newEmail = UserService.NormalizeEmail(requestedEmail);
if (newEmail == null)
return (false, "Email is required.", null);
if (string.Equals(user.Email, newEmail, StringComparison.OrdinalIgnoreCase))
return (false, "That email is already on your account.", null);
var existingEmailUser = await _db.Users.FirstOrDefaultAsync(u => u.Email == newEmail && u.UUID != user.UUID);
if (existingEmailUser != null)
return (false, "Email already in use.", null);
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.ChangeEmail);
if (cooldown > TimeSpan.Zero)
return (
false,
$"Please wait {Utilities.FormatDuration(cooldown)} before changing your email again.",
Utilities.TimeSpanToMilliseconds(cooldown)
);
await InvalidateActiveEmailTokens(user.UUID);
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
var tokenHash = Utilities.ComputeSha256(token);
var verificationUrl = BuildVerificationUrl(token);
var emailBody = EmailTemplates.VerifyChangedEmail(verificationUrl, user.Username);
await _email.SendAsync(newEmail, "Verify Your New Email - Sharpbin", emailBody);
if (!string.IsNullOrWhiteSpace(user.Email))
{
var notificationBody = EmailTemplates.EmailChangeRequested(user.Username, user.Email, newEmail);
await _email.SendAsync(user.Email, "Sharpbin Email Change Requested", notificationBody);
}
var verificationToken = new EmailVerificationToken
{
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
TargetEmail = newEmail,
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
Type = EmailTokenType.ChangeEmail,
};
await _db.EmailVerificationTokens.AddAsync(verificationToken);
await _db.SaveChangesAsync();
return (true, "Verification email sent to the new address.", null);
}
public async Task SendEmailVerification(User user, bool invalidateExisting = true)
{
if (string.IsNullOrWhiteSpace(user.Email))
return;
if (invalidateExisting)
await InvalidateActiveEmailTokens(user.UUID);
string token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
string tokenHash = Utilities.ComputeSha256(token);
string verificationUrl = $"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}";
string verificationUrl = BuildVerificationUrl(token);
string emailBody = EmailTemplates.VerifyEmail(verificationUrl, user.Username);
await _email.SendAsync(user.Email, "Verify Your Email - Sharpbin", emailBody);
@@ -230,13 +486,59 @@ namespace SharpbinV3.Server.Services
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
ExpiresAt = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(),
ExpiresAt = DateTimeOffset.UtcNow.Add(EmailVerificationLifetime).ToUnixTimeMilliseconds(),
Type = EmailTokenType.VerifyEmail,
};
await _db.EmailVerificationTokens.AddAsync(verificationToken);
await _db.SaveChangesAsync();
}
public async Task<(bool success, string message, long? retryAfter, string? resetLink)> IssuePasswordResetTokenAsync(
User user,
bool sendEmail,
bool invalidateExisting,
bool exposeLink
)
{
if (string.IsNullOrWhiteSpace(user.Email) && sendEmail)
return (false, "No email address is set for this account.", null, null);
var cooldown = await GetEmailTokenCooldown(user.UUID, EmailTokenType.ResetPassword);
if (cooldown > TimeSpan.Zero)
return (
false,
$"Please wait {Utilities.FormatDuration(cooldown)} before requesting another password reset link.",
Utilities.TimeSpanToMilliseconds(cooldown),
null
);
if (invalidateExisting)
await InvalidateActiveTokens(user.UUID, EmailTokenType.ResetPassword);
var token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
var tokenHash = Utilities.ComputeSha256(token);
var resetLink = BuildResetPasswordUrl(token);
if (sendEmail && !string.IsNullOrWhiteSpace(user.Email))
{
var emailBody = EmailTemplates.ResetPassword(user.Username, resetLink);
await _email.SendAsync(user.Email, "Reset Your Password - Sharpbin", emailBody);
}
var verificationToken = new EmailVerificationToken
{
TokenHash = tokenHash,
UserUUID = user.UUID,
User = user,
ExpiresAt = DateTimeOffset.UtcNow.Add(PasswordResetLifetime).ToUnixTimeMilliseconds(),
Type = EmailTokenType.ResetPassword,
};
await _db.EmailVerificationTokens.AddAsync(verificationToken);
await _db.SaveChangesAsync();
return (true, sendEmail ? "Password reset email sent." : "Password reset link generated.", null, exposeLink ? resetLink : null);
}
public async Task<(bool success, string message)> VerifyEmailVerificationToken(string token)
{
if (token.Length != EmailVerificationTokenLength)
@@ -255,13 +557,116 @@ namespace SharpbinV3.Server.Services
if (verificationToken != null && !verificationToken.Used)
{
if (verificationToken.Type == EmailTokenType.ChangeEmail)
{
if (string.IsNullOrWhiteSpace(verificationToken.TargetEmail))
return (false, "Token is invalid.");
var normalizedTargetEmail = UserService.NormalizeEmail(verificationToken.TargetEmail);
if (normalizedTargetEmail == null)
return (false, "Token is invalid.");
var existingEmailUser = await _db.Users.FirstOrDefaultAsync(u =>
u.Email == normalizedTargetEmail && u.UUID != verificationToken.UserUUID
);
if (existingEmailUser != null)
return (false, "Email already in use.");
if (!string.IsNullOrWhiteSpace(verificationToken.User.Email))
{
var notificationBody = EmailTemplates.EmailChanged(
verificationToken.User.Username,
verificationToken.User.Email,
normalizedTargetEmail
);
await _email.SendAsync(verificationToken.User.Email, "Sharpbin Email Address Changed", notificationBody);
}
verificationToken.User.Email = normalizedTargetEmail;
}
verificationToken.Used = true;
verificationToken.User.EmailVerified = true;
await InvalidateActiveEmailTokens(verificationToken.UserUUID);
await _db.SaveChangesAsync();
}
await _db.SaveChangesAsync();
return (true, "Email successfully verified.");
}
private async Task ReplacePasswordAsync(User user, string newPassword, bool saveChanges = true)
{
var existingUser = await _db.Users.FirstOrDefaultAsync(u => u.UUID == user.UUID) ?? throw new Exception("User not found");
existingUser.PasswordHash = Bcrypt.HashPassword(newPassword);
await _db
.RefreshTokens.Where(rt => rt.UserUUID == user.UUID && !rt.Revoked)
.ExecuteUpdateAsync(setters => setters.SetProperty(rt => rt.Revoked, true).SetProperty(rt => rt.Used, true));
await InvalidateActiveTokens(user.UUID, EmailTokenType.ResetPassword);
_db.Users.Update(existingUser);
if (saveChanges)
await _db.SaveChangesAsync();
}
private async Task<EmailVerificationToken?> GetValidPasswordResetToken(string token)
{
if (token.Length != EmailVerificationTokenLength)
return null;
var tokenHash = Utilities.ComputeSha256(token);
return await _db
.EmailVerificationTokens.Include(t => t.User)
.FirstOrDefaultAsync(t => t.TokenHash == tokenHash && t.Type == EmailTokenType.ResetPassword);
}
private async Task<(bool requiresTotp, bool blocked)> GetPasswordResetTwoFactorState(User user)
{
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
var blocked = user.Roles.HasFlag(Role.Admin) && _authSettings.Admins_Require_2FA && !totpEnabled;
return (totpEnabled, blocked);
}
private async Task InvalidateActiveTokens(Guid userUUID, params EmailTokenType[] types)
{
var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var tokenTypes = types.Length > 0 ? types : [EmailTokenType.VerifyEmail, EmailTokenType.ChangeEmail, EmailTokenType.ResetPassword];
await _db
.EmailVerificationTokens.Where(t => t.UserUUID == userUUID && !t.Used && t.ExpiresAt >= now && tokenTypes.Contains(t.Type))
.ExecuteUpdateAsync(setters => setters.SetProperty(t => t.Used, true));
}
private async Task InvalidateActiveEmailTokens(Guid userUUID)
{
await InvalidateActiveTokens(userUUID, EmailTokenType.VerifyEmail, EmailTokenType.ChangeEmail);
}
private async Task InvalidateActivePasswordResetTokens(Guid userUUID)
{
await InvalidateActiveTokens(userUUID, EmailTokenType.ResetPassword);
}
private async Task<TimeSpan> GetEmailTokenCooldown(Guid userUUID, EmailTokenType type)
{
var lastCreatedAt = await _db
.EmailVerificationTokens.Where(t => t.UserUUID == userUUID && t.Type == type)
.OrderByDescending(t => t.CreatedAt)
.Select(t => (long?)t.CreatedAt)
.FirstOrDefaultAsync();
if (lastCreatedAt == null)
return TimeSpan.Zero;
var nextAllowedAt = DateTimeOffset.FromUnixTimeMilliseconds(lastCreatedAt.Value).Add(EmailActionCooldown);
var remaining = nextAllowedAt - DateTimeOffset.UtcNow;
return remaining > TimeSpan.Zero ? remaining : TimeSpan.Zero;
}
private string BuildVerificationUrl(string token) =>
$"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}";
private string BuildResetPasswordUrl(string token) =>
$"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/reset-password?token={token}";
}
}
+10 -6
View File
@@ -22,15 +22,17 @@ namespace SharpbinV3.Server.Services
data = _cs.Compress(content);
double compressionRatio = (double)data.Length / originalSize;
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(content);
var comment = new Comment
{
PastePID = paste.PID,
ParentCommentID = parentCommentId,
Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content),
StoredSize = data.Length,
Content = storedContent,
StoredSize = storedContent.Length,
OriginalSize = originalSize,
IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold,
IsCompressed = isCompressed,
UserUUID = author.UUID,
CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
};
@@ -51,12 +53,14 @@ namespace SharpbinV3.Server.Services
data = _cs.Compress(newContent);
double compressionRatio = (double)data.Length / originalSize;
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(newContent);
comment.Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(newContent);
comment.StoredSize = data.Length;
comment.Content = storedContent;
comment.StoredSize = storedContent.Length;
comment.OriginalSize = originalSize;
comment.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
comment.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
comment.IsCompressed = isCompressed;
_db.Comments.Update(comment);
var result = await _db.SaveChangesAsync();
@@ -37,5 +37,71 @@ namespace SharpbinV3.Server.Services
return RenderTemplate("Verify Your Email", contentTemplate, replacements);
}
public static string VerifyChangedEmail(string verificationUrl, string username)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.VerifyChangedEmail.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "VERIFICATION_URL", verificationUrl } };
return RenderTemplate("Verify Your New Email", contentTemplate, replacements);
}
public static string EmailChangeRequested(string username, string oldEmail, string newEmail)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.EmailChangeRequested.html");
var replacements = new Dictionary<string, string>
{
{ "USERNAME", username },
{ "OLD_EMAIL", oldEmail },
{ "NEW_EMAIL", newEmail },
};
return RenderTemplate("Email Change Requested", contentTemplate, replacements);
}
public static string EmailChanged(string username, string oldEmail, string newEmail)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.EmailChanged.html");
var replacements = new Dictionary<string, string>
{
{ "USERNAME", username },
{ "OLD_EMAIL", oldEmail },
{ "NEW_EMAIL", newEmail },
};
return RenderTemplate("Email Address Changed", contentTemplate, replacements);
}
public static string ResetPassword(string username, string resetUrl)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.ResetPassword.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "RESET_URL", resetUrl } };
return RenderTemplate("Reset Your Password", contentTemplate, replacements);
}
public static string PasswordChanged(string username)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.PasswordChanged.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username } };
return RenderTemplate("Password Changed", contentTemplate, replacements);
}
public static string DeleteAccountVerification(string username, string deleteToken)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.DeleteAccountVerification.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "DELETE_TOKEN", deleteToken } };
return RenderTemplate("Confirm Account Deletion", contentTemplate, replacements);
}
public static string AccountDeleted(string username)
{
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.AccountDeleted.html");
var replacements = new Dictionary<string, string> { { "USERNAME", username } };
return RenderTemplate("Account Deleted", contentTemplate, replacements);
}
}
}
+46 -73
View File
@@ -1,6 +1,5 @@
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities;
@@ -10,14 +9,11 @@ using SharpbinV3.Server.Settings;
namespace SharpbinV3.Server.Services
{
public sealed class PasteService(AppDbContext db, ICompressionService cs, IMemoryCache cache, IOptions<PasteSettings> options)
public sealed class PasteService(AppDbContext db, ICompressionService cs, IOptions<PasteSettings> options)
{
private readonly AppDbContext _db = db;
private readonly ICompressionService _cs = cs;
private readonly IMemoryCache _cache = cache;
private readonly PasteSettings _pasteSettings = options.Value;
private readonly Lock _invalidationLock = new();
private readonly HashSet<string> _pasteListCacheKeys = [];
public async Task<Paste> Create(
User? author,
@@ -35,6 +31,8 @@ namespace SharpbinV3.Server.Services
data = _cs.Compress(content);
double compressionRatio = (double)data.Length / originalSize;
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(content);
var paste = new Paste
{
@@ -43,10 +41,10 @@ namespace SharpbinV3.Server.Services
Title = title,
AuthorUUID = author?.UUID,
User = author,
Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(content),
StoredSize = data.Length,
Content = storedContent,
StoredSize = storedContent.Length,
OriginalSize = originalSize,
IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold,
IsCompressed = isCompressed,
Syntax = syntax,
Visibility = visibility,
ExpiresAt = expiresAt,
@@ -59,8 +57,6 @@ namespace SharpbinV3.Server.Services
}
await _db.SaveChangesAsync();
InvalidatePasteListCache();
return paste;
}
@@ -69,8 +65,6 @@ namespace SharpbinV3.Server.Services
_db.Pastes.Remove(paste);
var result = await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return result > 0;
}
@@ -79,8 +73,6 @@ namespace SharpbinV3.Server.Services
_db.Pastes.Update(paste);
await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return paste;
}
@@ -102,17 +94,17 @@ namespace SharpbinV3.Server.Services
data = _cs.Compress(text);
double compressionRatio = (double)data.Length / originalSize;
var isCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
var storedContent = isCompressed ? data : Encoding.UTF8.GetBytes(text);
paste.Content = compressionRatio < _pasteSettings.CompressionThreshold ? data : Encoding.UTF8.GetBytes(text);
paste.StoredSize = data.Length;
paste.Content = storedContent;
paste.StoredSize = storedContent.Length;
paste.OriginalSize = originalSize;
paste.EditedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
paste.IsCompressed = compressionRatio < _pasteSettings.CompressionThreshold;
paste.IsCompressed = isCompressed;
_db.Pastes.Update(paste);
var result = await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return result > 0;
}
@@ -151,7 +143,6 @@ namespace SharpbinV3.Server.Services
return (null, true);
}
InvalidatePasteCache(paste.ID);
return (paste, false);
}
@@ -172,7 +163,6 @@ namespace SharpbinV3.Server.Services
try
{
await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return interaction;
}
catch (DbUpdateException)
@@ -192,56 +182,56 @@ namespace SharpbinV3.Server.Services
_db.PasteInteractions.Remove(interaction);
await _db.SaveChangesAsync();
InvalidatePasteCache(paste.ID);
return true;
}
public async Task<Paste?> Get(string id)
{
string key = $"v1:paste:{id}";
var paste = await _cache.GetOrCreateAsync(
key,
async entry =>
{
entry.SetSlidingExpiration(TimeSpan.FromMinutes(10));
var _paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
if (_paste != null)
{
_paste.PositiveInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == _paste.PID && pi.Type == Interaction.Positive)
.CountAsync();
_paste.NegativeInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == _paste.PID && pi.Type == Interaction.Negative)
.CountAsync();
}
return _paste;
}
);
var paste = await _db.Pastes.AsNoTracking().Include(p => p.User).FirstOrDefaultAsync(p => p.ID == id);
if (paste != null)
{
paste.PositiveInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == paste.PID && pi.Type == Interaction.Positive)
.CountAsync();
paste.NegativeInteractionCount = await _db
.PasteInteractions.Where(pi => pi.PasteID == paste.PID && pi.Type == Interaction.Negative)
.CountAsync();
}
return paste ?? null;
}
public async Task<List<Paste>> GetList(int offset, int count, bool publicOnly = false)
{
string key = $"v1:list:pastes:public={publicOnly}:offset={offset}:count={count}";
var query = _db.Pastes.AsQueryable();
if (publicOnly)
query = query.Where(p => p.Visibility == 0);
var pastes = await _cache.GetOrCreateAsync(
key,
async entry =>
{
entry.SetSlidingExpiration(TimeSpan.FromMinutes(5));
var pastes = await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync();
lock (_invalidationLock)
_pasteListCacheKeys.Add(key);
if (pastes.Count == 0)
return pastes;
var query = _db.Pastes.AsQueryable();
if (publicOnly)
query = query.Where(p => p.Visibility == 0);
var pasteIds = pastes.Select(p => p.PID).ToArray();
var interactionCounts = (
await _db
.PasteInteractions.Where(pi => pasteIds.Contains(pi.PasteID))
.GroupBy(pi => new { pi.PasteID, pi.Type })
.Select(g => new
{
g.Key.PasteID,
g.Key.Type,
Count = g.Count(),
})
.ToListAsync()
).ToDictionary(counts => (counts.PasteID, counts.Type), counts => counts.Count);
return await query.OrderByDescending(p => p.PID).Skip(offset).Take(count).Include(p => p.User).ToListAsync();
}
);
foreach (var paste in pastes)
{
paste.PositiveInteractionCount = interactionCounts.GetValueOrDefault((paste.PID, Interaction.Positive));
paste.NegativeInteractionCount = interactionCounts.GetValueOrDefault((paste.PID, Interaction.Negative));
}
return pastes ?? [];
return pastes;
}
public async Task<PasteInteraction?> GetUserInteraction(Paste paste, Guid userUUID)
@@ -274,22 +264,5 @@ namespace SharpbinV3.Server.Services
var currentTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
return expiresAt > currentTime - 1000;
}
private void InvalidatePasteCache(string pasteId)
{
string key = $"v1:paste:{pasteId}";
_cache.Remove(key);
}
private void InvalidatePasteListCache()
{
lock (_invalidationLock)
{
foreach (var listKey in _pasteListCacheKeys)
_cache.Remove(listKey);
_pasteListCacheKeys.Clear();
}
}
}
}
+21 -17
View File
@@ -85,27 +85,31 @@ namespace SharpbinV3.Server.Services
public async Task<List<ReportResponseDto>> GetReports(ReportQuery query)
{
return await BuildReportQuery(query)
var pagedReports = BuildReportQuery(query)
.OrderByDescending(r => r.CreatedAt)
.Skip((query.Page - 1) * query.PageSize)
.Take(query.PageSize)
.Take(query.PageSize);
return await pagedReports
.GroupJoin(_db.Users, r => r.ReporterUUID, reporter => reporter.UUID, (report, reporters) => new { report, reporters })
.SelectMany(r => r.reporters.DefaultIfEmpty(), (r, reporter) => new { r.report, reporter })
.Select(r => new ReportResponseDto
{
ReportID = r.ReportID,
Type = r.Type,
Status = r.Status,
Description = r.Description,
CreatedAt = r.CreatedAt,
UpdatedAt = r.UpdatedAt,
ReporterUUID = r.ReporterUUID,
ReporterUsername = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.Username).FirstOrDefault(),
ReporterDisplayName = _db.Users.Where(u => u.UUID == r.ReporterUUID).Select(u => u.DisplayName).FirstOrDefault(),
TargetType = r.TargetType,
PasteId = r.Paste != null ? r.Paste.ID : null,
PasteTitle = r.Paste != null ? r.Paste.Title : null,
UserUUID = r.UserUUID,
TargetUsername = r.User != null ? r.User.Username : null,
TargetDisplayName = r.User != null ? r.User.DisplayName : null,
ReportID = r.report.ReportID,
Type = r.report.Type,
Status = r.report.Status,
Description = r.report.Description,
CreatedAt = r.report.CreatedAt,
UpdatedAt = r.report.UpdatedAt,
ReporterUUID = r.report.ReporterUUID,
ReporterUsername = r.reporter != null ? r.reporter.Username : null,
ReporterDisplayName = r.reporter != null ? r.reporter.DisplayName : null,
TargetType = r.report.TargetType,
PasteId = r.report.Paste != null ? r.report.Paste.ID : null,
PasteTitle = r.report.Paste != null ? r.report.Paste.Title : null,
UserUUID = r.report.UserUUID,
TargetUsername = r.report.User != null ? r.report.User.Username : null,
TargetDisplayName = r.report.User != null ? r.report.User.DisplayName : null,
})
.ToListAsync();
}

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