mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
336990f5b8
|
||
|
|
45878d5af1
|
||
|
|
2c43c0b29c
|
||
|
|
0e3a6d97e3
|
||
|
|
878457f49d
|
||
|
|
8d060204c8
|
||
|
|
f2559eaad0
|
||
|
|
e485b9782b
|
||
|
|
ed7e82adc2
|
||
|
|
f8a74d415d | ||
|
|
41342efbed | ||
|
|
e7a28ea8c0 | ||
|
|
e375b0a020
|
||
|
|
ee8b8f239d
|
||
|
|
eb331f7339 | ||
|
|
b304d8ac9f
|
||
|
|
d45f253c00
|
||
|
|
b0e9f5104c
|
||
|
|
da79f3713a | ||
|
|
18e8154248 | ||
|
|
4e8187c186 | ||
|
|
5c8f81b951 | ||
|
|
e8f2050eb1
|
||
|
|
db492054f7 | ||
|
|
936d74facf | ||
|
|
500a6cfe76 | ||
|
|
1bfc5dbbc4
|
||
|
|
6cadc0b74d
|
||
|
|
6ed2974e42
|
||
|
|
d4976ac9aa
|
||
|
|
67ccee736a
|
||
|
|
045a1934d8
|
||
|
|
d16f1f872f
|
||
|
|
4f5ca9a069
|
||
|
|
6a7b8653dc
|
||
|
|
6c810b07b7
|
||
|
|
df39f2bd46
|
||
|
|
f2c67ae367
|
||
|
|
a41048afe7 | ||
|
|
ed582afe0e | ||
|
|
3b8039e036 | ||
|
|
7a4c0a9b4d | ||
|
|
61efbf8b04
|
||
|
|
0d551b887f | ||
|
|
c6ba7b2ea9
|
||
|
|
f5a7aabf42
|
||
|
|
18c20cdf64
|
||
|
|
69aef92b09 | ||
|
|
a2a030936c | ||
|
|
77b4c11a9f | ||
|
|
c2383ff892 | ||
|
|
de58bc732c | ||
|
|
c2ec839f0a | ||
|
|
090d9ed533 | ||
|
|
aa5de648d7 | ||
|
|
dac67df266 | ||
|
|
e8cd93e7bd
|
||
|
|
41d441135c
|
||
|
|
52dd251e14
|
||
|
|
20473da0ba
|
||
|
|
99169305c7
|
||
|
|
a55268afdc
|
||
|
|
e20a6200dd
|
||
|
|
70e637b281
|
||
|
|
6c65a52ee0
|
||
|
|
40c6ac663f
|
||
|
|
c98e5e53b0
|
||
|
|
23f0c92aed
|
||
|
|
e239bf2ae5
|
||
|
|
95a5c18dc5
|
||
|
|
3da7f99feb
|
||
|
|
77f6623fcf
|
||
|
|
8d3caf5375
|
||
|
|
95ca811d42
|
||
|
|
63b77bece9
|
||
|
|
f82d314d80
|
||
|
|
38dd017dcd
|
||
|
|
9064aecedb
|
||
|
|
2864c81f83
|
||
|
|
df8b1456af
|
||
|
|
b65d3f8726
|
||
|
|
ac08f5e32e | ||
|
|
6201369342 | ||
|
|
fbf21b9d6e | ||
|
|
245f07bf64 | ||
|
|
7c9c4026f0 | ||
|
|
3f17a41285 | ||
|
|
f6dd45a87b | ||
|
|
0b4939ab17 | ||
|
|
ad693b28ea
|
||
|
|
b962ed9f67
|
||
|
|
60796a85fb
|
||
|
|
edffd5490f
|
||
|
|
ea634fd851
|
||
|
|
2b272f2e93 | ||
|
|
9999b90305 | ||
|
|
ee6a6d5e6d
|
||
|
|
13260ffc0f | ||
|
|
ddb0bb80de | ||
|
|
ec4bbad1d7
|
||
|
|
3b53cfbddf
|
||
|
|
6d99a06c17
|
||
|
|
094c8e5e08
|
||
|
|
801426f93e
|
||
|
|
abacbf14af
|
||
|
|
62d80597dc
|
||
|
|
ccb5db14d2 | ||
|
|
da423eb1c8 | ||
|
|
08c4bf4367 | ||
|
|
0aa9176835 | ||
|
|
e8eb677ba7
|
||
|
|
322af06832
|
||
|
|
d78baae19e
|
||
|
|
e102c91d79
|
||
|
|
6a59b72d08
|
||
|
|
27093acadf
|
||
|
|
4e02399d9f
|
||
|
|
b7ce54d5a0
|
||
|
|
8eede40000
|
||
|
|
c98aca92b6
|
||
|
|
5296efa9db
|
||
|
|
9486840f05
|
||
|
|
6047d48da2
|
||
|
|
73f73d88dc
|
||
|
|
1496a02b76
|
||
|
|
059d32e42c
|
||
|
|
797747f718
|
||
|
|
f70328c93d
|
||
|
|
8b8c0bbf7a
|
||
|
|
6eb4f699b5
|
||
|
|
e0c9f1bbc1
|
||
|
|
bf1c647d10
|
||
|
|
873b1778ee
|
||
|
|
44d7ae8cd3
|
||
|
|
0564d55396
|
||
|
|
5f11ee4350
|
||
|
|
4c071fcc39
|
||
|
|
e7cd3723a7
|
||
|
|
d4e2cf25d3
|
||
|
|
fbec598ee2
|
||
|
|
cb7f94fd5c
|
||
|
|
0c9a747935
|
||
|
|
38c8af1c57
|
||
|
|
ec0635dd3b
|
||
|
|
49e73cde9c
|
||
|
|
12f716eb83
|
||
|
|
c986a73ef4
|
||
|
|
b9cff6a0bd
|
||
|
|
2302ebdffc
|
||
|
|
2b66cb2762
|
||
|
|
32c46b8c2b
|
||
|
|
e329e1f8ea
|
||
|
|
2c794b833a
|
||
|
|
5420d94595
|
||
|
|
95da3f9543
|
||
|
|
d21265f443
|
||
|
|
7dbbcb65ac | ||
|
|
980cbfa989 | ||
|
|
528456c168
|
||
|
|
b54c12ba10
|
||
|
|
eef98030d6
|
||
|
|
00233280d4
|
||
|
|
4e8d71b8c6 | ||
|
|
73a1edcc85 | ||
|
|
f1aef1cc3c | ||
|
|
7d87e2be13 | ||
|
|
51c6ea5f98 | ||
|
|
3c346353aa | ||
|
|
ac2f0a3dcf
|
||
|
|
75ecfbe7e7
|
||
|
|
2c3f8c95ac
|
||
|
|
f64584602e
|
||
|
|
5eebea314e
|
||
|
|
f786117cad
|
||
|
|
3ba63f692c
|
||
|
|
012690f507
|
||
|
|
5017e73bb5
|
||
|
|
809b513e7a
|
||
|
|
3374eadb56
|
||
|
|
7d09870ad2
|
||
|
|
fd1cb3998c
|
||
|
|
3dc8070efe
|
||
|
|
78f4ae181e
|
||
|
|
ee45deb439
|
||
|
|
3b2801a655
|
||
|
|
cac34423d9
|
||
|
|
5052bbdb13
|
||
|
|
0283d987d0
|
||
|
|
ff706d8777
|
||
|
|
53d0f33ff0
|
||
|
|
db363f0211
|
@@ -1,6 +1,8 @@
|
|||||||
**/.classpath
|
**/.classpath
|
||||||
**/.dockerignore
|
**/.dockerignore
|
||||||
**/.env
|
**/.env
|
||||||
|
**/backend.env
|
||||||
|
**/frontend.env
|
||||||
**/.git
|
**/.git
|
||||||
**/.gitignore
|
**/.gitignore
|
||||||
**/.project
|
**/.project
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# These are supported funding model platforms
|
||||||
|
ko_fi: whoswhip
|
||||||
@@ -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
|
||||||
@@ -324,3 +324,7 @@ FodyWeavers.xsd
|
|||||||
Data
|
Data
|
||||||
!SharpbinV3.Server/Data
|
!SharpbinV3.Server/Data
|
||||||
.idea
|
.idea
|
||||||
|
|
||||||
|
**/.env
|
||||||
|
backend.env
|
||||||
|
frontend.env
|
||||||
|
|||||||
@@ -1,3 +1,80 @@
|
|||||||
|
## [3.0.5](https://github.com/whoswhip/Sharpbin/compare/v3.0.4...v3.0.5) (2026-03-31)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* add back CSV syntax support in consts and appsettings ([3ba63f6](https://github.com/whoswhip/Sharpbin/commit/3ba63f692c25e016f226fccc9120a3649c7150d9))
|
||||||
|
* **auth:** replace HMAC token generation with SHA256 for email verification ([49e73cd](https://github.com/whoswhip/Sharpbin/commit/49e73cde9c856bee9f36e2cedb9742bd6a3e9942))
|
||||||
|
* **backend:paste:** check expiration before returning paste data or recording views; prevent paste authors from adding views to their own paste ([ec0635d](https://github.com/whoswhip/Sharpbin/commit/ec0635dd3b6401679e1a4a923302de5dcdbecda8))
|
||||||
|
* **cache:** ensure pasteExpiresAt is valid before cache deletion ([c98aca9](https://github.com/whoswhip/Sharpbin/commit/c98aca92b68a761056b5610d893c7be17da06d96))
|
||||||
|
* **controller:** only return paste not found if null or expired ([f70328c](https://github.com/whoswhip/Sharpbin/commit/f70328c93d8b008f6015ec239cc984bbcc0b57e3))
|
||||||
|
* **controller:** update paste expiration check to handle zero expiration case ([797747f](https://github.com/whoswhip/Sharpbin/commit/797747f718913f1b52d0d17caf7fc1f720bde59b))
|
||||||
|
* correct expiration time for 'Expire in 5 Minutes' option ([f786117](https://github.com/whoswhip/Sharpbin/commit/f786117cad468d0c0cacae10bbfe82c8d647353b))
|
||||||
|
* **docker-compose:** add back VITE_API_URL environment variable to frontend ([d4e2cf2](https://github.com/whoswhip/Sharpbin/commit/d4e2cf25d3c4eb4c414b59ce6b5655cd9a3ba8a7))
|
||||||
|
* **docker-compose:** add env_file entries for backend and frontend services ([c986a73](https://github.com/whoswhip/Sharpbin/commit/c986a73ef44df90c2e47f3a2dc60900b2271d230))
|
||||||
|
* **docker:** correct environment variable syntax for backend service ([e0c9f1b](https://github.com/whoswhip/Sharpbin/commit/e0c9f1bbc1fc150d139043bbfb84ff16a86b20be))
|
||||||
|
* **dotenv:** skip empty lines and comments when loading environment variables ([2302ebd](https://github.com/whoswhip/Sharpbin/commit/2302ebdffc74dbd5023803919730ac5bb8243abf))
|
||||||
|
* **email:** ensure all email settings are validated before sending; allow nullable From property ([b9cff6a](https://github.com/whoswhip/Sharpbin/commit/b9cff6a0bd5899e3aaa3775981ae0782d621fa97))
|
||||||
|
* **email:** validate settings before sending; use hmac for tokens ([2b66cb2](https://github.com/whoswhip/Sharpbin/commit/2b66cb27629726480c00ffae4775810a35ee4fcf))
|
||||||
|
* **encryption:** improve encryption security: adjust salt size and memory parameters for AES encryption ([b54c12b](https://github.com/whoswhip/Sharpbin/commit/b54c12ba10c3f6607a6345caaa4d528e90f1ce0a))
|
||||||
|
* forward headers during requests where needed ([3b53cfb](https://github.com/whoswhip/Sharpbin/commit/3b53cfbddf0397c8b040641d784dce8b070c9753))
|
||||||
|
* forward the request header when viewing on the /[id] server route ([62d8059](https://github.com/whoswhip/Sharpbin/commit/62d80597dc51428fc3be810fb268b4bfd4cd6098))
|
||||||
|
* **frontend:paste:** increase paste views only if api returns 'Paste view recorded.' ([4c071fc](https://github.com/whoswhip/Sharpbin/commit/4c071fcc3965f1164d95d0c2dfd729059ee7cfad))
|
||||||
|
* **frontend:user:** resolve lint error ([2c3f8c9](https://github.com/whoswhip/Sharpbin/commit/2c3f8c95ac55a891caeaebacadad808bfc7180d2))
|
||||||
|
* **frontend:** use darker version of tooltip on generate random password ([eef9803](https://github.com/whoswhip/Sharpbin/commit/eef98030d6daf6c223d5e12e7ad024211e411d13))
|
||||||
|
* improve header handling and error checking in paste loading ([6d99a06](https://github.com/whoswhip/Sharpbin/commit/6d99a06c17b7365c26d4dd48405f2963f5826f1f))
|
||||||
|
* improve icon consistency ([e102c91](https://github.com/whoswhip/Sharpbin/commit/e102c91d79618b87b71653e23df7a6511a6c09ba))
|
||||||
|
* make syntax extension comparison case insensitive and remove '.' ([801426f](https://github.com/whoswhip/Sharpbin/commit/801426f93e08fdce0d548f8c539c5f7dc06fea93))
|
||||||
|
* remove rate limiting on {id}/raw and {id} ([094c8e5](https://github.com/whoswhip/Sharpbin/commit/094c8e5e08dcbef33d4f0e4d965ac467d8d4d6d4))
|
||||||
|
* **routes:** /raw/{pasteId} no longer returns a body on error ([38c8af1](https://github.com/whoswhip/Sharpbin/commit/38c8af1c5713defe06077842bacbf69ef47eff00))
|
||||||
|
* set default value for AuthSettings__First_User_Admin and pass GIT_COMMIT_HASH as build argument ([f645846](https://github.com/whoswhip/Sharpbin/commit/f64584602eb7b29a7854923420c25811a2a64946))
|
||||||
|
* switch to better sqlite-3 instead of experimental node api ([5296efa](https://github.com/whoswhip/Sharpbin/commit/5296efa9dbf4bfd6f6613cdee4806d170de9ba6d))
|
||||||
|
* **types:** add missing createdAt field to Paste interface ([6047d48](https://github.com/whoswhip/Sharpbin/commit/6047d48da2d5920e9e79b4e12b48a142ec9e2646))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* /user/{uuid} redirects to /user/{username} based off uuid ([059d32e](https://github.com/whoswhip/Sharpbin/commit/059d32e42c93fa0113e0bf253ab8bb432b3fa0b2))
|
||||||
|
* add GIT_COMMIT_HASH support for versioning in Dockerfile and footer ([5eebea3](https://github.com/whoswhip/Sharpbin/commit/5eebea314e6c475e012d0378aa4d6147485210f4))
|
||||||
|
* add HatGlasses icon for anonymous users in Paste component ([b7ce54d](https://github.com/whoswhip/Sharpbin/commit/b7ce54d5a0e00ee27e53e492b71a973d63e94bef))
|
||||||
|
* **auth:** add JWT user parsing from token ([d78baae](https://github.com/whoswhip/Sharpbin/commit/d78baae19e2508cac2205fcc9b3b09ee600d95fe))
|
||||||
|
* **auth:** improve token refreshing ([75ecfbe](https://github.com/whoswhip/Sharpbin/commit/75ecfbe7e7724addf71f2a9d1de41f28132602a1))
|
||||||
|
* **backend:** add DotEnv class for loading environment variables from .env file ([0023328](https://github.com/whoswhip/Sharpbin/commit/00233280d45a2fa87c4c01b9086620606be210e1))
|
||||||
|
* email verification via smtp ([95da3f9](https://github.com/whoswhip/Sharpbin/commit/95da3f95435709692de347272fae01dff13ddf7c))
|
||||||
|
* **email:** add email verification html templates ([0564d55](https://github.com/whoswhip/Sharpbin/commit/0564d55396da1f811aa7fa624a8f42392aeb49b9))
|
||||||
|
* **email:** implement email queue management ([5420d94](https://github.com/whoswhip/Sharpbin/commit/5420d94595bba2731409677631551b7bc265ad3c))
|
||||||
|
* guest param in user page ([8eede40](https://github.com/whoswhip/Sharpbin/commit/8eede40000f6a541188c95370073e76113d152d8))
|
||||||
|
* **markdown:** add dont warn again feature ([e7cd372](https://github.com/whoswhip/Sharpbin/commit/e7cd3723a7c60e3f058de990e1b7ac2efb414683))
|
||||||
|
* open graph embed image generation ([9486840](https://github.com/whoswhip/Sharpbin/commit/9486840f05fadac604f1ccd3a838f3f0d1a71f51))
|
||||||
|
* **roles, visibility:** refactor user roles to use flags and introduce visibility enum ([44d7ae8](https://github.com/whoswhip/Sharpbin/commit/44d7ae8cd3ead498f7975a20b5269ee311553d23))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## [3.0.4](https://github.com/whoswhip/Sharpbin/compare/v3.0.3...v3.0.4) (2026-02-14)
|
||||||
|
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
* **backend:** use GenerateSecureRandomString for api-keys, paste ids, and refresh tokens ([5017e73](https://github.com/whoswhip/Sharpbin/commit/5017e73bb54e626d4dc060fd553c972663eec45f))
|
||||||
|
* **frontend:api-keys:** add flag to track successful API key fetch ([78f4ae1](https://github.com/whoswhip/Sharpbin/commit/78f4ae181eb18a98ed9964d8e651d84319fa8d2c))
|
||||||
|
* **frontend:user:** resolve lint errors ([7d09870](https://github.com/whoswhip/Sharpbin/commit/7d09870ad25472ff17a1acc22d5724e199f2c931))
|
||||||
|
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
* add dotnet-ef tool configuration to dotnet-tools.json ([db363f0](https://github.com/whoswhip/Sharpbin/commit/db363f0211972a06b622770ca522d3ef0bba12c8))
|
||||||
|
* **backend:authentication:** implement API key authentication scheme and update authorization policies ([3374ead](https://github.com/whoswhip/Sharpbin/commit/3374eadb5654fa349a636c4a41a53df1ddf2edfe))
|
||||||
|
* **backend:utilities:** implement GenerateSecureRandomString function that uses RandomNumberGenerator ([809b513](https://github.com/whoswhip/Sharpbin/commit/809b513e7a3f5a4f7faf64b02d9ed83e81c540b8))
|
||||||
|
* **backend:** implement api keys; rename token -> verificationToken in paste creation api ([53d0f33](https://github.com/whoswhip/Sharpbin/commit/53d0f33ff026d6e5a188d80585e6a3bb633d9fa8))
|
||||||
|
* **frontend:api-keys:** display the count of API keys in the header and adjust empty state condition ([3dc8070](https://github.com/whoswhip/Sharpbin/commit/3dc8070efeb19538c4ff120d2a681c4167c716f3))
|
||||||
|
* **frontend:api-keys:** implement API key management features including creation, deletion, and fetching ([ee45deb](https://github.com/whoswhip/Sharpbin/commit/ee45deb43937cbf3996c3c379461110a484bd086))
|
||||||
|
* **frontend:modal:** decrease modal background opacity and blur ([3b2801a](https://github.com/whoswhip/Sharpbin/commit/3b2801a65509d3a894c701f03028b2cd4599b456))
|
||||||
|
* **frontend:stats:** enhance tooltip for total storage used to show uncompressed size ([cac3442](https://github.com/whoswhip/Sharpbin/commit/cac34423d99d1228f426be903da53bafca5f50e7))
|
||||||
|
* **frontend:user:** improve UX; move user settings to settings tab ([5052bbd](https://github.com/whoswhip/Sharpbin/commit/5052bbdb135dc2df08db94874de5bf2bf738364c))
|
||||||
|
* **frontend:** improve user page UX ([ff706d8](https://github.com/whoswhip/Sharpbin/commit/ff706d877742317cb8f4ccf72ba5f0791a6d2b88))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## [3.0.3](https://github.com/whoswhip/Sharpbin/compare/v3.0.2...v3.0.3) (2026-02-10)
|
## [3.0.3](https://github.com/whoswhip/Sharpbin/compare/v3.0.2...v3.0.3) (2026-02-10)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -26,15 +26,45 @@ The easiest way to run SharpbinV3 is using Docker Compose.
|
|||||||
git clone https://github.com/whoswhip/Sharpbin.git
|
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
|
```bash
|
||||||
docker-compose up -d
|
docker compose up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
### Configuration
|
### 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:
|
> When configuring via `appsettings.json` instead of for example `ConnectionStrings__DefaultConnection` it would be:
|
||||||
|
|
||||||
@@ -46,26 +76,32 @@ You can configure Sharpbin using environment variables or `appsettings.json`. Wh
|
|||||||
|
|
||||||
#### Backend (SharpbinV3.Server)
|
#### Backend (SharpbinV3.Server)
|
||||||
|
|
||||||
|
- `Domain`: The domain your instance of Sharpbin will be hosted at (e.g., example.com)
|
||||||
|
- `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`).
|
- `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_SecretKey`: Your Cloudflare Turnstile secret key.
|
||||||
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
|
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
|
||||||
- `AuthSettings__Registration_Enabled`: Set to `true` by default, enables/disables registration.
|
- `AuthSettings__Registration_Enabled`:**true**: Enables/disables registration.
|
||||||
- `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use.
|
- `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use.
|
||||||
- `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions.
|
- `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions.
|
||||||
|
- `AuthSettings__API_Key_HMAC_Secret`: Recommended to securely hash API keys, but is not required.
|
||||||
- `PasteSettings__MaxTitleLength`: Max title length in characters.
|
- `PasteSettings__MaxTitleLength`: Max title length in characters.
|
||||||
- `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB)
|
- `PasteSettings__MaxPasteSizeInBytes`:**1_048_576** (1MB): Max Paste Size set in bytes.
|
||||||
- `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default.
|
- `PasteSettings__EnablePasteCompression`:**true**: Enables/Disables server-side paste compression.
|
||||||
- `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default.
|
- `PasteSettings__RequiresVerification`:**true**: Enables/Disables CAPTCHA verification when creating pastes.
|
||||||
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers
|
- `PasteSettings__View_HMAC_Secret`: A required random secret of 32–128 characters used to hash viewer identifiers.
|
||||||
- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
|
- `PasteSettings__View_Internal_API_Key`: A shared key of 32–128 characters used to authorize view recording. Compose passes it to both services.
|
||||||
- `ASPNETCORE_ENVIRONMENT`: Set to `Production` or `Development`.
|
|
||||||
|
|
||||||
#### Frontend (SharpbinV3.Client)
|
#### Frontend (SharpbinV3.Client)
|
||||||
|
|
||||||
- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`).
|
- `VITE_API_URL`: The 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.
|
||||||
- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`)
|
- `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).
|
||||||
- `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_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.
|
The frontend will be accessible at http://localhost:5173.
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ node_modules
|
|||||||
.wrangler
|
.wrangler
|
||||||
/.svelte-kit
|
/.svelte-kit
|
||||||
/build
|
/build
|
||||||
|
.cache
|
||||||
|
|
||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|||||||
@@ -1,14 +1,26 @@
|
|||||||
# syntax=docker/dockerfile:1
|
# 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
|
WORKDIR /app
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm ci
|
RUN npm ci
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM node:20-alpine as runner
|
FROM node:24-alpine as runner
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=build /app .
|
ENV NODE_ENV=production
|
||||||
RUN apk add --no-cache wget
|
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
|
EXPOSE 5173
|
||||||
CMD ["npm", "run", "preview", "--", "--host", "0.0.0.0", "--port", "5173"]
|
USER node
|
||||||
|
CMD ["node", "build"]
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ This is the SvelteKit frontend for SharpbinV3.
|
|||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
- Node.js (v20 or newer recommended)
|
- Node.js 24
|
||||||
- npm
|
- npm
|
||||||
|
|
||||||
### Installation
|
### Installation
|
||||||
@@ -19,11 +19,12 @@ npm install
|
|||||||
|
|
||||||
### Environment Configuration
|
### 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_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 allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`)
|
- `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.
|
||||||
- `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.
|
|
||||||
|
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
|
### Running in Development
|
||||||
|
|
||||||
@@ -35,6 +36,25 @@ npm run dev
|
|||||||
|
|
||||||
The frontend will be available at http://localhost:5173.
|
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
|
## Script Reference
|
||||||
|
|
||||||
- `npm run dev`: Start the Vite development server.
|
- `npm run dev`: Start the Vite development server.
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import svelte from 'eslint-plugin-svelte';
|
|||||||
import { defineConfig } from 'eslint/config';
|
import { defineConfig } from 'eslint/config';
|
||||||
import globals from 'globals';
|
import globals from 'globals';
|
||||||
import ts from 'typescript-eslint';
|
import ts from 'typescript-eslint';
|
||||||
import svelteConfig from './svelte.config.js';
|
|
||||||
|
|
||||||
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
|
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
|
||||||
|
|
||||||
@@ -33,8 +32,7 @@ export default defineConfig(
|
|||||||
parserOptions: {
|
parserOptions: {
|
||||||
projectService: true,
|
projectService: true,
|
||||||
extraFileExtensions: ['.svelte'],
|
extraFileExtensions: ['.svelte'],
|
||||||
parser: ts.parser,
|
parser: ts.parser
|
||||||
svelteConfig
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+2141
-1286
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "sharpbinv3.client",
|
"name": "sharpbinv3.client",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "3.0.3",
|
"version": "3.0.5",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite dev",
|
"dev": "vite dev",
|
||||||
@@ -17,14 +17,16 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/compat": "^1.4.0",
|
"@eslint/compat": "^1.4.0",
|
||||||
"@eslint/js": "^9.39.1",
|
"@eslint/js": "^9.39.1",
|
||||||
"@sveltejs/adapter-auto": "^7.0.0",
|
"@sveltejs/adapter-auto": "^8.0.0",
|
||||||
"@sveltejs/kit": "^2.50.0",
|
"@sveltejs/kit": "^3.0.1",
|
||||||
"@sveltejs/vite-plugin-svelte": "^6.2.1",
|
"@sveltejs/vite-plugin-svelte": "^7.1.2",
|
||||||
"@tailwindcss/vite": "^4.1.17",
|
"@tailwindcss/vite": "^4.3.1",
|
||||||
|
"@types/better-sqlite3": "^7.6.13",
|
||||||
"@types/jsdom": "^27.0.0",
|
"@types/jsdom": "^27.0.0",
|
||||||
"@types/node": "^22",
|
"@types/node": "^22",
|
||||||
"@types/papaparse": "^5.5.2",
|
"@types/papaparse": "^5.5.2",
|
||||||
"@types/qrcode": "^1.5.6",
|
"@types/qrcode": "^1.5.6",
|
||||||
|
"@types/sharp": "^0.31.1",
|
||||||
"conventional-changelog": "^7.1.1",
|
"conventional-changelog": "^7.1.1",
|
||||||
"conventional-changelog-angular": "^8.1.0",
|
"conventional-changelog-angular": "^8.1.0",
|
||||||
"eslint": "^9.39.1",
|
"eslint": "^9.39.1",
|
||||||
@@ -34,23 +36,34 @@
|
|||||||
"prettier": "^3.7.4",
|
"prettier": "^3.7.4",
|
||||||
"prettier-plugin-svelte": "^3.4.0",
|
"prettier-plugin-svelte": "^3.4.0",
|
||||||
"prettier-plugin-tailwindcss": "^0.7.2",
|
"prettier-plugin-tailwindcss": "^0.7.2",
|
||||||
"svelte": "^5.48.3",
|
"svelte": "^5.55.7",
|
||||||
"svelte-check": "^4.3.4",
|
"svelte-check": "^4.3.4",
|
||||||
"tailwind-scrollbar": "^4.0.2",
|
"tailwind-scrollbar": "^4.0.2",
|
||||||
"tailwindcss": "^4.1.17",
|
"tailwindcss": "^4.1.17",
|
||||||
"typescript": "^5.9.3",
|
"typescript": "^6.0.3",
|
||||||
"typescript-eslint": "^8.48.1",
|
"typescript-eslint": "^8.71.2",
|
||||||
"vite": "^7.2.6"
|
"vite": "^8.0.16"
|
||||||
|
},
|
||||||
|
"imports": {
|
||||||
|
"#lib": "./src/lib/index.ts",
|
||||||
|
"#lib/*": "./src/lib/*"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@fontsource/inter": "^5.2.8",
|
||||||
|
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||||
"@lucide/svelte": "^0.562.0",
|
"@lucide/svelte": "^0.562.0",
|
||||||
"@sveltejs/adapter-node": "^5.4.0",
|
"@resvg/resvg-js": "^2.6.2",
|
||||||
"dompurify": "^3.3.1",
|
"@sveltejs/adapter-node": "^6.0.0",
|
||||||
|
"better-sqlite3": "^12.8.0",
|
||||||
|
"dompurify": "^3.4.16",
|
||||||
"hash-wasm": "^4.12.0",
|
"hash-wasm": "^4.12.0",
|
||||||
"highlight.js": "^11.8.0",
|
"highlight.js": "^11.8.0",
|
||||||
"jsdom": "^27.4.0",
|
"jsdom": "^27.4.0",
|
||||||
"marked": "^17.0.1",
|
"marked": "^17.0.1",
|
||||||
"papaparse": "^5.5.3",
|
"papaparse": "^5.5.3",
|
||||||
"qrcode": "^1.5.4"
|
"qrcode": "^1.5.4",
|
||||||
|
"satori": "^0.26.0",
|
||||||
|
"satori-html": "^0.3.2",
|
||||||
|
"sharp": "^0.35.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+1
@@ -27,6 +27,7 @@ declare global {
|
|||||||
| undefined;
|
| undefined;
|
||||||
var turnstileLoaded: (() => void) | undefined;
|
var turnstileLoaded: (() => void) | undefined;
|
||||||
declare const __APP_VERSION__: string;
|
declare const __APP_VERSION__: string;
|
||||||
|
declare const COMMIT_HASH: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export {};
|
export {};
|
||||||
|
|||||||
@@ -4,28 +4,41 @@
|
|||||||
label: string;
|
label: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export let options: Option[] = [];
|
interface Props {
|
||||||
export let value: string | number = '';
|
options?: Option[];
|
||||||
export let placeholder = 'Select...';
|
value?: string | number;
|
||||||
export let searchable = false;
|
placeholder?: string;
|
||||||
export let displayValue: (val: string | number) => string = (val) => {
|
searchable?: boolean;
|
||||||
return options.find((o) => o.value === val)?.label ?? String(val);
|
displayValue?: (val: string | number) => string;
|
||||||
};
|
variant?: string;
|
||||||
export let variant: string = '';
|
}
|
||||||
|
|
||||||
let isOpen = false;
|
let {
|
||||||
let searchQuery = '';
|
options = [],
|
||||||
let dropdownElement: HTMLDivElement;
|
value = $bindable(''),
|
||||||
let dropdownListElement: HTMLDivElement;
|
placeholder = 'Select...',
|
||||||
let dropdownMaxHeight = '12rem';
|
searchable = false,
|
||||||
|
displayValue = (val) => {
|
||||||
|
return options.find((o) => o.value === val)?.label ?? String(val);
|
||||||
|
},
|
||||||
|
variant = ''
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
$: filteredOptions = searchable
|
let isOpen = $state(false);
|
||||||
? options.filter(
|
let searchQuery = $state('');
|
||||||
(opt) =>
|
let dropdownElement = $state<HTMLDivElement | undefined>(undefined);
|
||||||
opt.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
let dropdownListElement = $state<HTMLDivElement | undefined>(undefined);
|
||||||
String(opt.value).toLowerCase().includes(searchQuery.toLowerCase())
|
let dropdownMaxHeight = $state('12rem');
|
||||||
)
|
|
||||||
: options;
|
let filteredOptions = $derived(
|
||||||
|
searchable
|
||||||
|
? options.filter(
|
||||||
|
(opt) =>
|
||||||
|
opt.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
String(opt.value).toLowerCase().includes(searchQuery.toLowerCase())
|
||||||
|
)
|
||||||
|
: options
|
||||||
|
);
|
||||||
|
|
||||||
function handleSelect(selectedValue: string | number) {
|
function handleSelect(selectedValue: string | number) {
|
||||||
value = selectedValue;
|
value = selectedValue;
|
||||||
@@ -64,12 +77,12 @@
|
|||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:window on:click={handleClickOutside} />
|
<svelte:window onclick={handleClickOutside} />
|
||||||
|
|
||||||
<div bind:this={dropdownElement} class="relative mb-2 w-full" class:dropdown-sm={variant === 'sm'}>
|
<div bind:this={dropdownElement} class="relative mb-2 w-full" class:dropdown-sm={variant === 'sm'}>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
on:click={toggleDropdown}
|
onclick={toggleDropdown}
|
||||||
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-left transition-colors hover:bg-neutral-700"
|
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-left transition-colors hover:bg-neutral-700"
|
||||||
class:dropdown-sm-btn={variant === 'sm'}
|
class:dropdown-sm-btn={variant === 'sm'}
|
||||||
>
|
>
|
||||||
@@ -91,7 +104,7 @@
|
|||||||
class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none"
|
class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none"
|
||||||
class:dropdown-sm-input={variant === 'sm'}
|
class:dropdown-sm-input={variant === 'sm'}
|
||||||
bind:value={searchQuery}
|
bind:value={searchQuery}
|
||||||
on:keydown={handleKeyDown}
|
onkeydown={handleKeyDown}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
@@ -102,7 +115,7 @@
|
|||||||
{#each filteredOptions as option (option.value)}
|
{#each filteredOptions as option (option.value)}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
on:click={() => handleSelect(option.value)}
|
onclick={() => handleSelect(option.value)}
|
||||||
class="w-full border-b border-neutral-700 px-3 py-2 text-left last:border-b-0 hover:bg-neutral-600"
|
class="w-full border-b border-neutral-700 px-3 py-2 text-left last:border-b-0 hover:bg-neutral-600"
|
||||||
class:bg-neutral-700={value === option.value}
|
class:bg-neutral-700={value === option.value}
|
||||||
class:dropdown-sm-option={variant === 'sm'}
|
class:dropdown-sm-option={variant === 'sm'}
|
||||||
|
|||||||
@@ -19,4 +19,13 @@
|
|||||||
>
|
>
|
||||||
<span class="mx-1">•</span>
|
<span class="mx-1">•</span>
|
||||||
v{__APP_VERSION__}
|
v{__APP_VERSION__}
|
||||||
|
<a
|
||||||
|
href="https://github.com/whoswhip/Sharpbin/commit/{COMMIT_HASH}"
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
class="text-neutral-400 underline hover:text-neutral-200"
|
||||||
|
>{(COMMIT_HASH?.length ?? 0) >= 7 && COMMIT_HASH !== 'unknown'
|
||||||
|
? `(${COMMIT_HASH.slice(0, 7)})`
|
||||||
|
: ''}</a
|
||||||
|
>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,50 +1,65 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import QRCode from 'qrcode';
|
import QRCode from 'qrcode';
|
||||||
import { getRefreshToken, getToken, setTokens } from '$lib/utils/auth';
|
import { getRefreshToken, getToken, setTokens } from '#lib/utils/auth';
|
||||||
import { parseTotpEnabled } from '$lib/utils/totp';
|
import { parseTotpEnabled } from '#lib/utils/totp';
|
||||||
import { tick } from 'svelte';
|
import { tick } from 'svelte';
|
||||||
import { extractError } from '$lib/utils/misc';
|
import { extractError } from '#lib/utils/misc';
|
||||||
|
import type { ModalItem, ModalMode } from '#lib/types/modal';
|
||||||
|
|
||||||
export let show = false;
|
interface Props {
|
||||||
export let mode:
|
show?: boolean;
|
||||||
| 'decrypt'
|
mode?: ModalMode;
|
||||||
| 'encrypt'
|
title?: string;
|
||||||
| 'confirm'
|
message?: string;
|
||||||
| 'prompt'
|
error?: string;
|
||||||
| 'multiselect'
|
placeholder?: string;
|
||||||
| 'totp'
|
inputType?: string;
|
||||||
| 'totpSetup'
|
inputMaxLength?: number | null;
|
||||||
| 'report' = 'decrypt';
|
items?: ModalItem[];
|
||||||
export let title = '';
|
initialValue?: unknown;
|
||||||
export let message = '';
|
totpActive?: boolean | null;
|
||||||
export let error = '';
|
reportTarget?: 'user' | 'paste' | null;
|
||||||
export let placeholder = '';
|
reportTargetId?: string | number | null;
|
||||||
export let inputType = 'text';
|
reportSiteKey?: string | null;
|
||||||
export let inputMaxLength: number | null = null;
|
onConfirm: (value: unknown) => void;
|
||||||
export let items: { label: string; value: unknown }[] = [];
|
onCancel: () => void;
|
||||||
export let initialValue: unknown = null;
|
confirmButtonText?: string;
|
||||||
export let totpActive: boolean | null = null;
|
}
|
||||||
export let reportTarget: 'user' | 'paste' | null = null;
|
|
||||||
export let reportTargetId: string | number | null = null;
|
|
||||||
export let reportSiteKey: string | null = null;
|
|
||||||
export let onConfirm: (value: unknown) => void;
|
|
||||||
export let onCancel: () => void;
|
|
||||||
export let confirmButtonText = '';
|
|
||||||
|
|
||||||
let inputValue: string | unknown[] | boolean = '';
|
let {
|
||||||
let totpSecret = '';
|
show = false,
|
||||||
let totpQr = '';
|
mode = 'decrypt',
|
||||||
let totpEnabled = false;
|
title = '',
|
||||||
let totpInitialized = false;
|
message = '',
|
||||||
let totpLoading = false;
|
error = $bindable(''),
|
||||||
let totpError = '';
|
placeholder = '',
|
||||||
let displayError = '';
|
inputType = 'text',
|
||||||
let reportTypes: string[] = [];
|
inputMaxLength = null,
|
||||||
let reportType = '';
|
items = [],
|
||||||
let reportInitialized = false;
|
initialValue = null,
|
||||||
let reportLoading = false;
|
totpActive = null,
|
||||||
let multiselectInitialized = false;
|
reportTarget = null,
|
||||||
let turnstileEl: HTMLDivElement | null = null;
|
reportTargetId = null,
|
||||||
|
reportSiteKey = null,
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
confirmButtonText = ''
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
let inputValue: string | unknown[] | boolean = $state('');
|
||||||
|
let totpSecret = $state('');
|
||||||
|
let totpQr = $state('');
|
||||||
|
let totpEnabled = $state(false);
|
||||||
|
let totpInitialized = $state(false);
|
||||||
|
let totpLoading = $state(false);
|
||||||
|
let totpError = $state('');
|
||||||
|
let displayError = $derived(error || totpError);
|
||||||
|
let reportTypes: string[] = $state([]);
|
||||||
|
let reportType = $state('');
|
||||||
|
let reportInitialized = $state(false);
|
||||||
|
let reportLoading = $state(false);
|
||||||
|
let multiselectInitialized = $state(false);
|
||||||
|
let turnstileEl: HTMLDivElement | null = $state(null);
|
||||||
let turnstileWidgetId: string | null = null;
|
let turnstileWidgetId: string | null = null;
|
||||||
|
|
||||||
const titleMap = {
|
const titleMap = {
|
||||||
@@ -63,34 +78,12 @@
|
|||||||
encrypt: 'Encrypt',
|
encrypt: 'Encrypt',
|
||||||
confirm: 'Confirm',
|
confirm: 'Confirm',
|
||||||
multiselect: 'Confirm',
|
multiselect: 'Confirm',
|
||||||
totpSetup: totpEnabled ? 'Disable' : 'Enable',
|
totpSetup: 'Enable',
|
||||||
totp: 'Verify',
|
totp: 'Verify',
|
||||||
report: 'Submit Report',
|
report: 'Submit Report',
|
||||||
prompt: 'Submit'
|
prompt: 'Submit'
|
||||||
};
|
};
|
||||||
|
|
||||||
$: displayError = error || totpError;
|
|
||||||
|
|
||||||
$: if (!show) resetModal();
|
|
||||||
|
|
||||||
$: if (show && mode === 'totpSetup' && !totpInitialized) {
|
|
||||||
totpInitialized = true;
|
|
||||||
if (totpActive !== null) {
|
|
||||||
totpEnabled = totpActive;
|
|
||||||
}
|
|
||||||
initializeTotp();
|
|
||||||
}
|
|
||||||
|
|
||||||
$: if (show && mode === 'report' && !reportInitialized) {
|
|
||||||
reportInitialized = true;
|
|
||||||
initializeReport();
|
|
||||||
}
|
|
||||||
|
|
||||||
$: if (show && mode === 'multiselect' && !multiselectInitialized) {
|
|
||||||
multiselectInitialized = true;
|
|
||||||
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
function resetModal() {
|
function resetModal() {
|
||||||
inputValue =
|
inputValue =
|
||||||
initialValue !== null
|
initialValue !== null
|
||||||
@@ -212,7 +205,8 @@
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleSubmit() {
|
async function handleSubmit(event: Event) {
|
||||||
|
event.preventDefault();
|
||||||
if (mode === 'report') {
|
if (mode === 'report') {
|
||||||
await submitReport();
|
await submitReport();
|
||||||
return;
|
return;
|
||||||
@@ -308,7 +302,8 @@
|
|||||||
body.VerificationToken = verification;
|
body.VerificationToken = verification;
|
||||||
}
|
}
|
||||||
const targetId = encodeURIComponent(String(reportTargetId));
|
const targetId = encodeURIComponent(String(reportTargetId));
|
||||||
const res = await fetch(`/api/${reportTarget}/${targetId}/report`, {
|
const reportPath = reportTarget === 'paste' ? 'pastes' : 'users';
|
||||||
|
const res = await fetch(`/api/report/${reportPath}/${targetId}/report`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
@@ -394,18 +389,45 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$: displayTitle = title || titleMap[mode];
|
$effect(() => {
|
||||||
|
if (!show) resetModal();
|
||||||
$: confirmLabel = confirmButtonText || confirmLabelMap[mode];
|
});
|
||||||
$: shouldShowInput =
|
$effect(() => {
|
||||||
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report';
|
if (show && mode === 'totpSetup' && !totpInitialized) {
|
||||||
|
totpInitialized = true;
|
||||||
|
if (totpActive !== null) {
|
||||||
|
totpEnabled = totpActive;
|
||||||
|
}
|
||||||
|
initializeTotp();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$effect(() => {
|
||||||
|
if (show && mode === 'report' && !reportInitialized) {
|
||||||
|
reportInitialized = true;
|
||||||
|
initializeReport();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$effect(() => {
|
||||||
|
if (show && mode === 'multiselect' && !multiselectInitialized) {
|
||||||
|
multiselectInitialized = true;
|
||||||
|
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let displayTitle = $derived(title || titleMap[mode]);
|
||||||
|
let confirmLabel = $derived(
|
||||||
|
confirmButtonText ||
|
||||||
|
(mode === 'totpSetup' ? (totpEnabled ? 'Disable' : 'Enable') : confirmLabelMap[mode])
|
||||||
|
);
|
||||||
|
let shouldShowInput = $derived(
|
||||||
|
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report'
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if show}
|
{#if show}
|
||||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
|
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-xs">
|
||||||
<form
|
<form
|
||||||
on:submit|preventDefault={handleSubmit}
|
onsubmit={handleSubmit}
|
||||||
class="w-full max-w-md rounded bg-neutral-900 p-6"
|
class="w-full max-w-md rounded border border-neutral-800 bg-neutral-900 p-6"
|
||||||
>
|
>
|
||||||
<h2 class="mb-4 text-xl font-semibold text-white">
|
<h2 class="mb-4 text-xl font-semibold text-white">
|
||||||
{displayTitle}
|
{displayTitle}
|
||||||
@@ -448,7 +470,7 @@
|
|||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
on:click={copySecret}
|
onclick={copySecret}
|
||||||
class="rounded bg-neutral-700 px-3 py-1 text-sm font-medium text-white transition-colors hover:bg-neutral-800"
|
class="rounded bg-neutral-700 px-3 py-1 text-sm font-medium text-white transition-colors hover:bg-neutral-800"
|
||||||
>
|
>
|
||||||
Copy
|
Copy
|
||||||
@@ -463,7 +485,7 @@
|
|||||||
maxlength="6"
|
maxlength="6"
|
||||||
inputmode="numeric"
|
inputmode="numeric"
|
||||||
pattern="[0-9]*"
|
pattern="[0-9]*"
|
||||||
on:input={onCodeInput}
|
oninput={onCodeInput}
|
||||||
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
|
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
|
||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
@@ -543,7 +565,7 @@
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
on:click={onCancel}
|
onclick={onCancel}
|
||||||
class="cursor-pointer rounded border border-neutral-700 px-4 py-2 text-white hover:bg-neutral-950"
|
class="cursor-pointer rounded border border-neutral-700 px-4 py-2 text-white hover:bg-neutral-950"
|
||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Modal from '$lib/components/Modal.svelte';
|
import Modal from '#lib/components/Modal.svelte';
|
||||||
import { cancelModal, confirmModal, modal } from '$lib/stores/modal';
|
import { cancelModal, confirmModal, modal } from '#lib/stores/modal';
|
||||||
|
|
||||||
$: state = $modal;
|
let state = $derived($modal);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '#lib/stores/user';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import { clearTokens } from '$lib/utils/auth';
|
import { clearTokens, hasRole } from '#lib/utils/auth';
|
||||||
import logo from '$lib/assets/favicon.svg';
|
import logo from '#lib/assets/favicon.svg';
|
||||||
import type { PageData } from '../../routes/$types';
|
import type { PageData } from '../../routes/$types';
|
||||||
import { slide } from 'svelte/transition';
|
import { slide } from 'svelte/transition';
|
||||||
import { Menu, X } from '@lucide/svelte';
|
import { Menu, X } from '@lucide/svelte';
|
||||||
@@ -15,9 +15,13 @@
|
|||||||
window.location.href = '/';
|
window.location.href = '/';
|
||||||
}
|
}
|
||||||
|
|
||||||
export let data: PageData;
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
let menuOpen = false;
|
let { data }: Props = $props();
|
||||||
|
|
||||||
|
let menuOpen = $state(false);
|
||||||
|
|
||||||
let currentPath = page.url.pathname;
|
let currentPath = page.url.pathname;
|
||||||
let returnParam =
|
let returnParam =
|
||||||
@@ -41,28 +45,40 @@
|
|||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="top-0 left-0 z-100 h-15 w-full bg-neutral-900" id="navbar">
|
<div
|
||||||
|
class="sticky top-0 left-0 z-100 h-15 w-full border-b border-neutral-800 bg-neutral-900 shadow-md"
|
||||||
|
id="navbar"
|
||||||
|
>
|
||||||
<div class="mx-auto hidden h-15 w-[95%] max-w-7xl items-center py-2 md:flex">
|
<div class="mx-auto hidden h-15 w-[95%] max-w-7xl items-center py-2 md:flex">
|
||||||
<div>
|
<div class="flex items-center gap-6">
|
||||||
<a href={resolve('/')} class="text-xl font-bold text-white hover:text-neutral-300">Sharpbin</a
|
<a href={resolve('/')} class="group flex items-center gap-2">
|
||||||
|
<img src={logo} alt="Sharpbin Logo" class="h-7 w-7 group-hover:opacity-80" />
|
||||||
|
<span class="text-xl font-bold text-white group-hover:text-neutral-300">Sharpbin</span>
|
||||||
|
</a>
|
||||||
|
<div class="h-5 w-px bg-neutral-700"></div>
|
||||||
|
<a
|
||||||
|
href={resolve('/recent')}
|
||||||
|
class="relative text-neutral-300 after:absolute after:-bottom-0.5 after:left-0 after:h-px after:w-0 after:bg-white after:transition-all hover:text-white hover:after:w-full"
|
||||||
|
>Recent Pastes</a
|
||||||
>
|
>
|
||||||
<a href={resolve('/recent')} class="ml-6 text-white hover:text-neutral-300">Recent Pastes</a>
|
|
||||||
</div>
|
</div>
|
||||||
{#if $user}
|
{#if $user}
|
||||||
<div class="ml-auto flex items-center space-x-4">
|
<div class="ml-auto flex items-center space-x-4">
|
||||||
{#if $user.roles.includes(1) || $user.roles.includes(255)}
|
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
|
||||||
<a
|
<a
|
||||||
href={resolve('/reports')}
|
href={resolve('/reports')}
|
||||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Reports</a
|
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||||
|
>Reports</a
|
||||||
>
|
>
|
||||||
{/if}
|
{/if}
|
||||||
<a
|
<a
|
||||||
href={resolve(`/user/${$user.username}`)}
|
href={resolve(`/user/${$user.username}`)}
|
||||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Profile</a
|
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||||
|
>Profile</a
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
on:click={logout}
|
onclick={logout}
|
||||||
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800"
|
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||||
>Logout</button
|
>Logout</button
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
@@ -70,13 +86,14 @@
|
|||||||
<div class="ml-auto flex items-center space-x-4">
|
<div class="ml-auto flex items-center space-x-4">
|
||||||
<a
|
<a
|
||||||
href={resolve(`/login${returnParam}`)}
|
href={resolve(`/login${returnParam}`)}
|
||||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Login</a
|
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||||
|
>Login</a
|
||||||
>
|
>
|
||||||
<!-- eslint-disable svelte/no-navigation-without-resolve -->
|
<!-- eslint-disable svelte/no-navigation-without-resolve -->
|
||||||
<a
|
<a
|
||||||
href={data.options?.registration_enabled ? resolve(`/register${returnParam}`) : '#'}
|
href={data.options?.registration_enabled ? resolve(`/register${returnParam}`) : '#'}
|
||||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800 {data.options
|
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600 {data
|
||||||
?.registration_enabled
|
.options?.registration_enabled
|
||||||
? ''
|
? ''
|
||||||
: 'cursor-not-allowed bg-neutral-800 text-neutral-500!'}">Register</a
|
: 'cursor-not-allowed bg-neutral-800 text-neutral-500!'}">Register</a
|
||||||
>
|
>
|
||||||
@@ -91,7 +108,7 @@
|
|||||||
</a>
|
</a>
|
||||||
<button
|
<button
|
||||||
class="ml-auto flex h-10 w-10 items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 hover:bg-neutral-700 focus:outline-none"
|
class="ml-auto flex h-10 w-10 items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 hover:bg-neutral-700 focus:outline-none"
|
||||||
on:click={() => (menuOpen = !menuOpen)}
|
onclick={() => (menuOpen = !menuOpen)}
|
||||||
aria-label="Toggle Menu"
|
aria-label="Toggle Menu"
|
||||||
aria-expanded={menuOpen}
|
aria-expanded={menuOpen}
|
||||||
>
|
>
|
||||||
@@ -113,23 +130,23 @@
|
|||||||
<a
|
<a
|
||||||
href={resolve('/recent')}
|
href={resolve('/recent')}
|
||||||
class="block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
class="block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||||
on:click={() => (menuOpen = false)}>Recent Pastes</a
|
onclick={() => (menuOpen = false)}>Recent Pastes</a
|
||||||
>
|
>
|
||||||
{#if $user}
|
{#if $user}
|
||||||
{#if $user.roles.includes(1) || $user.roles.includes(255)}
|
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
|
||||||
<a
|
<a
|
||||||
href={resolve('/reports')}
|
href={resolve('/reports')}
|
||||||
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||||
on:click={() => (menuOpen = false)}>Reports</a
|
onclick={() => (menuOpen = false)}>Reports</a
|
||||||
>
|
>
|
||||||
{/if}
|
{/if}
|
||||||
<a
|
<a
|
||||||
href={resolve(`/user/${$user.username}`)}
|
href={resolve(`/user/${$user.username}`)}
|
||||||
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||||
on:click={() => (menuOpen = false)}>Profile</a
|
onclick={() => (menuOpen = false)}>Profile</a
|
||||||
>
|
>
|
||||||
<button
|
<button
|
||||||
on:click={() => {
|
onclick={() => {
|
||||||
logout();
|
logout();
|
||||||
menuOpen = false;
|
menuOpen = false;
|
||||||
}}
|
}}
|
||||||
@@ -140,7 +157,7 @@
|
|||||||
<a
|
<a
|
||||||
href={resolve(`/login${returnParam}`)}
|
href={resolve(`/login${returnParam}`)}
|
||||||
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||||
on:click={() => (menuOpen = false)}>Login</a
|
onclick={() => (menuOpen = false)}>Login</a
|
||||||
>
|
>
|
||||||
<!-- eslint-disable svelte/no-navigation-without-resolve -->
|
<!-- eslint-disable svelte/no-navigation-without-resolve -->
|
||||||
<a
|
<a
|
||||||
@@ -149,7 +166,7 @@
|
|||||||
.options?.registration_enabled
|
.options?.registration_enabled
|
||||||
? ''
|
? ''
|
||||||
: 'cursor-not-allowed bg-neutral-900 text-neutral-500'}"
|
: 'cursor-not-allowed bg-neutral-900 text-neutral-500'}"
|
||||||
on:click={() => (menuOpen = false)}>Register</a
|
onclick={() => (menuOpen = false)}>Register</a
|
||||||
>
|
>
|
||||||
<!-- eslint-enable svelte/no-navigation-without-resolve -->
|
<!-- eslint-enable svelte/no-navigation-without-resolve -->
|
||||||
{/if}
|
{/if}
|
||||||
|
|||||||
@@ -1,11 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import {
|
import { tooltip, dateToRelativeString, formatNumber, formatBytes } from '#lib/utils/misc';
|
||||||
tooltip,
|
|
||||||
dateToRelativeString,
|
|
||||||
extractDateFromUUIDv7,
|
|
||||||
formatNumber,
|
|
||||||
formatBytes
|
|
||||||
} from '$lib/utils/misc';
|
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import {
|
import {
|
||||||
Eye,
|
Eye,
|
||||||
@@ -13,22 +7,29 @@
|
|||||||
Code,
|
Code,
|
||||||
User,
|
User,
|
||||||
History,
|
History,
|
||||||
Calendar,
|
CalendarDays,
|
||||||
Timer,
|
CalendarOff,
|
||||||
Lock,
|
Lock,
|
||||||
EyeOff,
|
EyeOff,
|
||||||
Globe
|
Globe,
|
||||||
|
HatGlasses,
|
||||||
|
ThumbsUp
|
||||||
} from '@lucide/svelte';
|
} from '@lucide/svelte';
|
||||||
import { syntaxes } from '$lib/consts';
|
import { syntaxes } from '#lib/consts';
|
||||||
import type { Paste } from '$lib/types/paste';
|
import type { Paste } from '#lib/types/paste';
|
||||||
|
|
||||||
export let paste: Paste;
|
interface Props {
|
||||||
export let now: Date;
|
paste: Paste;
|
||||||
export let showUser: boolean = true;
|
now: Date;
|
||||||
export let compact: boolean = false;
|
showUser?: boolean;
|
||||||
|
compact?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
const createdAt = extractDateFromUUIDv7(paste.uuid);
|
let { paste, now, showUser = true, compact = false }: Props = $props();
|
||||||
const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext'];
|
|
||||||
|
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>
|
</script>
|
||||||
|
|
||||||
{#if compact}
|
{#if compact}
|
||||||
@@ -45,14 +46,14 @@
|
|||||||
</span>
|
</span>
|
||||||
<div
|
<div
|
||||||
class="flex items-center gap-2 text-sm text-neutral-400"
|
class="flex items-center gap-2 text-sm text-neutral-400"
|
||||||
use:tooltip={`${createdAt?.toLocaleString()} • ${dateToRelativeString(createdAt ?? new Date(), true, false, now)}`}
|
use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
|
||||||
>
|
>
|
||||||
<Calendar class="h-4 w-4" />
|
<CalendarDays class="h-4 w-4" />
|
||||||
{#if createdAt}
|
{#if paste.createdAt}
|
||||||
{#if createdAt.getTime() > Date.now() - 86_400_000}
|
{#if paste.createdAt > Date.now() - 86_400_000}
|
||||||
Created {dateToRelativeString(createdAt, true, false, now)}
|
Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
|
||||||
{:else}
|
{:else}
|
||||||
Created on {createdAt.toLocaleDateString()}
|
{new Date(paste.createdAt).toLocaleDateString()}
|
||||||
{/if}
|
{/if}
|
||||||
{:else}
|
{:else}
|
||||||
Creation date unknown
|
Creation date unknown
|
||||||
@@ -64,7 +65,11 @@
|
|||||||
<div>
|
<div>
|
||||||
{#if showUser}
|
{#if showUser}
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<User class="h-4 w-4" />
|
{#if paste.author}
|
||||||
|
<User class="h-4 w-4" />
|
||||||
|
{:else}
|
||||||
|
<HatGlasses class="h-4 w-4" />
|
||||||
|
{/if}
|
||||||
{paste.author?.username ?? 'Anonymous'}
|
{paste.author?.username ?? 'Anonymous'}
|
||||||
</div>
|
</div>
|
||||||
{:else}
|
{:else}
|
||||||
@@ -81,19 +86,29 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||||
<Eye class="h-4 w-4" />
|
<span class="flex items-center gap-2">
|
||||||
|
<Eye class="h-4 w-4" />
|
||||||
{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}
|
{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="flex items-center gap-2"
|
||||||
|
use:tooltip={`${formatNumber(paste.likes)} likes, ${formatNumber(paste.dislikes)} dislikes`}
|
||||||
|
>
|
||||||
|
<ThumbsUp class="h-4 w-4" />
|
||||||
|
{netLikeText}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<div
|
<div
|
||||||
class="flex items-center gap-2"
|
class="flex items-center gap-2"
|
||||||
use:tooltip={paste.isCompressed ? `Compressed Size: ${formatBytes(paste.size)}` : ''}
|
use:tooltip={paste.isCompressed
|
||||||
|
? `Compressed Size: ${formatBytes(paste.storedSize)}`
|
||||||
|
: ''}
|
||||||
>
|
>
|
||||||
<FileBox class="h-4 w-4" />
|
<FileBox class="h-4 w-4" />
|
||||||
{formatBytes(paste.trueSize)}
|
{formatBytes(paste.originalSize)}
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<Code class="h-4 w-4" />
|
<Code class="h-4 w-4" />
|
||||||
@@ -117,28 +132,34 @@
|
|||||||
<div>
|
<div>
|
||||||
<div
|
<div
|
||||||
class="flex items-center gap-2 text-sm text-neutral-400"
|
class="flex items-center gap-2 text-sm text-neutral-400"
|
||||||
use:tooltip={`${createdAt?.toLocaleString()} • ${dateToRelativeString(createdAt ?? new Date(), true, false, now)}`}
|
use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
|
||||||
>
|
>
|
||||||
<Calendar class="h-4 w-4" />
|
<CalendarDays class="h-4 w-4" />
|
||||||
<span>
|
<span>
|
||||||
{#if createdAt}
|
{#if paste.createdAt}
|
||||||
{#if createdAt.getTime() > Date.now() - 86_400_000}
|
{#if paste.createdAt > Date.now() - 86_400_000}
|
||||||
Created {dateToRelativeString(createdAt, true, false, now)}
|
Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
|
||||||
{:else}
|
{:else}
|
||||||
Created on {createdAt.toLocaleDateString()}
|
Created on {new Date(paste.createdAt).toLocaleDateString()}
|
||||||
{/if}
|
{/if}
|
||||||
{:else}
|
{:else}
|
||||||
Creation date unknown
|
Creation date unknown
|
||||||
{/if}
|
{/if}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{#if paste.editedAt}
|
{#if paste.editedAt && paste.editedAt != 0}
|
||||||
<div
|
<div
|
||||||
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
|
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
|
||||||
use:tooltip={new Date(paste.editedAt).toLocaleString()}
|
use:tooltip={new Date(paste.editedAt).toLocaleString()}
|
||||||
>
|
>
|
||||||
<History class="h-4 w-4" />
|
<History class="h-4 w-4" />
|
||||||
<span>Edited {dateToRelativeString(new Date(paste.editedAt), true, false, now)}</span>
|
<span>
|
||||||
|
{#if paste.editedAt > Date.now() - 86_400_000}
|
||||||
|
Edited {dateToRelativeString(new Date(paste.editedAt), true, false, now)}
|
||||||
|
{:else}
|
||||||
|
Edited on {new Date(paste.editedAt).toLocaleDateString()}
|
||||||
|
{/if}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
{#if paste.expiresAt > 0}
|
{#if paste.expiresAt > 0}
|
||||||
@@ -146,7 +167,7 @@
|
|||||||
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
|
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
|
||||||
use:tooltip={new Date(paste.expiresAt).toLocaleString()}
|
use:tooltip={new Date(paste.expiresAt).toLocaleString()}
|
||||||
>
|
>
|
||||||
<Timer class="h-4 w-4" />
|
<CalendarOff class="h-4 w-4" />
|
||||||
<span>
|
<span>
|
||||||
{paste.expiresAt > 0 && paste.expiresAt < Date.now()
|
{paste.expiresAt > 0 && paste.expiresAt < Date.now()
|
||||||
? `Expired ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`
|
? `Expired ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`
|
||||||
@@ -156,24 +177,37 @@
|
|||||||
{/if}
|
{/if}
|
||||||
{#if showUser}
|
{#if showUser}
|
||||||
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
|
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
|
||||||
<User class="h-4 w-4" />
|
{#if paste.author}
|
||||||
|
<User class="h-4 w-4" />
|
||||||
|
{:else}
|
||||||
|
<HatGlasses class="h-4 w-4" />
|
||||||
|
{/if}
|
||||||
<span>{paste.author?.username ?? 'Anonymous'}</span>
|
<span>{paste.author?.username ?? 'Anonymous'}</span>
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<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 text-sm text-neutral-400">
|
<div class="flex items-center gap-2">
|
||||||
<Eye class="h-4 w-4" />
|
<Eye class="h-4 w-4" />
|
||||||
<span>{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}</span>
|
<span>{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}</span>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
|
class="flex items-center gap-2"
|
||||||
use:tooltip={paste.isCompressed ? `Compressed Size: ${formatBytes(paste.size)}` : ''}
|
use:tooltip={`${formatNumber(paste.likes)} likes, ${formatNumber(paste.dislikes)} dislikes`}
|
||||||
|
>
|
||||||
|
<ThumbsUp class="h-4 w-4" />
|
||||||
|
<span>{netLikeText}</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="flex items-center gap-2"
|
||||||
|
use:tooltip={paste.isCompressed
|
||||||
|
? `Compressed Size: ${formatBytes(paste.storedSize)}`
|
||||||
|
: ''}
|
||||||
>
|
>
|
||||||
<FileBox class="h-4 w-4" />
|
<FileBox class="h-4 w-4" />
|
||||||
<span>{formatBytes(paste.trueSize)}</span>
|
<span>{formatBytes(paste.originalSize)}</span>
|
||||||
</div>
|
</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" />
|
<Code class="h-4 w-4" />
|
||||||
<span>{syntax.name}</span>
|
<span>{syntax.name}</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { CommentReaction, CommentTreeNode } from '#lib/types/comment';
|
||||||
|
import { dateToRelativeString, tooltip } from '#lib/utils/misc';
|
||||||
|
import { parseCommentMarkdown } from '#lib/utils/markdown';
|
||||||
|
import { escapeHtml } from '#lib/utils/html';
|
||||||
|
import { user } from '#lib/stores/user';
|
||||||
|
import PasteCommentItem from '#lib/components/PasteCommentItem.svelte';
|
||||||
|
import { ThumbsUp, ThumbsDown, Trash2, Shredder, Reply, Quote } from '@lucide/svelte';
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import RichTextEditor from './RichTextEditor.svelte';
|
||||||
|
import { hasRole, roles } from '#lib/utils/auth';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
node: CommentTreeNode;
|
||||||
|
depth?: number;
|
||||||
|
now: Date;
|
||||||
|
reactingIds: Record<number, boolean>;
|
||||||
|
onReact: (commentId: number, target: 1 | 2, current: CommentReaction) => Promise<void>;
|
||||||
|
onReply: (parentCommentID: number, content: string) => Promise<boolean>;
|
||||||
|
deleteCommentAction: (commentId: number, hardDelete?: boolean) => Promise<boolean>;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
node,
|
||||||
|
depth = 1,
|
||||||
|
now,
|
||||||
|
reactingIds,
|
||||||
|
onReact,
|
||||||
|
onReply,
|
||||||
|
deleteCommentAction
|
||||||
|
}: Props = $props();
|
||||||
|
let deleting = $state(false);
|
||||||
|
|
||||||
|
const maxCommentLength = 320;
|
||||||
|
let expanded = $state(false);
|
||||||
|
let showDeepReplies = $state(false);
|
||||||
|
let replyOpen = $state(false);
|
||||||
|
let replyText = $state('');
|
||||||
|
let replySubmitting = $state(false);
|
||||||
|
let replyError = $state('');
|
||||||
|
let replyEditor = $state<{ focus: () => void } | undefined>(undefined);
|
||||||
|
|
||||||
|
let commentText = $derived(node.content ?? '*[Deleted comment]*');
|
||||||
|
let isLongComment = $derived(commentText.length > maxCommentLength);
|
||||||
|
let isDeleted = $derived(node.content === null);
|
||||||
|
let parsedHtml = $derived(
|
||||||
|
isDeleted ? escapeHtml(commentText) : parseCommentMarkdown(commentText)
|
||||||
|
);
|
||||||
|
let authorDisplay = $derived(
|
||||||
|
node.author
|
||||||
|
? (node.author.displayName?.length || 0) > 0
|
||||||
|
? node.author.displayName
|
||||||
|
: node.author.username
|
||||||
|
: 'Deleted User'
|
||||||
|
);
|
||||||
|
|
||||||
|
async function submitReply() {
|
||||||
|
replyError = '';
|
||||||
|
if (!$user) {
|
||||||
|
replyError = 'You must be signed in to reply.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!replyText.trim()) {
|
||||||
|
replyError = 'Reply cannot be empty.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
replySubmitting = true;
|
||||||
|
const ok = await onReply(node.id, replyText);
|
||||||
|
replySubmitting = false;
|
||||||
|
if (ok) {
|
||||||
|
replyText = '';
|
||||||
|
replyError = '';
|
||||||
|
replyOpen = false;
|
||||||
|
} else {
|
||||||
|
replyError = 'Failed to post reply.';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openReply(initialText: string) {
|
||||||
|
replyOpen = true;
|
||||||
|
replyError = '';
|
||||||
|
replyText = initialText;
|
||||||
|
queueMicrotask(() => {
|
||||||
|
replyEditor?.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(hardDelete = false) {
|
||||||
|
if (deleting) return;
|
||||||
|
deleting = true;
|
||||||
|
await deleteCommentAction(node.id, hardDelete);
|
||||||
|
deleting = false;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div class="rounded border border-transparent p-3">
|
||||||
|
<div class="mb-2 flex items-center justify-between gap-3 text-xs text-neutral-400">
|
||||||
|
<div class="flex min-w-0 items-center gap-2 text-sm">
|
||||||
|
{#if node.author}
|
||||||
|
{#if node.author.isBanned}
|
||||||
|
<span class="text-red-500">BANNED</span>
|
||||||
|
{/if}
|
||||||
|
<a
|
||||||
|
href={resolve(`/user/${node.author?.username}`)}
|
||||||
|
class="flex items-center gap-2 underline"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="truncate font-semibold text-neutral-200 {node.author.isBanned
|
||||||
|
? 'line-through decoration-red-500 decoration-2'
|
||||||
|
: ''}">{authorDisplay}</span
|
||||||
|
>
|
||||||
|
</a>
|
||||||
|
{/if}
|
||||||
|
{#if node.updatedAt}
|
||||||
|
<span
|
||||||
|
class="text-xs text-neutral-400"
|
||||||
|
use:tooltip={`Edited on ${new Date(node.updatedAt * 1000).toLocaleString()} • ${dateToRelativeString(new Date(node.updatedAt * 1000), true, true, now, 3)}`}
|
||||||
|
>edited</span
|
||||||
|
>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
class="shrink-0"
|
||||||
|
use:tooltip={`${new Date(node.createdAt * 1000).toLocaleString()} • ${dateToRelativeString(new Date(node.createdAt * 1000), true, true, now, 3)}`}
|
||||||
|
>{dateToRelativeString(new Date(node.createdAt * 1000), true, false, now, 2)}</span
|
||||||
|
>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="text-sm leading-relaxed text-neutral-200">
|
||||||
|
<div class="wrap-break-word" class:italic={isDeleted} class:text-neutral-500={isDeleted}>
|
||||||
|
{#if expanded || !isLongComment}
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
{@html parsedHtml}
|
||||||
|
{:else}
|
||||||
|
<div class="line-clamp-3">
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
{@html parsedHtml}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{#if isLongComment}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="mt-2 text-xs text-neutral-400 hover:text-neutral-200"
|
||||||
|
onclick={() => {
|
||||||
|
expanded = !expanded;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{expanded ? 'Show less' : 'Show more'}
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-3 flex flex-wrap items-center gap-1.5">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-7 min-w-10 items-center justify-center gap-1 rounded px-2 text-xs {node.userReaction !==
|
||||||
|
1
|
||||||
|
? 'text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600'
|
||||||
|
: 'bg-green-950 text-green-200 hover:bg-green-900 active:bg-green-800'} disabled:cursor-not-allowed disabled:hover:bg-transparent"
|
||||||
|
class:border-green-700={node.userReaction === 1}
|
||||||
|
onclick={() => onReact(node.id, 1, node.userReaction)}
|
||||||
|
disabled={reactingIds[node.id] || !$user}
|
||||||
|
aria-label="Like comment"
|
||||||
|
title="Like"
|
||||||
|
>
|
||||||
|
<ThumbsUp class="h-3.5 w-3.5" />
|
||||||
|
{node.likes}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-7 min-w-10 items-center justify-center gap-1 rounded px-2 text-xs {node.userReaction !==
|
||||||
|
2
|
||||||
|
? 'text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600'
|
||||||
|
: 'bg-red-950 text-red-200 hover:bg-red-900 active:bg-red-800'} disabled:cursor-not-allowed disabled:hover:bg-transparent"
|
||||||
|
class:border-red-700={node.userReaction === 2}
|
||||||
|
onclick={() => onReact(node.id, 2, node.userReaction)}
|
||||||
|
disabled={reactingIds[node.id] || !$user}
|
||||||
|
aria-label="Dislike comment"
|
||||||
|
title="Dislike"
|
||||||
|
>
|
||||||
|
<ThumbsDown class="h-3.5 w-3.5" />
|
||||||
|
{node.dislikes}
|
||||||
|
</button>
|
||||||
|
{#if $user}
|
||||||
|
{#if !replyOpen}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-7 items-center gap-1 rounded px-2 text-xs text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600"
|
||||||
|
onclick={() => {
|
||||||
|
openReply(node.content ? `> ${node.content.replace(/\n/g, '\n> ')}\n\n` : '');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Quote class="h-3.5 w-3.5" />
|
||||||
|
Quote
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-7 items-center gap-1 rounded px-2 text-xs text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600"
|
||||||
|
onclick={() => {
|
||||||
|
if (replyOpen) {
|
||||||
|
replyOpen = false;
|
||||||
|
replyError = '';
|
||||||
|
replyText = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
openReply('');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Reply class="h-3.5 w-3.5" />
|
||||||
|
{replyOpen ? 'Cancel' : 'Reply'}
|
||||||
|
</button>
|
||||||
|
{#if node.author?.uuid === $user.uuid || hasRole($user.roles, 4) || hasRole($user.roles, 2)}
|
||||||
|
<div class="ml-auto flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-7 w-7 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600"
|
||||||
|
onclick={() => handleDelete(false)}
|
||||||
|
disabled={deleting}
|
||||||
|
aria-label="Delete comment"
|
||||||
|
title="Delete"
|
||||||
|
>
|
||||||
|
<Trash2 class="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
{#if hasRole($user.roles, roles.Moderator) || hasRole($user.roles, roles.Admin)}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-7 w-7 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 active:bg-neutral-600"
|
||||||
|
onclick={() => handleDelete(true)}
|
||||||
|
disabled={deleting}
|
||||||
|
aria-label="Hard delete comment"
|
||||||
|
title="Hard delete"
|
||||||
|
>
|
||||||
|
<Shredder class="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if replyOpen}
|
||||||
|
<RichTextEditor
|
||||||
|
class="mt-3"
|
||||||
|
bind:this={replyEditor}
|
||||||
|
bind:value={replyText}
|
||||||
|
placeholder="Write a reply..."
|
||||||
|
onSubmit={submitReply}
|
||||||
|
disabled={replySubmitting}
|
||||||
|
submitting={replySubmitting}
|
||||||
|
submitLabel="Reply"
|
||||||
|
submittingLabel="Replying..."
|
||||||
|
compact
|
||||||
|
/>
|
||||||
|
{#if replyError}
|
||||||
|
<p class="mt-2 text-xs text-red-400">{replyError}</p>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if node.children.length > 0}
|
||||||
|
<div class="mt-3 border-l border-neutral-700 pl-3">
|
||||||
|
{#if depth >= 3 && !showDeepReplies}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded border border-neutral-700 px-2 py-1 text-xs text-neutral-300 hover:text-neutral-100"
|
||||||
|
onclick={() => {
|
||||||
|
showDeepReplies = true;
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Show {node.children.length} more repl{node.children.length === 1 ? 'y' : 'ies'}
|
||||||
|
</button>
|
||||||
|
{:else}
|
||||||
|
<div class="space-y-3">
|
||||||
|
{#each node.children as child (child.id)}
|
||||||
|
<PasteCommentItem
|
||||||
|
node={child}
|
||||||
|
depth={depth + 1}
|
||||||
|
{now}
|
||||||
|
{reactingIds}
|
||||||
|
{onReact}
|
||||||
|
{onReply}
|
||||||
|
{deleteCommentAction}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import { getToken } from '#lib/utils/auth';
|
||||||
|
import { user } from '#lib/stores/user';
|
||||||
|
import type {
|
||||||
|
CommentReaction,
|
||||||
|
CommentReactionResult,
|
||||||
|
PasteComment,
|
||||||
|
CommentTreeNode
|
||||||
|
} from '#lib/types/comment';
|
||||||
|
import PasteCommentItem from '#lib/components/PasteCommentItem.svelte';
|
||||||
|
import { SvelteMap } from 'svelte/reactivity';
|
||||||
|
import RichTextEditor from './RichTextEditor.svelte';
|
||||||
|
import { openModal } from '#lib/stores/modal';
|
||||||
|
import { RefreshCw } from '@lucide/svelte';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
pasteId: string;
|
||||||
|
initialComments?: PasteComment[];
|
||||||
|
}
|
||||||
|
|
||||||
|
let { pasteId, initialComments = [] }: Props = $props();
|
||||||
|
|
||||||
|
let comments = $derived.by(() => [...initialComments]);
|
||||||
|
let loading = $state(false);
|
||||||
|
let posting = $state(false);
|
||||||
|
let now = $state(new Date());
|
||||||
|
let interval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let errorMessage = $state('');
|
||||||
|
let newComment = $state('');
|
||||||
|
let reactingIds = $state<Record<number, boolean>>({});
|
||||||
|
|
||||||
|
const sortedComments = $derived(
|
||||||
|
[...comments].sort((a, b) => {
|
||||||
|
if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;
|
||||||
|
return a.id - b.id;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const threadedComments = $derived(buildCommentTree(sortedComments));
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
interval = setInterval(() => {
|
||||||
|
now = new Date();
|
||||||
|
}, 1000 * 30);
|
||||||
|
void refreshComments();
|
||||||
|
return () => {
|
||||||
|
if (interval) clearInterval(interval);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
function buildCommentTree(list: PasteComment[]): CommentTreeNode[] {
|
||||||
|
const nodes = new SvelteMap<number, CommentTreeNode>();
|
||||||
|
const roots: CommentTreeNode[] = [];
|
||||||
|
|
||||||
|
for (const comment of list) {
|
||||||
|
nodes.set(comment.id, {
|
||||||
|
...comment,
|
||||||
|
children: []
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const node of nodes.values()) {
|
||||||
|
if (node.parentCommentID && nodes.has(node.parentCommentID)) {
|
||||||
|
nodes.get(node.parentCommentID)?.children.push(node);
|
||||||
|
} else {
|
||||||
|
roots.push(node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return roots;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshComments() {
|
||||||
|
loading = true;
|
||||||
|
errorMessage = '';
|
||||||
|
const token = getToken();
|
||||||
|
const headers = new Headers();
|
||||||
|
if (token) headers.set('Authorization', `Bearer ${token}`);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/paste/${pasteId}/comments`, { headers });
|
||||||
|
if (!res.ok) {
|
||||||
|
errorMessage = 'Failed to load comments.';
|
||||||
|
loading = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const json = await res.json();
|
||||||
|
comments = Array.isArray(json?.comments) ? (json.comments as PasteComment[]) : [];
|
||||||
|
} catch {
|
||||||
|
errorMessage = 'Failed to load comments.';
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function postComment(content: string, parentCommentID: number | null): Promise<boolean> {
|
||||||
|
errorMessage = '';
|
||||||
|
const token = getToken();
|
||||||
|
if (!token) {
|
||||||
|
errorMessage = 'You must be signed in to comment.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const trimmed = content.trim();
|
||||||
|
if (!trimmed) {
|
||||||
|
errorMessage = 'Comment cannot be empty.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parentCommentID === null) posting = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/paste/${pasteId}/comments`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ content: trimmed, parentCommentID })
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({}));
|
||||||
|
errorMessage = err?.message || 'Failed to post comment.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const json = await res.json();
|
||||||
|
const created = json?.comment as PasteComment | undefined;
|
||||||
|
if (!created) {
|
||||||
|
errorMessage = 'Failed to post comment.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
comments = [...comments, created];
|
||||||
|
if (parentCommentID === null) newComment = '';
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
errorMessage = 'Failed to post comment.';
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
if (parentCommentID === null) posting = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function reactToComment(commentId: number, target: 1 | 2, current: CommentReaction) {
|
||||||
|
errorMessage = '';
|
||||||
|
const token = getToken();
|
||||||
|
if (!token) {
|
||||||
|
errorMessage = 'You must be signed in to react.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
reactingIds = { ...reactingIds, [commentId]: true };
|
||||||
|
const nextReaction: CommentReaction = current === target ? null : target;
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/paste/${pasteId}/comments/${commentId}/reaction`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ reaction: nextReaction })
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({}));
|
||||||
|
errorMessage = err?.message || 'Failed to apply reaction.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const json = await res.json();
|
||||||
|
const reaction = json?.reaction as CommentReactionResult | undefined;
|
||||||
|
if (!reaction) {
|
||||||
|
errorMessage = 'Failed to apply reaction.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
comments = comments.map((comment) =>
|
||||||
|
comment.id === commentId
|
||||||
|
? {
|
||||||
|
...comment,
|
||||||
|
likes: reaction.likes,
|
||||||
|
dislikes: reaction.dislikes,
|
||||||
|
userReaction: reaction.userReaction
|
||||||
|
}
|
||||||
|
: comment
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
errorMessage = 'Failed to apply reaction.';
|
||||||
|
} finally {
|
||||||
|
const next = { ...reactingIds };
|
||||||
|
delete next[commentId];
|
||||||
|
reactingIds = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submitTopLevelComment(content: string) {
|
||||||
|
await postComment(content, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteComment(commentId: number, hardDelete = false): Promise<boolean> {
|
||||||
|
errorMessage = '';
|
||||||
|
const token = getToken();
|
||||||
|
if (!token) {
|
||||||
|
errorMessage = 'You must be signed in to delete comments.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = hardDelete ? 'Hard delete comment?' : 'Delete comment?';
|
||||||
|
const message = hardDelete
|
||||||
|
? 'This permanently removes the comment from the thread. This cannot be undone.'
|
||||||
|
: 'This will remove the comment content while preserving the thread structure.';
|
||||||
|
const confirmButtonText = hardDelete ? 'Hard delete' : 'Delete';
|
||||||
|
const ok = await openModal<boolean>({
|
||||||
|
mode: 'confirm',
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
confirmButtonText,
|
||||||
|
cancelValue: false
|
||||||
|
});
|
||||||
|
if (!ok) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const query = hardDelete ? '?hardDelete=true' : '';
|
||||||
|
const res = await fetch(`/api/paste/${pasteId}/comments/${commentId}${query}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({}));
|
||||||
|
errorMessage = err?.message || 'Failed to delete comment.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
await refreshComments();
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
errorMessage = 'Failed to delete comment.';
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<section id="comments-section" class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4 mt-4">
|
||||||
|
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<h2 class="text-lg font-semibold text-neutral-100">{comments.length} Comments</h2>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 items-center gap-2 rounded px-2 text-xs text-neutral-300 hover:bg-neutral-800 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
|
||||||
|
onclick={refreshComments}
|
||||||
|
disabled={loading}
|
||||||
|
aria-label="Refresh comments"
|
||||||
|
>
|
||||||
|
<RefreshCw class="h-3.5 w-3.5 {loading ? 'animate-spin' : ''}" />
|
||||||
|
{loading ? 'Refreshing' : 'Refresh'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if $user}
|
||||||
|
<div class="mb-5">
|
||||||
|
<RichTextEditor
|
||||||
|
bind:value={newComment}
|
||||||
|
placeholder="Add a comment..."
|
||||||
|
onSubmit={submitTopLevelComment}
|
||||||
|
disabled={posting}
|
||||||
|
submitting={posting}
|
||||||
|
compact
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="mb-4 rounded border border-neutral-700 bg-neutral-800 p-3 text-sm text-neutral-300">
|
||||||
|
Sign in to post comments and reactions.
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if errorMessage}
|
||||||
|
<div class="mb-4 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
|
||||||
|
{errorMessage}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if loading && comments.length === 0}
|
||||||
|
<div class="rounded border border-neutral-700 bg-neutral-800 p-3 text-sm text-neutral-300">
|
||||||
|
Loading comments...
|
||||||
|
</div>
|
||||||
|
{:else if threadedComments.length === 0}
|
||||||
|
<div class="rounded border border-neutral-700 bg-neutral-800 p-3 text-sm text-neutral-300">
|
||||||
|
No comments yet.
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="space-y-2">
|
||||||
|
{#each threadedComments as node (node.id)}
|
||||||
|
<PasteCommentItem
|
||||||
|
{node}
|
||||||
|
{now}
|
||||||
|
{reactingIds}
|
||||||
|
onReact={reactToComment}
|
||||||
|
onReply={(parentCommentID, content) => postComment(content, parentCommentID)}
|
||||||
|
deleteCommentAction={deleteComment}
|
||||||
|
/>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</section>
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { Bold, Italic, CodeXml, Quote, Send, Eye, Pencil } from '@lucide/svelte';
|
||||||
|
import { parseCommentMarkdown } from '#lib/utils/markdown';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
class?: string;
|
||||||
|
value?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
submitting?: boolean;
|
||||||
|
compact?: boolean;
|
||||||
|
submitLabel?: string;
|
||||||
|
submittingLabel?: string;
|
||||||
|
onSubmit?: (value: string) => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
class: className = '',
|
||||||
|
value = $bindable(''),
|
||||||
|
placeholder = 'Write a comment...',
|
||||||
|
disabled = false,
|
||||||
|
submitting = false,
|
||||||
|
compact = false,
|
||||||
|
submitLabel = 'Post comment',
|
||||||
|
submittingLabel = 'Posting...',
|
||||||
|
onSubmit
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
let editor = $state<HTMLTextAreaElement | null>(null);
|
||||||
|
let mode = $state<'preview' | 'raw'>('raw');
|
||||||
|
|
||||||
|
const isDisabled = $derived(disabled || submitting);
|
||||||
|
const canSubmit = $derived(!isDisabled && value.trim().length > 0);
|
||||||
|
const parsedHtml = $derived(parseCommentMarkdown(value));
|
||||||
|
const editorMinHeight = $derived(compact ? 'min-h-20' : 'min-h-24');
|
||||||
|
|
||||||
|
function focusEditor() {
|
||||||
|
editor?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function focus() {
|
||||||
|
focusEditor();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleMode() {
|
||||||
|
mode = mode === 'preview' ? 'raw' : 'preview';
|
||||||
|
queueMicrotask(focusEditor);
|
||||||
|
}
|
||||||
|
|
||||||
|
function replaceSelection(replacement: string, selectionStart: number, selectionEnd: number) {
|
||||||
|
value = `${value.slice(0, selectionStart)}${replacement}${value.slice(selectionEnd)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function wrapSelection(prefix: string, suffix: string, fallback: string) {
|
||||||
|
if (!editor) {
|
||||||
|
value = `${value}${prefix}${fallback}${suffix}`;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectionStart = editor.selectionStart;
|
||||||
|
const selectionEnd = editor.selectionEnd;
|
||||||
|
const selectedText = value.slice(selectionStart, selectionEnd);
|
||||||
|
const inner = selectedText.length > 0 ? selectedText : fallback;
|
||||||
|
const replacement = `${prefix}${inner}${suffix}`;
|
||||||
|
const cursorStart = selectionStart + prefix.length;
|
||||||
|
const cursorEnd = cursorStart + inner.length;
|
||||||
|
|
||||||
|
replaceSelection(replacement, selectionStart, selectionEnd);
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (!editor) return;
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(cursorStart, cursorEnd);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function addBold() {
|
||||||
|
wrapSelection('**', '**', 'text');
|
||||||
|
}
|
||||||
|
|
||||||
|
function addItalic() {
|
||||||
|
wrapSelection('*', '*', 'text');
|
||||||
|
}
|
||||||
|
|
||||||
|
function addCode() {
|
||||||
|
wrapSelection('`', '`', 'code');
|
||||||
|
}
|
||||||
|
|
||||||
|
function addQuote() {
|
||||||
|
if (!editor) {
|
||||||
|
value = `${value}${value.length > 0 && !value.endsWith('\n') ? '\n' : ''}> `;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectionStart = editor.selectionStart;
|
||||||
|
const selectionEnd = editor.selectionEnd;
|
||||||
|
const selectedText = value.slice(selectionStart, selectionEnd);
|
||||||
|
|
||||||
|
if (selectedText.length === 0) {
|
||||||
|
const needsNewline = selectionStart > 0 && !value.slice(0, selectionStart).endsWith('\n');
|
||||||
|
const insert = `${needsNewline ? '\n' : ''}> `;
|
||||||
|
const nextCaret = selectionStart + insert.length;
|
||||||
|
replaceSelection(insert, selectionStart, selectionEnd);
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (!editor) return;
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(nextCaret, nextCaret);
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const quoted = selectedText
|
||||||
|
.split('\n')
|
||||||
|
.map((line) => (line.startsWith('> ') ? line : `> ${line}`))
|
||||||
|
.join('\n');
|
||||||
|
replaceSelection(quoted, selectionStart, selectionEnd);
|
||||||
|
queueMicrotask(() => {
|
||||||
|
if (!editor) return;
|
||||||
|
editor.focus();
|
||||||
|
editor.setSelectionRange(selectionStart, selectionStart + quoted.length);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit() {
|
||||||
|
if (!canSubmit || !onSubmit) return;
|
||||||
|
await onSubmit(value);
|
||||||
|
if (mode === 'raw') {
|
||||||
|
queueMicrotask(focusEditor);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleKeydown(event: KeyboardEvent) {
|
||||||
|
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
|
||||||
|
event.preventDefault();
|
||||||
|
void submit();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div
|
||||||
|
class="mb-4 overflow-hidden rounded border border-neutral-700 bg-neutral-900 shadow-sm {className}"
|
||||||
|
>
|
||||||
|
{#if mode === 'raw'}
|
||||||
|
<textarea
|
||||||
|
bind:this={editor}
|
||||||
|
class="{editorMinHeight} w-full resize-y border-0 bg-neutral-900 p-3 font-mono text-sm text-neutral-100 placeholder:text-neutral-400 focus:bg-neutral-800/60"
|
||||||
|
{placeholder}
|
||||||
|
maxlength={5000}
|
||||||
|
disabled={isDisabled}
|
||||||
|
bind:value
|
||||||
|
onkeydown={handleKeydown}
|
||||||
|
></textarea>
|
||||||
|
{:else}
|
||||||
|
<div class="{editorMinHeight} w-full overflow-auto bg-neutral-900 p-3 text-sm text-neutral-100">
|
||||||
|
{#if value.trim().length === 0}
|
||||||
|
<div class="text-neutral-400">{placeholder}</div>
|
||||||
|
{:else}
|
||||||
|
<div class="text-sm leading-relaxed wrap-break-word text-neutral-200">
|
||||||
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
|
{@html parsedHtml}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div
|
||||||
|
class="flex w-full flex-col gap-2 border-t border-neutral-700 bg-neutral-800 p-2 md:flex-row md:items-center md:gap-0"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 w-8 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
|
||||||
|
onclick={addBold}
|
||||||
|
disabled={isDisabled || mode === 'preview'}
|
||||||
|
aria-label="Bold"
|
||||||
|
title="Bold"
|
||||||
|
>
|
||||||
|
<Bold class="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 w-8 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
|
||||||
|
onclick={addItalic}
|
||||||
|
disabled={isDisabled || mode === 'preview'}
|
||||||
|
aria-label="Italic"
|
||||||
|
title="Italic"
|
||||||
|
>
|
||||||
|
<Italic class="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 w-8 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
|
||||||
|
onclick={addQuote}
|
||||||
|
disabled={isDisabled || mode === 'preview'}
|
||||||
|
aria-label="Quote"
|
||||||
|
title="Quote"
|
||||||
|
>
|
||||||
|
<Quote class="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 w-8 items-center justify-center rounded text-neutral-300 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500"
|
||||||
|
onclick={addCode}
|
||||||
|
disabled={isDisabled || mode === 'preview'}
|
||||||
|
aria-label="Inline code"
|
||||||
|
title="Inline code"
|
||||||
|
>
|
||||||
|
<CodeXml class="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col items-stretch gap-2 md:ml-auto md:flex-row md:items-center">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 w-full items-center justify-center gap-2 rounded px-3 text-sm text-neutral-200 hover:bg-neutral-700 hover:text-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-500 md:w-auto"
|
||||||
|
onclick={toggleMode}
|
||||||
|
disabled={isDisabled}
|
||||||
|
>
|
||||||
|
{#if mode === 'preview'}
|
||||||
|
<Pencil class="h-4 w-4" />
|
||||||
|
{:else}
|
||||||
|
<Eye class="h-4 w-4" />
|
||||||
|
{/if}
|
||||||
|
{mode === 'preview' ? 'Raw' : 'Preview'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex h-8 w-full items-center justify-center gap-2 rounded border border-neutral-600 bg-neutral-700 px-3 text-sm font-medium text-neutral-100 hover:border-neutral-500 hover:bg-neutral-600 disabled:cursor-not-allowed disabled:border-neutral-700 disabled:bg-neutral-800 disabled:text-neutral-500 md:w-auto"
|
||||||
|
onclick={submit}
|
||||||
|
disabled={!canSubmit}
|
||||||
|
>
|
||||||
|
<Send class="h-4 w-4" />
|
||||||
|
{submitting ? submittingLabel : submitLabel}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -41,6 +41,7 @@ export const syntaxes: Record<string, Syntax> = {
|
|||||||
crystal: { name: 'Crystal', extension: 'cr' },
|
crystal: { name: 'Crystal', extension: 'cr' },
|
||||||
csp: { name: 'CSP', extension: 'csp' },
|
csp: { name: 'CSP', extension: 'csp' },
|
||||||
css: { name: 'CSS', extension: 'css' },
|
css: { name: 'CSS', extension: 'css' },
|
||||||
|
csv: { name: 'CSV', extension: 'csv' },
|
||||||
d: { name: 'D', extension: 'd' },
|
d: { name: 'D', extension: 'd' },
|
||||||
dart: { name: 'Dart', extension: 'dart' },
|
dart: { name: 'Dart', extension: 'dart' },
|
||||||
deplhi: { name: 'Delphi', extension: 'pas' },
|
deplhi: { name: 'Delphi', extension: 'pas' },
|
||||||
@@ -192,7 +193,7 @@ export const syntaxes: Record<string, Syntax> = {
|
|||||||
|
|
||||||
export const expiresOptions = [
|
export const expiresOptions = [
|
||||||
{ value: 0, label: 'Never Expire' },
|
{ value: 0, label: 'Never Expire' },
|
||||||
{ value: 30000, label: 'Expire in 5 Minutes' },
|
{ value: 300000, label: 'Expire in 5 Minutes' },
|
||||||
{ value: 600000, label: 'Expire in 10 Minutes' },
|
{ value: 600000, label: 'Expire in 10 Minutes' },
|
||||||
{ value: 1800000, label: 'Expire in 30 Minutes' },
|
{ value: 1800000, label: 'Expire in 30 Minutes' },
|
||||||
{ value: 3600000, label: 'Expire in 1 Hour' },
|
{ value: 3600000, label: 'Expire in 1 Hour' },
|
||||||
@@ -210,13 +211,6 @@ export const expiresOptions = [
|
|||||||
{ value: 315360000000, label: 'Expire in 10 Years' }
|
{ value: 315360000000, label: 'Expire in 10 Years' }
|
||||||
];
|
];
|
||||||
|
|
||||||
export const roles = {
|
|
||||||
0: 'User',
|
|
||||||
1: 'Moderator',
|
|
||||||
255: 'Administrator',
|
|
||||||
403: 'Banned'
|
|
||||||
};
|
|
||||||
|
|
||||||
export const trustedDomains = [
|
export const trustedDomains = [
|
||||||
'img.youtube.com',
|
'img.youtube.com',
|
||||||
'i.ytimg.com',
|
'i.ytimg.com',
|
||||||
|
|||||||
@@ -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.
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { env } from 'node:process';
|
||||||
|
|
||||||
|
export const apiUrl = env.VITE_API_URL ?? 'http://localhost:5050';
|
||||||
|
export const viewInternalApiKey =
|
||||||
|
env.NODE_ENV === 'development'
|
||||||
|
? 'cccdd42d9f2f648493e402f1da7c855ea798ad510e6bb9ea712dd7bed838e58'
|
||||||
|
: (env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '');
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import CalendarDays from '@lucide/svelte/icons/calendar-days';
|
||||||
|
import CalendarOff from '@lucide/svelte/icons/calendar-off';
|
||||||
|
import Code from '@lucide/svelte/icons/code';
|
||||||
|
import Eye from '@lucide/svelte/icons/eye';
|
||||||
|
import EyeOff from '@lucide/svelte/icons/eye-off';
|
||||||
|
import FileBox from '@lucide/svelte/icons/file-box';
|
||||||
|
import Globe from '@lucide/svelte/icons/globe';
|
||||||
|
import Lock from '@lucide/svelte/icons/lock';
|
||||||
|
import User from '@lucide/svelte/icons/user';
|
||||||
|
import type { PasteEmbedProps } from './pasteEmbed';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
title: PasteEmbedProps['title'];
|
||||||
|
uploader: PasteEmbedProps['uploader'];
|
||||||
|
metadata: PasteEmbedProps['metadata'];
|
||||||
|
previewLines: PasteEmbedProps['previewLines'];
|
||||||
|
isEncrypted: PasteEmbedProps['isEncrypted'];
|
||||||
|
}
|
||||||
|
|
||||||
|
let { title, uploader, metadata, previewLines, isEncrypted }: Props = $props();
|
||||||
|
|
||||||
|
const metadataIcons = {
|
||||||
|
size: FileBox,
|
||||||
|
views: Eye,
|
||||||
|
created: CalendarDays,
|
||||||
|
expires: CalendarOff,
|
||||||
|
syntax: Code,
|
||||||
|
'visibility-0': Globe,
|
||||||
|
'visibility-1': EyeOff,
|
||||||
|
'visibility-2': Lock
|
||||||
|
} as const;
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!--
|
||||||
|
the following tailwindcss styles fail to parse, so they are applied inline:
|
||||||
|
neutral-950
|
||||||
|
gap-1.5
|
||||||
|
truncate
|
||||||
|
whitespace-nowrap
|
||||||
|
gap-2
|
||||||
|
gap-x-6.5
|
||||||
|
gap-y-3
|
||||||
|
gap-0.75
|
||||||
|
gap-3
|
||||||
|
whitespace-pre
|
||||||
|
-->
|
||||||
|
<!-- 630px by 1200px -->
|
||||||
|
<div class="flex h-157.5 w-300 p-6" style="font-family:'Inter'; background-color: #0a0a0a;">
|
||||||
|
<div
|
||||||
|
class="flex h-full w-full flex-col rounded-lg border-2 border-neutral-800 bg-neutral-900 p-4"
|
||||||
|
>
|
||||||
|
<div class="mb-3.5 flex flex-col items-center justify-center" style="gap: 6px;">
|
||||||
|
<div
|
||||||
|
class="max-w-250 text-[54px] leading-[1.1] font-bold text-white"
|
||||||
|
style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
|
||||||
|
>
|
||||||
|
{title}
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center text-[20px] text-neutral-400" style="gap: 8px;">
|
||||||
|
<User class="h-4.5 w-4.5 text-neutral-400" />
|
||||||
|
<div>{uploader}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="mb-3 flex flex-wrap items-center justify-center" style="gap: 12px;">
|
||||||
|
{#each metadata as item (item.value)}
|
||||||
|
{@const Icon = metadataIcons[item.icon]}
|
||||||
|
<div class="flex items-center text-[24px] leading-none text-neutral-400">
|
||||||
|
<Icon class="mr-2 h-5.5 w-5.5 text-neutral-400" />
|
||||||
|
<div class="text-[24px] text-neutral-400">{item.value}</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{#if isEncrypted}
|
||||||
|
<div
|
||||||
|
class="flex flex-1 items-center justify-center overflow-hidden rounded-lg bg-neutral-800"
|
||||||
|
>
|
||||||
|
<div class="flex flex-col items-center justify-center gap-3.5 p-6">
|
||||||
|
<Lock class="h-16 w-16 text-neutral-400" />
|
||||||
|
<div class="text-[36px] leading-[1.1] font-bold text-neutral-100">Encrypted Paste</div>
|
||||||
|
<div class="max-w-195 text-center text-[20px] leading-[1.3] text-neutral-400">
|
||||||
|
Preview is hidden for private encrypted pastes. Open the paste page and decrypt with the
|
||||||
|
password to view content.
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
|
<div class="relative flex flex-1 overflow-hidden rounded-lg bg-neutral-800">
|
||||||
|
<div class="flex w-full flex-col pt-3" style="gap: 3px;">
|
||||||
|
{#each previewLines as line, index (index)}
|
||||||
|
<!-- emulates whitespace for indentation since satori doesnt seem to render it properly -->
|
||||||
|
{@const leadingSpaceCount = line.length - line.trimStart().length}
|
||||||
|
{@const contentWithoutIndent = line.trimStart()}
|
||||||
|
<div class="flex items-center px-3.5" style="gap: 12px;">
|
||||||
|
<div
|
||||||
|
class="w-7.5 text-right text-[20px] text-neutral-500"
|
||||||
|
style="font-family:'JetBrains Mono'; white-space: pre;"
|
||||||
|
>
|
||||||
|
{String(index + 1).padStart(3, ' ')}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="flex items-center text-[20px] text-neutral-100"
|
||||||
|
style="font-family:'JetBrains Mono'; white-space: pre;"
|
||||||
|
>
|
||||||
|
<div style={`width: ${leadingSpaceCount * 12}px;`}></div>
|
||||||
|
<div>{contentWithoutIndent}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
class="absolute right-0 bottom-0 left-0"
|
||||||
|
style="height: 58px; background: linear-gradient(to bottom, rgba(38, 38, 38, 0), rgba(38, 38, 38, 1));"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
||||||
|
import { mkdirSync } from 'node:fs';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
|
import BetterSqlite3 from 'better-sqlite3';
|
||||||
|
import type { Database } from 'better-sqlite3';
|
||||||
|
|
||||||
|
const CACHE_DIR = '.cache/og-images';
|
||||||
|
const CACHE_DB_PATH = join(CACHE_DIR, 'index.db');
|
||||||
|
const CACHE_EXPIRY_MS = 24 * 60 * 60 * 1000;
|
||||||
|
const CACHE_CLEAN_INTERVAL_MS = 60 * 60 * 1000;
|
||||||
|
const CACHE_STALE_WHILE_REVALIDATE_SECONDS = 300;
|
||||||
|
const PURGE_BATCH_SIZE = 200;
|
||||||
|
|
||||||
|
type CacheRow = {
|
||||||
|
relativePath: string;
|
||||||
|
pasteExpiresAt: number | null;
|
||||||
|
cacheExpiresAt: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ExpiredCacheRow = {
|
||||||
|
pasteId: string;
|
||||||
|
relativePath: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CachedOgImage = {
|
||||||
|
jpg: Buffer;
|
||||||
|
ttlSeconds: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type StoreCachedOgImageInput = {
|
||||||
|
id: string;
|
||||||
|
jpg: Buffer;
|
||||||
|
pasteExpiresAt?: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
let database: Database | null = null;
|
||||||
|
let lastPurgeAt = 0;
|
||||||
|
let purgeInFlight: Promise<void> | null = null;
|
||||||
|
|
||||||
|
function getDatabase(): Database {
|
||||||
|
if (database) return database;
|
||||||
|
|
||||||
|
mkdirSync(CACHE_DIR, { recursive: true });
|
||||||
|
const nextDatabase = new BetterSqlite3(CACHE_DB_PATH);
|
||||||
|
nextDatabase.exec('PRAGMA journal_mode = WAL');
|
||||||
|
nextDatabase.exec('PRAGMA synchronous = NORMAL');
|
||||||
|
nextDatabase.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS og_image_cache (
|
||||||
|
paste_id TEXT PRIMARY KEY,
|
||||||
|
relative_path TEXT NOT NULL,
|
||||||
|
paste_expires_at INTEGER,
|
||||||
|
cache_expires_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_og_image_cache_cache_expires_at
|
||||||
|
ON og_image_cache (cache_expires_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_og_image_cache_paste_expires_at
|
||||||
|
ON og_image_cache (paste_expires_at);
|
||||||
|
`);
|
||||||
|
database = nextDatabase;
|
||||||
|
return nextDatabase;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCacheTtlExpiry(pasteExpiresAt?: number | null): number {
|
||||||
|
const cacheExpiresAt = Date.now() + CACHE_EXPIRY_MS;
|
||||||
|
if (!pasteExpiresAt) return cacheExpiresAt;
|
||||||
|
return Math.min(cacheExpiresAt, pasteExpiresAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCacheTtlSeconds(expiresAt?: number | null): number {
|
||||||
|
if (!expiresAt) return CACHE_EXPIRY_MS / 1000;
|
||||||
|
const secondsUntilExpiry = Math.floor((expiresAt - Date.now()) / 1000);
|
||||||
|
if (secondsUntilExpiry <= 0) return 0;
|
||||||
|
return Math.min(secondsUntilExpiry, CACHE_EXPIRY_MS / 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getCacheControlHeader(ttlSeconds: number): string {
|
||||||
|
return ttlSeconds > 0
|
||||||
|
? `private, max-age=${ttlSeconds}, stale-while-revalidate=${CACHE_STALE_WHILE_REVALIDATE_SECONDS}`
|
||||||
|
: 'no-store, max-age=0';
|
||||||
|
}
|
||||||
|
|
||||||
|
function getShardRelativePath(id: string): string {
|
||||||
|
const hash = createHash('sha256').update(id).digest('hex');
|
||||||
|
return join(hash.slice(0, 2), hash.slice(2, 4), `${id}.jpg`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getAbsolutePath(relativePath: string): string {
|
||||||
|
return join(CACHE_DIR, relativePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteCacheFile(relativePath: string): Promise<void> {
|
||||||
|
await unlink(getAbsolutePath(relativePath)).catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteCacheEntry(id: string, relativePath?: string): Promise<void> {
|
||||||
|
const db = getDatabase();
|
||||||
|
const resolvedPath =
|
||||||
|
relativePath ??
|
||||||
|
(
|
||||||
|
db
|
||||||
|
.prepare('SELECT relative_path AS relativePath FROM og_image_cache WHERE paste_id = ?')
|
||||||
|
.get(id) as { relativePath: string } | undefined
|
||||||
|
)?.relativePath ??
|
||||||
|
null;
|
||||||
|
|
||||||
|
db.prepare('DELETE FROM og_image_cache WHERE paste_id = ?').run(id);
|
||||||
|
if (resolvedPath) {
|
||||||
|
await deleteCacheFile(resolvedPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getCachedOgImage(id: string): Promise<CachedOgImage | null> {
|
||||||
|
const db = getDatabase();
|
||||||
|
const row = db
|
||||||
|
.prepare(
|
||||||
|
'SELECT relative_path AS relativePath, paste_expires_at AS pasteExpiresAt, cache_expires_at AS cacheExpiresAt FROM og_image_cache WHERE paste_id = ?'
|
||||||
|
)
|
||||||
|
.get(id) as CacheRow | undefined;
|
||||||
|
|
||||||
|
if (!row) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ttlSeconds = getCacheTtlSeconds(row.cacheExpiresAt);
|
||||||
|
if (ttlSeconds <= 0) {
|
||||||
|
await deleteCacheEntry(id, row.relativePath);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
typeof row.pasteExpiresAt === 'number' &&
|
||||||
|
row.pasteExpiresAt > 0 &&
|
||||||
|
row.pasteExpiresAt <= Date.now()
|
||||||
|
) {
|
||||||
|
await deleteCacheEntry(id, row.relativePath);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const jpg = await readFile(getAbsolutePath(row.relativePath));
|
||||||
|
return { jpg, ttlSeconds };
|
||||||
|
} catch {
|
||||||
|
await deleteCacheEntry(id, row.relativePath);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function storeCachedOgImage({
|
||||||
|
id,
|
||||||
|
jpg,
|
||||||
|
pasteExpiresAt
|
||||||
|
}: StoreCachedOgImageInput): Promise<void> {
|
||||||
|
const db = getDatabase();
|
||||||
|
const relativePath = getShardRelativePath(id);
|
||||||
|
const absolutePath = getAbsolutePath(relativePath);
|
||||||
|
const tempPath = `${absolutePath}.tmp-${process.pid}-${Date.now()}`;
|
||||||
|
await mkdir(dirname(absolutePath), { recursive: true });
|
||||||
|
await writeFile(tempPath, jpg);
|
||||||
|
await rename(tempPath, absolutePath);
|
||||||
|
|
||||||
|
try {
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO og_image_cache (paste_id, relative_path, paste_expires_at, cache_expires_at)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
ON CONFLICT(paste_id) DO UPDATE SET
|
||||||
|
relative_path = excluded.relative_path,
|
||||||
|
paste_expires_at = excluded.paste_expires_at,
|
||||||
|
cache_expires_at = excluded.cache_expires_at`
|
||||||
|
).run(id, relativePath, pasteExpiresAt ?? null, getCacheTtlExpiry(pasteExpiresAt));
|
||||||
|
} catch (error) {
|
||||||
|
await unlink(absolutePath).catch(() => undefined);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function purgeExpiredCache(limit: number = PURGE_BATCH_SIZE): Promise<void> {
|
||||||
|
const db = getDatabase();
|
||||||
|
const now = Date.now();
|
||||||
|
const rows = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT paste_id AS pasteId, relative_path AS relativePath
|
||||||
|
FROM og_image_cache
|
||||||
|
WHERE cache_expires_at <= ?
|
||||||
|
OR (paste_expires_at IS NOT NULL AND paste_expires_at > 0 AND paste_expires_at <= ?)
|
||||||
|
LIMIT ?`
|
||||||
|
)
|
||||||
|
.all(now, now, limit) as ExpiredCacheRow[];
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
await deleteCacheFile(row.relativePath);
|
||||||
|
db.prepare('DELETE FROM og_image_cache WHERE paste_id = ?').run(row.pasteId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function scheduleOgImageCachePurge(): void {
|
||||||
|
const now = Date.now();
|
||||||
|
if (purgeInFlight || now - lastPurgeAt < CACHE_CLEAN_INTERVAL_MS) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
purgeInFlight = purgeExpiredCache().finally(() => {
|
||||||
|
lastPurgeAt = Date.now();
|
||||||
|
purgeInFlight = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
export type PasteEmbedMetadataItem = {
|
||||||
|
icon:
|
||||||
|
| 'size'
|
||||||
|
| 'views'
|
||||||
|
| 'created'
|
||||||
|
| 'expires'
|
||||||
|
| 'syntax'
|
||||||
|
| 'visibility-0'
|
||||||
|
| 'visibility-1'
|
||||||
|
| 'visibility-2';
|
||||||
|
value: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PasteEmbedProps = {
|
||||||
|
title: string;
|
||||||
|
uploader: string;
|
||||||
|
metadata: PasteEmbedMetadataItem[];
|
||||||
|
previewLines: string[];
|
||||||
|
isEncrypted: boolean;
|
||||||
|
};
|
||||||
@@ -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,39 +1,5 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store';
|
||||||
|
import type { ModalOpenOptions, ModalState } from '#lib/types/modal';
|
||||||
type ModalMode =
|
|
||||||
| 'decrypt'
|
|
||||||
| 'encrypt'
|
|
||||||
| 'confirm'
|
|
||||||
| 'prompt'
|
|
||||||
| 'multiselect'
|
|
||||||
| 'totp'
|
|
||||||
| 'totpSetup'
|
|
||||||
| 'report';
|
|
||||||
|
|
||||||
type ModalItem = { label: string; value: unknown };
|
|
||||||
|
|
||||||
type ModalState = {
|
|
||||||
show: boolean;
|
|
||||||
mode: ModalMode;
|
|
||||||
title: string;
|
|
||||||
message: string;
|
|
||||||
error: string;
|
|
||||||
placeholder: string;
|
|
||||||
inputType: string;
|
|
||||||
maxInputLength?: number;
|
|
||||||
items: ModalItem[];
|
|
||||||
initialValue: unknown;
|
|
||||||
totpActive: boolean | null;
|
|
||||||
reportTarget: 'user' | 'paste' | null;
|
|
||||||
reportTargetId: string | number | null;
|
|
||||||
reportSiteKey: string | null;
|
|
||||||
confirmButtonText: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type ModalOpenOptions = Partial<Omit<ModalState, 'show'>> & {
|
|
||||||
mode: ModalMode;
|
|
||||||
cancelValue?: unknown;
|
|
||||||
};
|
|
||||||
|
|
||||||
const initialState: ModalState = {
|
const initialState: ModalState = {
|
||||||
show: false,
|
show: false,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { writable } from 'svelte/store';
|
import { writable } from 'svelte/store';
|
||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/environment';
|
||||||
import type { AuthUser } from '$lib/types/user';
|
import type { AuthUser } from '#lib/types/user';
|
||||||
|
|
||||||
let initial: AuthUser | null = null;
|
let initial: AuthUser | null = null;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import type { Author } from './author';
|
||||||
|
|
||||||
|
export type CommentReaction = 1 | 2 | null;
|
||||||
|
|
||||||
|
export interface CommentAuthor extends Author {
|
||||||
|
displayName?: string | null;
|
||||||
|
roles?: number;
|
||||||
|
isBanned?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PasteComment {
|
||||||
|
id: number;
|
||||||
|
parentCommentID: number | null;
|
||||||
|
content: string | null;
|
||||||
|
storedSize: number;
|
||||||
|
originalSize: number;
|
||||||
|
isCompressed: boolean;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number | null;
|
||||||
|
likes: number;
|
||||||
|
dislikes: number;
|
||||||
|
userReaction: CommentReaction;
|
||||||
|
author: CommentAuthor | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CommentReactionResult {
|
||||||
|
commentID: number;
|
||||||
|
likes: number;
|
||||||
|
dislikes: number;
|
||||||
|
userReaction: CommentReaction;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CommentTreeNode extends PasteComment {
|
||||||
|
children: CommentTreeNode[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
export type ModalMode =
|
||||||
|
| 'decrypt'
|
||||||
|
| 'encrypt'
|
||||||
|
| 'confirm'
|
||||||
|
| 'prompt'
|
||||||
|
| 'multiselect'
|
||||||
|
| 'totp'
|
||||||
|
| 'totpSetup'
|
||||||
|
| 'report';
|
||||||
|
|
||||||
|
export type ModalItem = { label: string; value: unknown };
|
||||||
|
|
||||||
|
export type ModalState = {
|
||||||
|
show: boolean;
|
||||||
|
mode: ModalMode;
|
||||||
|
title: string;
|
||||||
|
message: string;
|
||||||
|
error: string;
|
||||||
|
placeholder: string;
|
||||||
|
inputType: string;
|
||||||
|
maxInputLength?: number;
|
||||||
|
items: ModalItem[];
|
||||||
|
initialValue: unknown;
|
||||||
|
totpActive: boolean | null;
|
||||||
|
reportTarget: 'user' | 'paste' | null;
|
||||||
|
reportTargetId: string | number | null;
|
||||||
|
reportSiteKey: string | null;
|
||||||
|
confirmButtonText: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ModalOpenOptions = Partial<Omit<ModalState, 'show'>> & {
|
||||||
|
mode: ModalMode;
|
||||||
|
cancelValue?: unknown;
|
||||||
|
};
|
||||||
@@ -1,17 +1,23 @@
|
|||||||
import type { Author } from './author';
|
import type { Author } from './author';
|
||||||
|
|
||||||
|
export type PasteReaction = 1 | 2 | null;
|
||||||
|
|
||||||
export interface Paste {
|
export interface Paste {
|
||||||
id: string;
|
id: string;
|
||||||
uuid: string;
|
uuid: string;
|
||||||
|
createdAt: number;
|
||||||
title: string | null;
|
title: string | null;
|
||||||
size: number;
|
storedSize: number;
|
||||||
trueSize: number;
|
originalSize: number;
|
||||||
isCompressed: boolean;
|
isCompressed: boolean;
|
||||||
views: number;
|
views: number;
|
||||||
syntax: string;
|
syntax: string;
|
||||||
visibility: 0 | 1 | 2;
|
visibility: 0 | 1 | 2;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
editedAt: number | null;
|
editedAt: number | null;
|
||||||
|
likes: number;
|
||||||
|
dislikes: number;
|
||||||
|
userReaction: PasteReaction;
|
||||||
reportCount: number | null;
|
reportCount: number | null;
|
||||||
author: Author | null;
|
author: Author | null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,4 +28,4 @@ export const reportTypeLabels = ['CopyrightViolation', 'IllegalContent', 'Fraud'
|
|||||||
|
|
||||||
export const reportStatusLabels = ['Open', 'Closed'] as const;
|
export const reportStatusLabels = ['Open', 'Closed'] as const;
|
||||||
|
|
||||||
export const reportTargetLabels = ['Paste', 'User'] as const;
|
export const reportTargetLabels = ['Paste', 'User', 'Comment'] as const;
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ export interface User {
|
|||||||
username: string;
|
username: string;
|
||||||
displayName: string | null;
|
displayName: string | null;
|
||||||
email: string | null;
|
email: string | null;
|
||||||
|
emailVerified: boolean;
|
||||||
lastLogin: number | null;
|
lastLogin: number | null;
|
||||||
roles: number[];
|
roles: number; // bitfield; 5 = User | Admin
|
||||||
|
isBanned: boolean;
|
||||||
visibility: 0 | 1 | 2;
|
visibility: 0 | 1 | 2;
|
||||||
pastes: Paste[] | null;
|
pastes: Paste[] | null;
|
||||||
pagination: Pagination | null;
|
pagination: Pagination | null;
|
||||||
@@ -17,3 +19,12 @@ export interface User {
|
|||||||
export interface AuthUser extends User {
|
export interface AuthUser extends User {
|
||||||
totpEnabled: boolean;
|
totpEnabled: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface JWTUser {
|
||||||
|
uuid: string;
|
||||||
|
username: string;
|
||||||
|
displayname: string;
|
||||||
|
totpEnabled: boolean;
|
||||||
|
roles: number;
|
||||||
|
isBanned: boolean;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,43 +1,141 @@
|
|||||||
import { browser } from '$app/environment';
|
import { browser } from '$app/environment';
|
||||||
import type { Cookies } from '@sveltejs/kit';
|
import type { Cookies } from '@sveltejs/kit';
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '#lib/stores/user';
|
||||||
|
import type { JWTUser } from '#lib/types/user';
|
||||||
|
|
||||||
|
export const roles = {
|
||||||
|
User: 1,
|
||||||
|
Moderator: 2,
|
||||||
|
Admin: 4
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type Role = keyof typeof roles;
|
||||||
|
|
||||||
const TOKEN_KEY = 'token';
|
const TOKEN_KEY = 'token';
|
||||||
const REFRESH_TOKEN_KEY = 'refreshToken';
|
const REFRESH_TOKEN_KEY = 'refreshToken';
|
||||||
|
const TOKEN_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 180;
|
||||||
|
const AUTH_TOKENS_UPDATED_EVENT = 'auth:tokens-updated';
|
||||||
|
const AUTH_TOKENS_CLEARED_EVENT = 'auth:tokens-cleared';
|
||||||
|
|
||||||
export function getToken() {
|
let refreshPromise: Promise<void> | null = null;
|
||||||
|
let lastRefreshAttempt = 0;
|
||||||
|
let refreshFailureCount = 0;
|
||||||
|
let refreshIntervalId: ReturnType<typeof setInterval> | null = null;
|
||||||
|
let listenersRegistered = false;
|
||||||
|
|
||||||
|
function getCookieValue(key: string) {
|
||||||
if (!browser) return null;
|
if (!browser) return null;
|
||||||
|
const entry = document.cookie
|
||||||
|
.split('; ')
|
||||||
|
.find((cookieEntry) => cookieEntry.startsWith(`${key}=`));
|
||||||
|
if (!entry) return null;
|
||||||
|
const value = entry.slice(key.length + 1);
|
||||||
|
try {
|
||||||
|
return decodeURIComponent(value);
|
||||||
|
} catch {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCookieSecurityAttributes() {
|
||||||
|
if (!browser) return '';
|
||||||
|
return window.location.protocol === 'https:' ? '; secure' : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function emitAuthEvent(eventName: string) {
|
||||||
|
if (!browser) return;
|
||||||
|
window.dispatchEvent(new CustomEvent(eventName));
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeBase64Url(value: string) {
|
||||||
|
const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
|
||||||
|
const padding = normalized.length % 4 === 0 ? '' : '='.repeat(4 - (normalized.length % 4));
|
||||||
|
return atob(normalized + padding);
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeJwtPayload(token: string): Record<string, unknown> | null {
|
||||||
|
try {
|
||||||
|
const [, payload] = token.split('.');
|
||||||
|
if (!payload) return null;
|
||||||
|
return JSON.parse(decodeBase64Url(payload));
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBooleanClaim(value: unknown) {
|
||||||
|
if (typeof value === 'string') return value.toLowerCase() === 'true';
|
||||||
|
return Boolean(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseNumberClaim(value: unknown): number | null {
|
||||||
|
const numeric =
|
||||||
|
typeof value === 'number' ? value : typeof value === 'string' ? parseInt(value, 10) : NaN;
|
||||||
|
return Number.isFinite(numeric) ? numeric : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPermanentRefreshFailure(status: number, message?: string) {
|
||||||
|
if (status === 401 || status === 403) return true;
|
||||||
|
if (!message) return false;
|
||||||
|
const normalized = message.toLowerCase();
|
||||||
return (
|
return (
|
||||||
document.cookie
|
normalized.includes('invalid') ||
|
||||||
.split('; ')
|
normalized.includes('expired') ||
|
||||||
.find((c) => c.startsWith(`${TOKEN_KEY}=`))
|
normalized.includes('revoked') ||
|
||||||
?.split('=')[1] || null
|
normalized.includes('malformed')
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function queueRefresh(token: string, refreshToken: string) {
|
||||||
|
if (refreshPromise) {
|
||||||
|
await refreshPromise;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const timeSinceLastAttempt = now - lastRefreshAttempt;
|
||||||
|
const minDelay = getBackoffDelay(refreshFailureCount);
|
||||||
|
if (timeSinceLastAttempt < minDelay) return;
|
||||||
|
|
||||||
|
refreshPromise = performRefresh(token, refreshToken);
|
||||||
|
try {
|
||||||
|
await refreshPromise;
|
||||||
|
} finally {
|
||||||
|
refreshPromise = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getToken() {
|
||||||
|
return getCookieValue(TOKEN_KEY);
|
||||||
|
}
|
||||||
|
|
||||||
export function getRefreshToken() {
|
export function getRefreshToken() {
|
||||||
if (!browser) return null;
|
return getCookieValue(REFRESH_TOKEN_KEY);
|
||||||
return (
|
|
||||||
document.cookie
|
|
||||||
.split('; ')
|
|
||||||
.find((c) => c.startsWith(`${REFRESH_TOKEN_KEY}=`))
|
|
||||||
?.split('=')[1] || null
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setTokens(token: string, refreshToken: string) {
|
export function setTokens(token: string, refreshToken: string) {
|
||||||
if (!browser) return;
|
if (!browser) return;
|
||||||
console.log('Setting tokens');
|
const secureAttributes = getCookieSecurityAttributes();
|
||||||
document.cookie = `${TOKEN_KEY}=${token}; path=/; secure; samesite=strict`;
|
document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=${TOKEN_COOKIE_MAX_AGE_SECONDS}; samesite=strict${secureAttributes}`;
|
||||||
document.cookie = `${REFRESH_TOKEN_KEY}=${refreshToken}; path=/; secure; samesite=strict`;
|
document.cookie = `${REFRESH_TOKEN_KEY}=${encodeURIComponent(refreshToken)}; path=/; max-age=${TOKEN_COOKIE_MAX_AGE_SECONDS}; samesite=strict${secureAttributes}`;
|
||||||
|
refreshFailureCount = 0;
|
||||||
|
emitAuthEvent(AUTH_TOKENS_UPDATED_EVENT);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearTokens() {
|
export function clearTokens() {
|
||||||
if (!browser) return;
|
if (!browser) return;
|
||||||
console.log('Clearing tokens');
|
const secureAttributes = getCookieSecurityAttributes();
|
||||||
document.cookie = `${TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
document.cookie = `${TOKEN_KEY}=; path=/; max-age=0; samesite=strict${secureAttributes}`;
|
||||||
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
|
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; max-age=0; samesite=strict${secureAttributes}`;
|
||||||
user.set(null);
|
user.set(null);
|
||||||
|
emitAuthEvent(AUTH_TOKENS_CLEARED_EVENT);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getBackoffDelay(attempt: number): number {
|
||||||
|
const baseDelay = 1000;
|
||||||
|
const maxDelay = 30000;
|
||||||
|
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
|
||||||
|
return delay + Math.random() * 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function refreshTokenIfNeeded() {
|
export async function refreshTokenIfNeeded() {
|
||||||
@@ -45,37 +143,84 @@ export async function refreshTokenIfNeeded() {
|
|||||||
const refreshToken = getRefreshToken();
|
const refreshToken = getRefreshToken();
|
||||||
if (!token || !refreshToken) return;
|
if (!token || !refreshToken) return;
|
||||||
|
|
||||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
const payload = decodeJwtPayload(token);
|
||||||
const exp = payload.exp * 1000;
|
const expClaim = payload ? parseNumberClaim(payload.exp) : null;
|
||||||
|
if (expClaim === null) {
|
||||||
|
await queueRefresh(token, refreshToken);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const exp = expClaim * 1000;
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
if (exp - now < 2 * 60 * 1000) {
|
if (exp - now >= 2 * 60 * 1000) return;
|
||||||
console.log('Refreshing token...');
|
await queueRefresh(token, refreshToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function performRefresh(token: string, refreshToken: string) {
|
||||||
|
lastRefreshAttempt = Date.now();
|
||||||
|
|
||||||
|
try {
|
||||||
const res = await fetch('/api/auth/refresh', {
|
const res = await fetch('/api/auth/refresh', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ token, refreshToken })
|
body: JSON.stringify({ token, refreshToken })
|
||||||
});
|
});
|
||||||
if (res.ok) {
|
let data: {
|
||||||
const data = await res.json();
|
success?: boolean;
|
||||||
if (data.success && data.token?.token && data.token?.refreshToken) {
|
message?: string;
|
||||||
console.log('Token refreshed successfully');
|
token?: { token?: string; refreshToken?: string };
|
||||||
setTokens(data.token.token, data.token.refreshToken);
|
} | null = null;
|
||||||
} else {
|
try {
|
||||||
console.log('Invalid tokens received during refresh');
|
data = await res.json();
|
||||||
|
} catch {
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
refreshFailureCount++;
|
||||||
|
if (isPermanentRefreshFailure(res.status, data?.message)) {
|
||||||
clearTokens();
|
clearTokens();
|
||||||
}
|
}
|
||||||
} else {
|
return;
|
||||||
console.log('Failed to refresh token');
|
|
||||||
clearTokens();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (data?.success && data.token?.token && data.token?.refreshToken) {
|
||||||
|
setTokens(data.token.token, data.token.refreshToken);
|
||||||
|
} else {
|
||||||
|
refreshFailureCount++;
|
||||||
|
if (isPermanentRefreshFailure(res.status, data?.message)) {
|
||||||
|
clearTokens();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
refreshFailureCount++;
|
||||||
}
|
}
|
||||||
console.log('Token is still valid, no refresh needed');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function startTokenRefreshInterval() {
|
export function startTokenRefreshInterval() {
|
||||||
if (!browser) return;
|
if (!browser) return;
|
||||||
setInterval(refreshTokenIfNeeded, 60 * 1000);
|
if (refreshIntervalId !== null) return;
|
||||||
|
refreshIntervalId = setInterval(() => {
|
||||||
|
void refreshTokenIfNeeded();
|
||||||
|
}, 60 * 1000);
|
||||||
|
|
||||||
|
if (!listenersRegistered) {
|
||||||
|
window.addEventListener('focus', () => {
|
||||||
|
void refreshTokenIfNeeded();
|
||||||
|
});
|
||||||
|
document.addEventListener('visibilitychange', () => {
|
||||||
|
if (document.visibilityState === 'visible') {
|
||||||
|
void refreshTokenIfNeeded();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
window.addEventListener('online', () => {
|
||||||
|
void refreshTokenIfNeeded();
|
||||||
|
});
|
||||||
|
listenersRegistered = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void refreshTokenIfNeeded();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getServerToken(cookies: Cookies) {
|
export function getServerToken(cookies: Cookies) {
|
||||||
@@ -87,12 +232,19 @@ export function getServerRefreshToken(cookies: Cookies) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function setServerTokens(cookies: Cookies, token: string, refreshToken: string) {
|
export function setServerTokens(cookies: Cookies, token: string, refreshToken: string) {
|
||||||
cookies.set('token', token, { path: '/', httpOnly: true, sameSite: 'strict', secure: true });
|
cookies.set('token', token, {
|
||||||
|
path: '/',
|
||||||
|
httpOnly: true,
|
||||||
|
sameSite: 'strict',
|
||||||
|
secure: true,
|
||||||
|
maxAge: TOKEN_COOKIE_MAX_AGE_SECONDS
|
||||||
|
});
|
||||||
cookies.set('refreshToken', refreshToken, {
|
cookies.set('refreshToken', refreshToken, {
|
||||||
path: '/',
|
path: '/',
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: 'strict',
|
sameSite: 'strict',
|
||||||
secure: true
|
secure: true,
|
||||||
|
maxAge: TOKEN_COOKIE_MAX_AGE_SECONDS
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,3 +252,29 @@ export function clearServerTokens(cookies: Cookies) {
|
|||||||
cookies.delete('token', { path: '/' });
|
cookies.delete('token', { path: '/' });
|
||||||
cookies.delete('refreshToken', { path: '/' });
|
cookies.delete('refreshToken', { path: '/' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function getUserFromToken(token: string): JWTUser | null {
|
||||||
|
const payload = decodeJwtPayload(token);
|
||||||
|
if (!payload) return null;
|
||||||
|
|
||||||
|
const uuid = typeof payload.uuid === 'string' ? payload.uuid : null;
|
||||||
|
const username = typeof payload.username === 'string' ? payload.username : null;
|
||||||
|
const displayname = typeof payload.displayname === 'string' ? payload.displayname : '';
|
||||||
|
const rolesClaim = parseNumberClaim(payload.roles);
|
||||||
|
|
||||||
|
if (!uuid || !username || rolesClaim === null) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
uuid,
|
||||||
|
username,
|
||||||
|
displayname,
|
||||||
|
totpEnabled: parseBooleanClaim(payload.totp_enabled),
|
||||||
|
roles: rolesClaim,
|
||||||
|
isBanned: parseBooleanClaim(payload.is_banned)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const hasRole = (userRoles: number, role: number) => (userRoles & role) !== 0;
|
||||||
|
|
||||||
|
export const getUserRoles = (userRoles: number): Role[] =>
|
||||||
|
(Object.keys(roles) as Role[]).filter((role) => hasRole(userRoles, roles[role]));
|
||||||
|
|||||||
@@ -1,10 +1,21 @@
|
|||||||
import { argon2id } from 'hash-wasm';
|
import { argon2id } from 'hash-wasm';
|
||||||
|
|
||||||
|
const BASE64_CHUNK_SIZE = 0x8000;
|
||||||
|
const SALT_LENGTH = 16;
|
||||||
|
const IV_LENGTH = 12;
|
||||||
|
const ARGON2_MEMORY_SIZE = 262144;
|
||||||
|
const ARGON2_ITERATIONS = 3;
|
||||||
|
const ARGON2_PARALLELISM = 1;
|
||||||
|
const ARGON2_HASH_LENGTH = 32;
|
||||||
|
const AES_KEY_LENGTH = 256;
|
||||||
|
const ENCRYPTION_AAD = 'enc-v4';
|
||||||
|
const ENCRYPTED_DATA_OVERHEAD = 60;
|
||||||
|
const ENCRYPTED_METADATA_OVERHEAD = 150;
|
||||||
|
|
||||||
function toBase64(bytes: Uint8Array): string {
|
function toBase64(bytes: Uint8Array): string {
|
||||||
let binary = '';
|
let binary = '';
|
||||||
const chunkSize = 0x8000;
|
for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) {
|
||||||
for (let i = 0; i < bytes.length; i += chunkSize) {
|
binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK_SIZE));
|
||||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
|
|
||||||
}
|
}
|
||||||
return btoa(binary);
|
return btoa(binary);
|
||||||
}
|
}
|
||||||
@@ -20,34 +31,32 @@ function fromBase64(data: string): Uint8Array {
|
|||||||
|
|
||||||
export async function encryptAES(content: string, password: string): Promise<string> {
|
export async function encryptAES(content: string, password: string): Promise<string> {
|
||||||
const enc = new TextEncoder();
|
const enc = new TextEncoder();
|
||||||
const salt = window.crypto.getRandomValues(new Uint8Array(32));
|
const salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
|
||||||
const memorySize = 65536;
|
|
||||||
const iterations = 3;
|
|
||||||
const parallelism = 1;
|
|
||||||
|
|
||||||
const keyMaterial = await argon2id({
|
const keyMaterial = await argon2id({
|
||||||
password,
|
password,
|
||||||
salt,
|
salt,
|
||||||
iterations,
|
iterations: ARGON2_ITERATIONS,
|
||||||
memorySize,
|
memorySize: ARGON2_MEMORY_SIZE,
|
||||||
parallelism,
|
parallelism: ARGON2_PARALLELISM,
|
||||||
hashLength: 32,
|
hashLength: ARGON2_HASH_LENGTH,
|
||||||
outputType: 'binary'
|
outputType: 'binary'
|
||||||
});
|
});
|
||||||
|
|
||||||
const key = await window.crypto.subtle.importKey(
|
const key = await window.crypto.subtle.importKey(
|
||||||
'raw',
|
'raw',
|
||||||
keyMaterial as unknown as BufferSource,
|
new Uint8Array(keyMaterial),
|
||||||
{ name: 'AES-GCM' },
|
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||||
false,
|
false,
|
||||||
['encrypt']
|
['encrypt']
|
||||||
);
|
);
|
||||||
|
|
||||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
const iv = window.crypto.getRandomValues(new Uint8Array(IV_LENGTH));
|
||||||
const encryptedContent = await window.crypto.subtle.encrypt(
|
const encryptedContent = await window.crypto.subtle.encrypt(
|
||||||
{
|
{
|
||||||
name: 'AES-GCM',
|
name: 'AES-GCM',
|
||||||
iv
|
iv,
|
||||||
|
additionalData: enc.encode(ENCRYPTION_AAD)
|
||||||
},
|
},
|
||||||
key,
|
key,
|
||||||
enc.encode(content)
|
enc.encode(content)
|
||||||
@@ -61,9 +70,9 @@ export async function encryptAES(content: string, password: string): Promise<str
|
|||||||
return JSON.stringify({
|
return JSON.stringify({
|
||||||
version: 4,
|
version: 4,
|
||||||
kdf: 'Argon2id',
|
kdf: 'Argon2id',
|
||||||
memorySize,
|
memorySize: ARGON2_MEMORY_SIZE,
|
||||||
iterations,
|
iterations: ARGON2_ITERATIONS,
|
||||||
parallelism,
|
parallelism: ARGON2_PARALLELISM,
|
||||||
algorithm: 'AES-GCM',
|
algorithm: 'AES-GCM',
|
||||||
saltLength: salt.byteLength,
|
saltLength: salt.byteLength,
|
||||||
ivLength: iv.byteLength,
|
ivLength: iv.byteLength,
|
||||||
@@ -73,9 +82,9 @@ export async function encryptAES(content: string, password: string): Promise<str
|
|||||||
|
|
||||||
export function estimateEncryptedSize(content: string): number {
|
export function estimateEncryptedSize(content: string): number {
|
||||||
const rawSize = new TextEncoder().encode(content).length;
|
const rawSize = new TextEncoder().encode(content).length;
|
||||||
const combinedSize = rawSize + 60;
|
const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
|
||||||
const b64Size = Math.ceil(combinedSize / 3) * 4;
|
const b64Size = Math.ceil(combinedSize / 3) * 4;
|
||||||
return b64Size + 150;
|
return b64Size + ENCRYPTED_METADATA_OVERHEAD;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function decryptAES(result: string, password: string): Promise<string | null> {
|
export async function decryptAES(result: string, password: string): Promise<string | null> {
|
||||||
@@ -84,8 +93,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
|||||||
const parsed = JSON.parse(result);
|
const parsed = JSON.parse(result);
|
||||||
const combined = fromBase64(parsed.data);
|
const combined = fromBase64(parsed.data);
|
||||||
|
|
||||||
const saltLength = parsed.saltLength || 16;
|
const saltLength = parsed.saltLength || SALT_LENGTH;
|
||||||
const ivLength = parsed.ivLength || 12;
|
const ivLength = parsed.ivLength || IV_LENGTH;
|
||||||
const salt = combined.slice(0, saltLength);
|
const salt = combined.slice(0, saltLength);
|
||||||
const iv = combined.slice(saltLength, saltLength + ivLength);
|
const iv = combined.slice(saltLength, saltLength + ivLength);
|
||||||
const data = combined.slice(saltLength + ivLength);
|
const data = combined.slice(saltLength + ivLength);
|
||||||
@@ -99,7 +108,7 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
|||||||
iterations: parsed.iterations,
|
iterations: parsed.iterations,
|
||||||
memorySize: parsed.memorySize,
|
memorySize: parsed.memorySize,
|
||||||
parallelism: parsed.parallelism,
|
parallelism: parsed.parallelism,
|
||||||
hashLength: 32,
|
hashLength: ARGON2_HASH_LENGTH,
|
||||||
outputType: 'binary'
|
outputType: 'binary'
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -118,7 +127,7 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
|||||||
hash: parsed.hash
|
hash: parsed.hash
|
||||||
},
|
},
|
||||||
baseKey,
|
baseKey,
|
||||||
{ name: 'AES-GCM', length: 256 },
|
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||||
true,
|
true,
|
||||||
['encrypt', 'decrypt']
|
['encrypt', 'decrypt']
|
||||||
);
|
);
|
||||||
@@ -127,8 +136,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
|||||||
|
|
||||||
const key = await window.crypto.subtle.importKey(
|
const key = await window.crypto.subtle.importKey(
|
||||||
'raw',
|
'raw',
|
||||||
keyMaterial as unknown as BufferSource,
|
new Uint8Array(keyMaterial),
|
||||||
{ name: 'AES-GCM' },
|
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||||
false,
|
false,
|
||||||
['decrypt']
|
['decrypt']
|
||||||
);
|
);
|
||||||
@@ -136,7 +145,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
|||||||
const decryptedContent = await window.crypto.subtle.decrypt(
|
const decryptedContent = await window.crypto.subtle.decrypt(
|
||||||
{
|
{
|
||||||
name: 'AES-GCM',
|
name: 'AES-GCM',
|
||||||
iv
|
iv,
|
||||||
|
additionalData: enc.encode(ENCRYPTION_AAD)
|
||||||
},
|
},
|
||||||
key,
|
key,
|
||||||
data
|
data
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
const htmlEscapeMap: Record<string, string> = {
|
||||||
|
'&': '&',
|
||||||
|
'<': '<',
|
||||||
|
'>': '>',
|
||||||
|
'"': '"',
|
||||||
|
"'": ''',
|
||||||
|
'`': '`'
|
||||||
|
};
|
||||||
|
|
||||||
|
export function escapeHtml(value: string): string {
|
||||||
|
return value.replace(/[&<>"'`]/g, (char) => htmlEscapeMap[char]);
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
import { marked } from 'marked';
|
import { marked } from 'marked';
|
||||||
import createDOMPurify from 'dompurify';
|
import createDOMPurify from 'dompurify';
|
||||||
import type { WindowLike } 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';
|
||||||
|
|
||||||
const tagMap: Record<string, string> = {
|
const tagMap: Record<string, string> = {
|
||||||
IMG: 'image',
|
IMG: 'image',
|
||||||
@@ -10,6 +13,18 @@ const tagMap: Record<string, string> = {
|
|||||||
IFRAME: 'iframe'
|
IFRAME: 'iframe'
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export function getIgnoreExternalMediaWarning(): boolean {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
|
||||||
|
return window.localStorage.getItem(externalMediaWarningStorageKey) === 'true';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setIgnoreExternalMediaWarning(ignore: boolean) {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
|
window.localStorage.setItem(externalMediaWarningStorageKey, ignore ? 'true' : 'false');
|
||||||
|
}
|
||||||
|
|
||||||
export async function parseMarkdown(
|
export async function parseMarkdown(
|
||||||
md: string,
|
md: string,
|
||||||
preventExternal: boolean = true,
|
preventExternal: boolean = true,
|
||||||
@@ -80,6 +95,14 @@ export async function parseMarkdown(
|
|||||||
'background-color: #404040; color: white; padding: 0.25rem 0.75rem; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
|
'background-color: #404040; color: white; padding: 0.25rem 0.75rem; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const ignoreButton = dom.document.createElement('button');
|
||||||
|
ignoreButton.textContent = "Don't warn again";
|
||||||
|
ignoreButton.className = 'ignore-media-warning-btn';
|
||||||
|
ignoreButton.setAttribute(
|
||||||
|
'style',
|
||||||
|
'background-color: transparent; color: #d4d4d8; padding: 0.25rem 0.75rem; border: 1px solid #525252; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
|
||||||
|
);
|
||||||
|
|
||||||
if (element.getAttribute('alt'))
|
if (element.getAttribute('alt'))
|
||||||
button.setAttribute('data-alt', element.getAttribute('alt') || '');
|
button.setAttribute('data-alt', element.getAttribute('alt') || '');
|
||||||
if (element.getAttribute('title'))
|
if (element.getAttribute('title'))
|
||||||
@@ -89,9 +112,17 @@ export async function parseMarkdown(
|
|||||||
if (element.getAttribute('height'))
|
if (element.getAttribute('height'))
|
||||||
button.setAttribute('data-height', element.getAttribute('height') || '');
|
button.setAttribute('data-height', element.getAttribute('height') || '');
|
||||||
|
|
||||||
|
const actions = dom.document.createElement('span');
|
||||||
|
actions.setAttribute(
|
||||||
|
'style',
|
||||||
|
'display: flex; gap: 0.5rem; justify-content: center; flex-wrap: wrap;'
|
||||||
|
);
|
||||||
|
actions.appendChild(button);
|
||||||
|
actions.appendChild(ignoreButton);
|
||||||
|
|
||||||
placeholder.appendChild(warning);
|
placeholder.appendChild(warning);
|
||||||
placeholder.appendChild(subWarning);
|
placeholder.appendChild(subWarning);
|
||||||
placeholder.appendChild(button);
|
placeholder.appendChild(actions);
|
||||||
|
|
||||||
const parent = element.parentNode;
|
const parent = element.parentNode;
|
||||||
if (parent && parent.nodeName === 'A') {
|
if (parent && parent.nodeName === 'A') {
|
||||||
@@ -108,3 +139,195 @@ export async function parseMarkdown(
|
|||||||
|
|
||||||
return DOMPurify.sanitize(html);
|
return DOMPurify.sanitize(html);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function parseCommentMarkdown(text: string): string {
|
||||||
|
const lines = text.replace(/\r\n?/g, '\n').split('\n');
|
||||||
|
const output: string[] = [];
|
||||||
|
let index = 0;
|
||||||
|
|
||||||
|
while (index < lines.length) {
|
||||||
|
const codeBlock = tryParseCodeBlock(lines, index);
|
||||||
|
if (codeBlock) {
|
||||||
|
output.push(codeBlock.html);
|
||||||
|
index = codeBlock.nextIndex;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const spoilerBlock = tryParseSpoilerBlock(lines, index);
|
||||||
|
if (spoilerBlock) {
|
||||||
|
output.push(spoilerBlock.html);
|
||||||
|
index = spoilerBlock.nextIndex;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const quoteBlock = tryParseQuoteBlock(lines, index);
|
||||||
|
if (quoteBlock) {
|
||||||
|
output.push(quoteBlock.html);
|
||||||
|
index = quoteBlock.nextIndex;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (/^\s*---\s*$/.test(lines[index])) {
|
||||||
|
output.push('<hr class="my-2 border-t border-neutral-700" />');
|
||||||
|
index += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
output.push(parseInlineElements(lines[index]));
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return output.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ParsedCommentBlock {
|
||||||
|
html: string;
|
||||||
|
nextIndex: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryParseCodeBlock(lines: string[], startIndex: number): ParsedCommentBlock | null {
|
||||||
|
const firstLine = lines[startIndex];
|
||||||
|
if (!firstLine.startsWith('```')) return null;
|
||||||
|
|
||||||
|
const inlineCloseIndex = firstLine.indexOf('```', 3);
|
||||||
|
if (inlineCloseIndex > -1) {
|
||||||
|
const code = firstLine.slice(3, inlineCloseIndex);
|
||||||
|
const trailing = firstLine.slice(inlineCloseIndex + 3).trim();
|
||||||
|
const html = renderCodeBlock(code);
|
||||||
|
if (trailing.length === 0) {
|
||||||
|
return { html, nextIndex: startIndex + 1 };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
html: `${html}\n${parseInlineElements(trailing)}`,
|
||||||
|
nextIndex: startIndex + 1
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const codeLines: string[] = [];
|
||||||
|
let index = startIndex + 1;
|
||||||
|
|
||||||
|
while (index < lines.length && !lines[index].startsWith('```')) {
|
||||||
|
codeLines.push(lines[index]);
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index < lines.length) index += 1;
|
||||||
|
|
||||||
|
return {
|
||||||
|
html: renderCodeBlock(codeLines.join('\n')),
|
||||||
|
nextIndex: index
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryParseSpoilerBlock(lines: string[], startIndex: number): ParsedCommentBlock | null {
|
||||||
|
const spoilerOpenMatch = lines[startIndex].match(/^\[Spoiler(?:="([^"]*)")?\](.*)$/i);
|
||||||
|
if (!spoilerOpenMatch) return null;
|
||||||
|
|
||||||
|
const title = spoilerOpenMatch[1]?.trim() || 'Spoiler';
|
||||||
|
const contentParts: string[] = [];
|
||||||
|
let remainder = spoilerOpenMatch[2] ?? '';
|
||||||
|
let index = startIndex;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const closeMatch = /\[\/spoiler\]/i.exec(remainder);
|
||||||
|
if (closeMatch && closeMatch.index !== undefined) {
|
||||||
|
const beforeClose = remainder.slice(0, closeMatch.index);
|
||||||
|
if (beforeClose.length > 0) contentParts.push(beforeClose);
|
||||||
|
|
||||||
|
const contentHtml = contentParts.map((line) => parseInlineElements(line)).join('<br />');
|
||||||
|
let html = `<details class="rounded-sm my-2 bg-neutral-800"><summary class="cursor-pointer px-2 py-1 font-semibold text-neutral-300 hover:text-neutral-200 w-full">${escapeHtml(title)}</summary><div class=" text-neutral-300 bg-neutral-700/40 px-2 p-2 rounded-b-sm">${contentHtml}</div></details>`;
|
||||||
|
|
||||||
|
const afterClose = remainder.slice(closeMatch.index + closeMatch[0].length).trim();
|
||||||
|
if (afterClose.length > 0) {
|
||||||
|
html += `\n${parseInlineElements(afterClose)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
html,
|
||||||
|
nextIndex: index + 1
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (remainder.length > 0) contentParts.push(remainder);
|
||||||
|
index += 1;
|
||||||
|
if (index >= lines.length) return null;
|
||||||
|
remainder = lines[index];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryParseQuoteBlock(lines: string[], startIndex: number): ParsedCommentBlock | null {
|
||||||
|
if (!lines[startIndex].startsWith('>')) return null;
|
||||||
|
|
||||||
|
const quoteLines: string[] = [];
|
||||||
|
let index = startIndex;
|
||||||
|
|
||||||
|
while (index < lines.length && lines[index].startsWith('>')) {
|
||||||
|
quoteLines.push(parseInlineElements(lines[index].replace(/^>\s?/, '')));
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
html: `<blockquote class="border-l-4 border-neutral-600 pl-3 my-2 text-neutral-400 italic">${quoteLines.join('<br />')}</blockquote>`,
|
||||||
|
nextIndex: index
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCodeBlock(code: string): string {
|
||||||
|
return `<pre class="my-2 overflow-x-auto rounded bg-neutral-900 p-2"><code class="font-mono text-sm text-neutral-100">${escapeHtml(code)}</code></pre>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeCommentLink(rawUrl: string): string | null {
|
||||||
|
const url = rawUrl.trim();
|
||||||
|
if (url.length === 0) return null;
|
||||||
|
if (url.startsWith('/')) return url;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = new URL(url);
|
||||||
|
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
|
||||||
|
return parsed.toString();
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseInlineElements(text: string): string {
|
||||||
|
const inlinePattern =
|
||||||
|
/```([\s\S]*?)```|\*\*\*([^*\n]+)\*\*\*|\*\*([^*\n]+)\*\*|\*([^*\n]+)\*|`([^`\n]+)`|\[([^\]\n]+)\]\(([^)\n]+)\)|@([a-zA-Z0-9_-]+)/g;
|
||||||
|
|
||||||
|
let output = '';
|
||||||
|
let lastIndex = 0;
|
||||||
|
|
||||||
|
for (const match of text.matchAll(inlinePattern)) {
|
||||||
|
const index = match.index ?? 0;
|
||||||
|
output += escapeHtml(text.slice(lastIndex, index));
|
||||||
|
|
||||||
|
if (match[1] !== undefined) {
|
||||||
|
output += renderCodeBlock(match[1]);
|
||||||
|
} else if (match[2] !== undefined) {
|
||||||
|
output += `<strong class="font-bold"><em class="italic">${escapeHtml(match[2])}</em></strong>`;
|
||||||
|
} else if (match[3] !== undefined) {
|
||||||
|
output += `<strong class="font-bold">${escapeHtml(match[3])}</strong>`;
|
||||||
|
} else if (match[4] !== undefined) {
|
||||||
|
output += `<em class="italic">${escapeHtml(match[4])}</em>`;
|
||||||
|
} else if (match[5] !== undefined) {
|
||||||
|
output += `<code class="bg-neutral-800 px-1 py-0.5 rounded text-neutral-100 font-mono text-sm">${escapeHtml(match[5])}</code>`;
|
||||||
|
} else if (match[6] !== undefined && match[7] !== undefined) {
|
||||||
|
const safeUrl = normalizeCommentLink(match[7]);
|
||||||
|
if (safeUrl) {
|
||||||
|
output += `<a href="${escapeHtml(safeUrl)}" class="text-blue-400 hover:underline" target="_blank" rel="noopener noreferrer">${escapeHtml(match[6])}</a>`;
|
||||||
|
} else {
|
||||||
|
output += escapeHtml(match[0]);
|
||||||
|
}
|
||||||
|
} else if (match[8] !== undefined) {
|
||||||
|
const username = match[8];
|
||||||
|
output += `<a href="/user/${encodeURIComponent(username)}" class="text-blue-400 hover:underline">@${escapeHtml(username)}</a>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
lastIndex = index + match[0].length;
|
||||||
|
}
|
||||||
|
|
||||||
|
output += escapeHtml(text.slice(lastIndex));
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
import { syntaxes } from '$lib/consts';
|
import { syntaxes } from '#lib/consts';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param bytes Bytes to format.
|
||||||
|
* @param decimals Number of decimal places to include for non-integer values. Defaults to 2.
|
||||||
|
* @returns A human readable string representing the byte size, e.g. "1.5 MB".
|
||||||
|
*/
|
||||||
export function formatBytes(bytes: number, decimals = 2): string {
|
export function formatBytes(bytes: number, decimals = 2): string {
|
||||||
if (bytes === 0) return '0 Bytes';
|
if (bytes === 0) return '0 Bytes';
|
||||||
|
|
||||||
@@ -15,6 +20,10 @@ export function formatBytes(bytes: number, decimals = 2): string {
|
|||||||
return `${formattedValue} ${unitLabel}`;
|
return `${formattedValue} ${unitLabel}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param num The number to format with commas as thousand separators.
|
||||||
|
* @returns The formatted number as a string with commas. For example, 1234567 becomes "1,234,567".
|
||||||
|
*/
|
||||||
export function formatNumber(num: number): string {
|
export function formatNumber(num: number): string {
|
||||||
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||||
}
|
}
|
||||||
@@ -61,13 +70,21 @@ export function extractError(resData: unknown): string | null {
|
|||||||
export function syntaxFromExtension(extension: string): string | null {
|
export function syntaxFromExtension(extension: string): string | null {
|
||||||
const ext = extension.startsWith('.') ? extension.slice(1) : extension;
|
const ext = extension.startsWith('.') ? extension.slice(1) : extension;
|
||||||
for (const [key, value] of Object.entries(syntaxes)) {
|
for (const [key, value] of Object.entries(syntaxes)) {
|
||||||
if (value.extension === `.${ext}`) {
|
if (value.extension.toLowerCase() === ext.toLowerCase()) {
|
||||||
return key;
|
return key;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param date The date to compare to the current time.
|
||||||
|
* @param useSuffix Whether to include "ago" or "from now" suffixes. Defaults to true.
|
||||||
|
* @param full Whether to return a full breakdown of all time units (e.g. "1 year, 2 months, 3 days ago") or just the largest unit (e.g. "1 year ago"). Defaults to false.
|
||||||
|
* @param nowArg Optional date to use as the current time for comparison, useful for testing. Defaults to the actual current time.
|
||||||
|
* @param accuracy The maximum number of time units to include in the output when full is true. For example, with an accuracy of 2, you might get "1 year, 2 months ago" but not "1 year, 2 months, 3 days ago". Defaults to 1.
|
||||||
|
* @returns A human readable relative time string.
|
||||||
|
*/
|
||||||
export function dateToRelativeString(
|
export function dateToRelativeString(
|
||||||
date: Date,
|
date: Date,
|
||||||
useSuffix = true,
|
useSuffix = true,
|
||||||
@@ -96,7 +113,7 @@ export function dateToRelativeString(
|
|||||||
return `${count} ${unit.name}${count > 1 ? 's' : ''} ${suffix}`.trim();
|
return `${count} ${unit.name}${count > 1 ? 's' : ''} ${suffix}`.trim();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return `0 seconds ${suffix}`.trim();
|
return useSuffix ? 'just now' : '0 seconds';
|
||||||
}
|
}
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
let acc = 0;
|
let acc = 0;
|
||||||
@@ -109,10 +126,18 @@ export function dateToRelativeString(
|
|||||||
acc++;
|
acc++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (parts.length === 0) parts.push('0 seconds');
|
if (parts.length === 0) return useSuffix ? 'just now' : '0 seconds';
|
||||||
return `${parts.join(', ')} ${suffix}`.trim();
|
return `${parts.join(', ')} ${suffix}`.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param node The HTML element to attach the tooltip to.
|
||||||
|
* @param params The tooltip text, or an array where the first element is the tooltip text and the second element is a boolean indicating whether to use a darker background for the tooltip.
|
||||||
|
* @returns An object with update and destroy methods to manage the tooltip lifecycle.
|
||||||
|
* @example
|
||||||
|
* <button use:tooltip="This is a tooltip">Hover me</button>
|
||||||
|
* <button use:tooltip={["This is a darker tooltip", true]}>Hover me</button>
|
||||||
|
*/
|
||||||
export function tooltip(node: HTMLElement, params: string | [string, boolean?]) {
|
export function tooltip(node: HTMLElement, params: string | [string, boolean?]) {
|
||||||
let currentText = typeof params === 'string' ? params : (params[0] ?? '');
|
let currentText = typeof params === 'string' ? params : (params[0] ?? '');
|
||||||
let darker = typeof params === 'string' ? false : (params[1] ?? false);
|
let darker = typeof params === 'string' ? false : (params[1] ?? false);
|
||||||
|
|||||||
@@ -9,10 +9,3 @@ export function parseTotpEnabled(tokenValue: string | null) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number[], nextRoles: number[]) {
|
|
||||||
if (!totpEnabled) return false;
|
|
||||||
const nextHasAdmin = nextRoles.includes(255);
|
|
||||||
const alreadyAdmin = currentRoles.includes(255);
|
|
||||||
return nextHasAdmin && !alreadyAdmin;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import hljs from 'highlight.js';
|
import hljs from 'highlight.js';
|
||||||
|
import { escapeHtml } from '../utils/html';
|
||||||
|
|
||||||
type HighlightRequest = {
|
type HighlightRequest = {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -11,9 +12,6 @@ type HighlightResponse = {
|
|||||||
html: string;
|
html: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const escapeHtml = (value: string) =>
|
|
||||||
value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
||||||
|
|
||||||
self.onmessage = (event: MessageEvent<HighlightRequest>) => {
|
self.onmessage = (event: MessageEvent<HighlightRequest>) => {
|
||||||
const { id, code, lang } = event.data;
|
const { id, code, lang } = event.data;
|
||||||
let html = '';
|
let html = '';
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import type { LayoutServerLoad } from './$types';
|
import type { LayoutServerLoad } from './$types';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const load: LayoutServerLoad = async ({ fetch, url }) => {
|
export const load: LayoutServerLoad = async ({ fetch, url }) => {
|
||||||
try {
|
const res = await fetch('/api/auth/info');
|
||||||
const res = await fetch('/api/auth/info');
|
const pasteOptionsRes = await fetch('/api/paste/info');
|
||||||
const pasteOptionsRes = await fetch('/api/paste/info');
|
|
||||||
const options = await res.json();
|
if (!res.ok || !pasteOptionsRes.ok) {
|
||||||
const pasteOptions = await pasteOptionsRes.json();
|
throw error(503, 'Failed to load site configuration.');
|
||||||
return { options, pasteOptions, url: url.href };
|
|
||||||
} catch {
|
|
||||||
return { options: null, pasteOptions: null, url: url.href };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const options = await res.json();
|
||||||
|
const pasteOptions = await pasteOptionsRes.json();
|
||||||
|
return { options, pasteOptions, url: url.href };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,17 +1,53 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import './layout.css';
|
import './layout.css';
|
||||||
import favicon from '$lib/assets/favicon.svg';
|
import favicon from '#lib/assets/favicon.svg';
|
||||||
import Navbar from '$lib/components/Navbar.svelte';
|
import Navbar from '#lib/components/Navbar.svelte';
|
||||||
import Footer from '$lib/components/Footer.svelte';
|
import Footer from '#lib/components/Footer.svelte';
|
||||||
import ModalHost from '$lib/components/ModalHost.svelte';
|
import ModalHost from '#lib/components/ModalHost.svelte';
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '#lib/stores/user';
|
||||||
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
|
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '#lib/utils/auth';
|
||||||
import { parseTotpEnabled } from '$lib/utils/totp';
|
import { parseTotpEnabled } from '#lib/utils/totp';
|
||||||
import { page } from '$app/state';
|
import { page } from '$app/state';
|
||||||
import type { LayoutData } from './$types';
|
import type { LayoutData } from './$types';
|
||||||
|
|
||||||
export let data: LayoutData;
|
interface Props {
|
||||||
|
data: LayoutData;
|
||||||
|
children?: import('svelte').Snippet;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { data, children }: Props = $props();
|
||||||
|
|
||||||
|
async function syncUserFromToken() {
|
||||||
|
const token = getToken();
|
||||||
|
if (!token) {
|
||||||
|
user.set(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/user/me', {
|
||||||
|
headers: { Authorization: `Bearer ${token}` }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
if (res.status === 401 || res.status === 403) {
|
||||||
|
user.set(null);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const me = await res.json();
|
||||||
|
let userData = me;
|
||||||
|
if (me && 'user' in me && typeof me.user === 'object') {
|
||||||
|
const { user: nestedUser, ...rest } = me;
|
||||||
|
userData = { ...rest, ...nestedUser };
|
||||||
|
}
|
||||||
|
user.set({ ...userData, totpEnabled: parseTotpEnabled(getToken()) });
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
startTokenRefreshInterval();
|
startTokenRefreshInterval();
|
||||||
@@ -20,35 +56,49 @@
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(async () => {
|
onMount(() => {
|
||||||
await refreshTokenIfNeeded();
|
const refreshAndSync = async () => {
|
||||||
const token = getToken();
|
await refreshTokenIfNeeded();
|
||||||
if (!token) {
|
await syncUserFromToken();
|
||||||
user.set(null);
|
};
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const res = await fetch('/api/user/me', {
|
const handleFocus = () => {
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
void refreshAndSync();
|
||||||
});
|
};
|
||||||
|
|
||||||
if (res.ok) {
|
const handleVisibilityChange = () => {
|
||||||
const me = await res.json();
|
if (document.visibilityState === 'visible') {
|
||||||
let userData = me;
|
void refreshAndSync();
|
||||||
if (me && 'user' in me && typeof me.user === 'object') {
|
|
||||||
const { user: nestedUser, ...rest } = me;
|
|
||||||
userData = { ...rest, ...nestedUser };
|
|
||||||
}
|
}
|
||||||
user.set({ ...userData, totpEnabled: parseTotpEnabled(getToken()) });
|
};
|
||||||
} else {
|
|
||||||
|
const handleTokensUpdated = () => {
|
||||||
|
void syncUserFromToken();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleTokensCleared = () => {
|
||||||
user.set(null);
|
user.set(null);
|
||||||
}
|
};
|
||||||
|
|
||||||
|
void refreshAndSync();
|
||||||
|
|
||||||
|
window.addEventListener('focus', handleFocus);
|
||||||
|
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||||
|
window.addEventListener('auth:tokens-updated', handleTokensUpdated);
|
||||||
|
window.addEventListener('auth:tokens-cleared', handleTokensCleared);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('focus', handleFocus);
|
||||||
|
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||||
|
window.removeEventListener('auth:tokens-updated', handleTokensUpdated);
|
||||||
|
window.removeEventListener('auth:tokens-cleared', handleTokensCleared);
|
||||||
|
};
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
<link rel="icon" href={favicon} />
|
<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
|
<script
|
||||||
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
|
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
|
||||||
async
|
async
|
||||||
@@ -58,7 +108,7 @@
|
|||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<Navbar {data} />
|
<Navbar {data} />
|
||||||
<slot />
|
{@render children?.()}
|
||||||
<Footer />
|
<Footer />
|
||||||
|
|
||||||
<ModalHost />
|
<ModalHost />
|
||||||
|
|||||||
@@ -1,54 +1,64 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
import { syntaxes, expiresOptions } from '$lib/consts';
|
import { syntaxes, expiresOptions } from '#lib/consts';
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '#lib/stores/user';
|
||||||
import { getToken } from '$lib/utils/auth';
|
import { getToken } from '#lib/utils/auth';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { fly, fade } from 'svelte/transition';
|
import { fly, fade } from 'svelte/transition';
|
||||||
import { encryptAES, estimateEncryptedSize } from '$lib/utils/encryption';
|
import { encryptAES, estimateEncryptedSize } from '#lib/utils/encryption';
|
||||||
import {
|
import {
|
||||||
formatBytes,
|
formatBytes,
|
||||||
formatNumber,
|
formatNumber,
|
||||||
isBinaryData,
|
isBinaryData,
|
||||||
tooltip,
|
tooltip,
|
||||||
syntaxFromExtension
|
syntaxFromExtension
|
||||||
} from '$lib/utils/misc';
|
} from '#lib/utils/misc';
|
||||||
import { parseMarkdown } from '$lib/utils/markdown';
|
import { parseMarkdown } from '#lib/utils/markdown';
|
||||||
import Dropdown from '$lib/components/Dropdown.svelte';
|
import Dropdown from '#lib/components/Dropdown.svelte';
|
||||||
import { SvelteURLSearchParams } from 'svelte/reactivity';
|
import { SvelteURLSearchParams } from 'svelte/reactivity';
|
||||||
import { FileUp, X, Eye, EyeClosed, Dices } from '@lucide/svelte';
|
import { FileUp, X, Eye, EyeClosed, Dices } from '@lucide/svelte';
|
||||||
|
|
||||||
export let data: PageData;
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
let textArea: HTMLTextAreaElement;
|
let { data }: Props = $props();
|
||||||
let markdownConatiner: HTMLDivElement;
|
|
||||||
|
|
||||||
let error = '';
|
let textArea = $state<HTMLTextAreaElement | undefined>(undefined);
|
||||||
let title = '';
|
let markdownConatiner = $state<HTMLDivElement | undefined>(undefined);
|
||||||
let content = '';
|
|
||||||
let selectedSyntax = data.options?.syntaxes?.[0];
|
|
||||||
let expiresIn: number = 0;
|
|
||||||
let selectedVisibility = data.options?.visibilities?.[0]?.value;
|
|
||||||
let password = '';
|
|
||||||
let passwordVisible = false;
|
|
||||||
let anonymousUpload = false;
|
|
||||||
let isDragging = false;
|
|
||||||
let dragError = '';
|
|
||||||
let previewMode = false;
|
|
||||||
let renderedMarkdown = '';
|
|
||||||
|
|
||||||
$: currentByteSize =
|
const getInitialSyntax = () => data.options?.syntaxes?.[0] ?? 'plaintext';
|
||||||
|
const getInitialVisibility = () => data.options?.visibilities?.[0]?.value ?? 0;
|
||||||
|
|
||||||
|
let error = $state('');
|
||||||
|
let title = $state('');
|
||||||
|
let content = $state('');
|
||||||
|
let selectedSyntax = $state(getInitialSyntax());
|
||||||
|
let expiresIn: number = $state(0);
|
||||||
|
let selectedVisibility = $state(getInitialVisibility());
|
||||||
|
let password = $state('');
|
||||||
|
let passwordVisible = $state(false);
|
||||||
|
let anonymousUpload = $state(false);
|
||||||
|
let isDragging = $state(false);
|
||||||
|
let dragError = $state('');
|
||||||
|
let previewMode = $state(false);
|
||||||
|
let renderedMarkdown = $state('');
|
||||||
|
|
||||||
|
let currentByteSize = $derived(
|
||||||
selectedVisibility === 2
|
selectedVisibility === 2
|
||||||
? estimateEncryptedSize(content)
|
? estimateEncryptedSize(content)
|
||||||
: new TextEncoder().encode(content).length;
|
: new TextEncoder().encode(content).length
|
||||||
|
);
|
||||||
|
|
||||||
$: if (selectedSyntax !== 'markdown') {
|
$effect(() => {
|
||||||
previewMode = false;
|
if (selectedSyntax !== 'markdown') {
|
||||||
}
|
previewMode = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const MAX_HEIGHT = () => Math.floor((window.innerHeight - 120) * 0.6);
|
const MAX_HEIGHT = () => Math.floor((window.innerHeight - 120) * 0.6);
|
||||||
|
|
||||||
let previewHeight = 'auto';
|
let previewHeight = $state('auto');
|
||||||
async function togglePreview(toPreview: boolean) {
|
async function togglePreview(toPreview: boolean) {
|
||||||
if (toPreview && !previewMode) {
|
if (toPreview && !previewMode) {
|
||||||
previewHeight = textArea?.style.height || 'auto';
|
previewHeight = textArea?.style.height || 'auto';
|
||||||
@@ -59,11 +69,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function resize(markdown: boolean = false) {
|
function resize(markdown: boolean = false) {
|
||||||
if ((!markdown && !textArea) || (markdown && !markdownConatiner)) return;
|
const element = markdown ? markdownConatiner : textArea;
|
||||||
|
if (!element) return;
|
||||||
|
|
||||||
let h: number;
|
let h: number;
|
||||||
let max: number;
|
let max: number;
|
||||||
let element = markdown ? markdownConatiner : textArea;
|
|
||||||
|
|
||||||
element.style.height = 'auto';
|
element.style.height = 'auto';
|
||||||
h = element.scrollHeight;
|
h = element.scrollHeight;
|
||||||
@@ -106,17 +116,21 @@
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
const syntaxOptions =
|
let syntaxOptions = $derived.by(
|
||||||
data.options?.syntaxes?.map((lang: string) => ({
|
() =>
|
||||||
value: lang,
|
data.options?.syntaxes?.map((lang: string) => ({
|
||||||
label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1)
|
value: lang,
|
||||||
})) ?? [];
|
label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1)
|
||||||
|
})) ?? []
|
||||||
|
);
|
||||||
|
|
||||||
const visibilityOptions =
|
let visibilityOptions = $derived.by(
|
||||||
data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
|
() =>
|
||||||
value: visibility.value,
|
data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
|
||||||
label: visibility.displayName
|
value: visibility.value,
|
||||||
})) ?? [];
|
label: visibility.displayName
|
||||||
|
})) ?? []
|
||||||
|
);
|
||||||
|
|
||||||
async function handleSubmit(event: Event) {
|
async function handleSubmit(event: Event) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -132,9 +146,9 @@
|
|||||||
data.auth?.cf_turnstile_site_key &&
|
data.auth?.cf_turnstile_site_key &&
|
||||||
window.turnstile
|
window.turnstile
|
||||||
) {
|
) {
|
||||||
const token = window.turnstile.getResponse();
|
const verificationToken = window.turnstile.getResponse();
|
||||||
if (token) {
|
if (verificationToken) {
|
||||||
params.append('token', token);
|
params.append('verificationToken', verificationToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,11 +230,27 @@
|
|||||||
|
|
||||||
<svelte:head>
|
<svelte:head>
|
||||||
<title>Create a Paste - Sharpbin</title>
|
<title>Create a Paste - Sharpbin</title>
|
||||||
|
<meta
|
||||||
|
name="description"
|
||||||
|
content="Create and share code snippets, and text instantly with Sharpbin. Supports syntax highlighting, encryption, expiry, and more."
|
||||||
|
/>
|
||||||
|
<meta name="robots" content="index, follow" />
|
||||||
|
<link rel="canonical" href={data.url.split('/').slice(0, 3).join('/') + '/'} />
|
||||||
|
<!-- normalized to prevent duplicate content issues -google search console -->
|
||||||
<meta property="og:title" content="Create a Paste - Sharpbin" />
|
<meta property="og:title" content="Create a Paste - Sharpbin" />
|
||||||
<meta property="og:description" content="Create and share your pastes easily with Sharpbin." />
|
<meta
|
||||||
|
property="og:description"
|
||||||
|
content="Create and share code snippets, and text instantly with Sharpbin. Supports syntax highlighting, encryption, expiry, and more."
|
||||||
|
/>
|
||||||
<meta property="og:type" content="website" />
|
<meta property="og:type" content="website" />
|
||||||
<meta property="og:url" content={data.url} />
|
<meta property="og:url" content={data.url} />
|
||||||
<meta property="og:site_name" content="Sharpbin" />
|
<meta property="og:site_name" content="Sharpbin" />
|
||||||
|
<meta name="twitter:card" content="summary" />
|
||||||
|
<meta name="twitter:title" content="Create a Paste - Sharpbin" />
|
||||||
|
<meta
|
||||||
|
name="twitter:description"
|
||||||
|
content="Create and share code snippets, and text instantly with Sharpbin."
|
||||||
|
/>
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<main
|
<main
|
||||||
@@ -228,7 +258,7 @@
|
|||||||
>
|
>
|
||||||
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||||
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
|
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
|
||||||
<form class="mt-4" on:submit|preventDefault={handleSubmit}>
|
<form class="mt-4" onsubmit={handleSubmit}>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Title (optional)"
|
placeholder="Title (optional)"
|
||||||
@@ -258,10 +288,10 @@
|
|||||||
minlength="1"
|
minlength="1"
|
||||||
bind:this={textArea}
|
bind:this={textArea}
|
||||||
bind:value={content}
|
bind:value={content}
|
||||||
on:input={() => resize()}
|
oninput={() => resize()}
|
||||||
on:change={() => resize()}
|
onchange={() => resize()}
|
||||||
on:focus={() => resize()}
|
onfocus={() => resize()}
|
||||||
on:beforeinput={(e) => {
|
onbeforeinput={(e) => {
|
||||||
if (!data.options?.maxPasteSize) return;
|
if (!data.options?.maxPasteSize) return;
|
||||||
|
|
||||||
const futureSize =
|
const futureSize =
|
||||||
@@ -276,19 +306,19 @@
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
on:dragenter={(e) => {
|
ondragenter={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
isDragging = true;
|
isDragging = true;
|
||||||
}}
|
}}
|
||||||
on:dragover={(e) => {
|
ondragover={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
isDragging = true;
|
isDragging = true;
|
||||||
}}
|
}}
|
||||||
on:dragleave={(e) => {
|
ondragleave={(e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
isDragging = false;
|
isDragging = false;
|
||||||
}}
|
}}
|
||||||
on:drop={(e) => {
|
ondrop={(e) => {
|
||||||
requestAnimationFrame(() => resize());
|
requestAnimationFrame(() => resize());
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
isDragging = false;
|
isDragging = false;
|
||||||
@@ -360,7 +390,7 @@
|
|||||||
class="h-full w-1/2 rounded-l transition-colors {previewMode
|
class="h-full w-1/2 rounded-l transition-colors {previewMode
|
||||||
? 'hover:bg-neutral-700'
|
? 'hover:bg-neutral-700'
|
||||||
: 'bg-neutral-700 text-white'}"
|
: 'bg-neutral-700 text-white'}"
|
||||||
on:click={() => togglePreview(false)}
|
onclick={() => togglePreview(false)}
|
||||||
>
|
>
|
||||||
Code
|
Code
|
||||||
</button>
|
</button>
|
||||||
@@ -369,7 +399,7 @@
|
|||||||
class="h-full w-1/2 rounded-r transition-colors {!previewMode
|
class="h-full w-1/2 rounded-r transition-colors {!previewMode
|
||||||
? 'hover:bg-neutral-700'
|
? 'hover:bg-neutral-700'
|
||||||
: 'bg-neutral-700 text-white'}"
|
: 'bg-neutral-700 text-white'}"
|
||||||
on:click={() => togglePreview(true)}
|
onclick={() => togglePreview(true)}
|
||||||
>
|
>
|
||||||
Preview
|
Preview
|
||||||
</button>
|
</button>
|
||||||
@@ -433,20 +463,20 @@
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="mr-1 ml-1 flex w-12.5 items-center justify-center border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
|
class="mr-1 ml-1 flex w-12.5 items-center justify-center border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
|
||||||
on:click={() => {
|
onclick={() => {
|
||||||
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
||||||
const bytes = new Uint8Array(16);
|
const bytes = new Uint8Array(16);
|
||||||
crypto.getRandomValues(bytes);
|
crypto.getRandomValues(bytes);
|
||||||
password = Array.from(bytes, (b) => chars[b % chars.length]).join('');
|
password = Array.from(bytes, (b) => chars[b % chars.length]).join('');
|
||||||
}}
|
}}
|
||||||
use:tooltip={'Generate Random Password'}
|
use:tooltip={['Generate Random Password', true]}
|
||||||
>
|
>
|
||||||
<Dices class="h-5 w-5" />
|
<Dices class="h-5 w-5" />
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex w-12.5 items-center justify-center rounded-r border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
|
class="flex w-12.5 items-center justify-center rounded-r border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
|
||||||
on:click={() => (passwordVisible = !passwordVisible)}
|
onclick={() => (passwordVisible = !passwordVisible)}
|
||||||
>
|
>
|
||||||
{#if passwordVisible}
|
{#if passwordVisible}
|
||||||
<EyeClosed class="h-5 w-5" />
|
<EyeClosed class="h-5 w-5" />
|
||||||
@@ -473,7 +503,7 @@
|
|||||||
{/if}
|
{/if}
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={$user?.roles && $user.roles.includes(403)}
|
disabled={$user?.isBanned}
|
||||||
class="mb-2 w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
|
class="mb-2 w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
|
||||||
>Create Paste</button
|
>Create Paste</button
|
||||||
>
|
>
|
||||||
@@ -485,7 +515,7 @@
|
|||||||
{error}
|
{error}
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
{#if $user?.roles && $user.roles.includes(403)}
|
{#if $user?.isBanned}
|
||||||
<div
|
<div
|
||||||
transition:fly={{ y: 40, duration: 300 }}
|
transition:fly={{ y: 40, duration: 300 }}
|
||||||
class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
|
class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import { error, redirect } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export async function GET({ params }) {
|
||||||
|
const username = params?.username;
|
||||||
|
if (!username) throw error(404, 'User not found');
|
||||||
|
throw redirect(302, `/user/${encodeURIComponent(username)}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
import { syntaxes } from '#lib/consts';
|
||||||
|
import { apiUrl } from '#lib/server/api';
|
||||||
|
import {
|
||||||
|
getCachedOgImage,
|
||||||
|
getCacheControlHeader,
|
||||||
|
getCacheTtlSeconds,
|
||||||
|
scheduleOgImageCachePurge,
|
||||||
|
storeCachedOgImage
|
||||||
|
} from '#lib/server/og/cache';
|
||||||
|
import OgPasteEmbed from '#lib/server/og/PasteEmbed.svelte';
|
||||||
|
import type { PasteEmbedProps } from '#lib/server/og/pasteEmbed';
|
||||||
|
import type { Paste } from '#lib/types/paste';
|
||||||
|
import {
|
||||||
|
dateToRelativeString,
|
||||||
|
extractDateFromUUIDv7,
|
||||||
|
formatBytes,
|
||||||
|
formatNumber
|
||||||
|
} from '#lib/utils/misc';
|
||||||
|
import { Resvg } from '@resvg/resvg-js';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import satori from 'satori';
|
||||||
|
import { html } from 'satori-html';
|
||||||
|
import sharp from 'sharp';
|
||||||
|
import type { Component } from 'svelte';
|
||||||
|
import { render } from 'svelte/server';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
|
||||||
|
const WIDTH = 1200;
|
||||||
|
const HEIGHT = 630;
|
||||||
|
|
||||||
|
const require = createRequire(import.meta.url);
|
||||||
|
|
||||||
|
type FontConfig = {
|
||||||
|
name: string;
|
||||||
|
data: Buffer;
|
||||||
|
weight: 400 | 700;
|
||||||
|
style: 'normal';
|
||||||
|
};
|
||||||
|
|
||||||
|
type GeneratedImage = {
|
||||||
|
jpg: Buffer;
|
||||||
|
cacheControl: string;
|
||||||
|
};
|
||||||
|
const generationInFlight = new Map<string, Promise<GeneratedImage>>();
|
||||||
|
|
||||||
|
const visibilityLabels: Record<Paste['visibility'], string> = {
|
||||||
|
0: 'Public',
|
||||||
|
1: 'Unlisted',
|
||||||
|
2: 'Private'
|
||||||
|
};
|
||||||
|
|
||||||
|
const fontsPromise: Promise<FontConfig[]> = Promise.all([
|
||||||
|
readFile(require.resolve('@fontsource/inter/files/inter-latin-400-normal.woff')),
|
||||||
|
readFile(require.resolve('@fontsource/inter/files/inter-latin-700-normal.woff')),
|
||||||
|
readFile(require.resolve('@fontsource/jetbrains-mono/files/jetbrains-mono-latin-400-normal.woff'))
|
||||||
|
]).then(([inter400, inter700, mono400]) => [
|
||||||
|
{ name: 'Inter', data: inter400, weight: 400, style: 'normal' },
|
||||||
|
{ name: 'Inter', data: inter700, weight: 700, style: 'normal' },
|
||||||
|
{ name: 'JetBrains Mono', data: mono400, weight: 400, style: 'normal' }
|
||||||
|
]);
|
||||||
|
|
||||||
|
function getPreviewLines(content: string): string[] {
|
||||||
|
return content
|
||||||
|
.split('\n')
|
||||||
|
.slice(0, 15)
|
||||||
|
.map((line) => {
|
||||||
|
const normalized = line.replace(/\t/g, ' ');
|
||||||
|
return normalized.length > 86 ? `${normalized.slice(0, 83)}...` : normalized;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const entityMap: Record<string, string> = {
|
||||||
|
lt: '<',
|
||||||
|
gt: '>',
|
||||||
|
amp: '&',
|
||||||
|
quot: '"',
|
||||||
|
'#39': "'",
|
||||||
|
'#x27': "'"
|
||||||
|
};
|
||||||
|
|
||||||
|
// satori sanitizes html but doesnt render them properly (stays as < for example)
|
||||||
|
// so replace sanitized entities with the actual characters
|
||||||
|
function decodeHtmlEntities(value: string): string {
|
||||||
|
let output = value;
|
||||||
|
for (;;) {
|
||||||
|
const next = output.replace(
|
||||||
|
/&(lt|gt|amp|quot|#39|#x27);/g,
|
||||||
|
(_, entity: string) => entityMap[entity]
|
||||||
|
);
|
||||||
|
if (next === output) return next;
|
||||||
|
output = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeSatoriTextNodes(node: unknown): unknown {
|
||||||
|
if (typeof node === 'string') return decodeHtmlEntities(node);
|
||||||
|
if (Array.isArray(node)) return node.map(normalizeSatoriTextNodes);
|
||||||
|
if (!node || typeof node !== 'object') return node;
|
||||||
|
|
||||||
|
const props = (node as { props?: { children?: unknown } }).props;
|
||||||
|
if (props && 'children' in props) {
|
||||||
|
props.children = normalizeSatoriTextNodes(props.children);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (props && Array.isArray(props.children) && props.children.length === 0) {
|
||||||
|
delete (props as Record<string, unknown>).children;
|
||||||
|
}
|
||||||
|
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET: RequestHandler = async ({ params, fetch }) => {
|
||||||
|
const id = params.id;
|
||||||
|
if (!id) {
|
||||||
|
return new Response('Missing paste id.', { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleOgImageCachePurge();
|
||||||
|
|
||||||
|
const cachedImage = await getCachedOgImage(id);
|
||||||
|
if (cachedImage) {
|
||||||
|
return new Response(new Uint8Array(cachedImage.jpg), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'image/jpeg',
|
||||||
|
'Cache-Control': getCacheControlHeader(cachedImage.ttlSeconds)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingGeneration = generationInFlight.get(id);
|
||||||
|
if (existingGeneration) {
|
||||||
|
const generated = await existingGeneration;
|
||||||
|
return new Response(new Uint8Array(generated.jpg), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'image/jpeg',
|
||||||
|
'Cache-Control': generated.cacheControl
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const generation = (async (): Promise<GeneratedImage> => {
|
||||||
|
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`);
|
||||||
|
if (!pasteRes.ok) {
|
||||||
|
throw new Response('Paste not found.', { status: pasteRes.status === 404 ? 404 : 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const pasteData = (await pasteRes.json()) as { paste?: Paste };
|
||||||
|
const paste = pasteData.paste;
|
||||||
|
if (!paste) {
|
||||||
|
throw new Response('Invalid paste response.', { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const isEncrypted = paste.visibility === 2;
|
||||||
|
let rawContent = '';
|
||||||
|
if (!isEncrypted) {
|
||||||
|
const rawRes = await fetch(`${apiUrl}/api/paste/${id}/raw`);
|
||||||
|
rawContent = rawRes.ok ? await rawRes.text() : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = rawContent || 'No content available.';
|
||||||
|
const created = paste.createdAt ? new Date(paste.createdAt) : extractDateFromUUIDv7(paste.uuid);
|
||||||
|
const metadata: PasteEmbedProps['metadata'] = [
|
||||||
|
{ icon: 'size', value: formatBytes(paste.originalSize) },
|
||||||
|
{
|
||||||
|
icon: 'views',
|
||||||
|
value: `${formatNumber(paste.views)} view${paste.views === 1 ? '' : 's'}`
|
||||||
|
},
|
||||||
|
{ icon: 'created', value: created ? created.toLocaleDateString() : 'Unknown' },
|
||||||
|
...(paste.expiresAt
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
icon: 'expires' as const,
|
||||||
|
value: `Expires in ${dateToRelativeString(new Date(paste.expiresAt), false)}`
|
||||||
|
}
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
{ icon: 'syntax', value: syntaxes[paste.syntax]?.name ?? paste.syntax },
|
||||||
|
{ icon: `visibility-${paste.visibility}`, value: visibilityLabels[paste.visibility] }
|
||||||
|
];
|
||||||
|
const props: PasteEmbedProps = {
|
||||||
|
title: paste.title?.trim() || 'Untitled Paste',
|
||||||
|
uploader: paste.author?.username ?? 'Anonymous Uploader',
|
||||||
|
metadata,
|
||||||
|
previewLines: isEncrypted ? [] : getPreviewLines(content),
|
||||||
|
isEncrypted
|
||||||
|
};
|
||||||
|
|
||||||
|
const fonts = await fontsPromise;
|
||||||
|
const markup = render(OgPasteEmbed as unknown as Component<PasteEmbedProps>, { props }).body;
|
||||||
|
const satoriNode = normalizeSatoriTextNodes(html(markup));
|
||||||
|
const svg = await satori(satoriNode, { width: WIDTH, height: HEIGHT, fonts });
|
||||||
|
const png = new Resvg(svg, { fitTo: { mode: 'width', value: WIDTH } }).render().asPng();
|
||||||
|
const jpg = await sharp(png).jpeg({ quality: 92, mozjpeg: true }).toBuffer();
|
||||||
|
|
||||||
|
const cacheTtlSeconds = getCacheTtlSeconds(paste.expiresAt);
|
||||||
|
const cacheControl = getCacheControlHeader(cacheTtlSeconds);
|
||||||
|
await storeCachedOgImage({ id, jpg, pasteExpiresAt: paste.expiresAt ?? null }).catch(
|
||||||
|
() => undefined
|
||||||
|
);
|
||||||
|
|
||||||
|
return { jpg, cacheControl };
|
||||||
|
})();
|
||||||
|
|
||||||
|
generationInFlight.set(id, generation);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const generated = await generation;
|
||||||
|
return new Response(new Uint8Array(generated.jpg), {
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'image/jpeg',
|
||||||
|
'Cache-Control': generated.cacheControl
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Response) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
generationInFlight.delete(id);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,37 +1,34 @@
|
|||||||
import type { PageServerLoad } from './$types';
|
import type { PageServerLoad } from './$types';
|
||||||
import type { Paste } from '$lib/types/paste';
|
import type { Paste } from '#lib/types/paste';
|
||||||
import { getServerToken } from '$lib/utils/auth';
|
import type { PasteComment } from '#lib/types/comment';
|
||||||
import { env } from '$env/dynamic/private';
|
import { getServerToken } from '#lib/utils/auth';
|
||||||
|
import { apiUrl, viewInternalApiKey } from '#lib/server/api';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
|
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent, request }) => {
|
||||||
const apiKey =
|
|
||||||
env.NODE_ENV === 'development'
|
|
||||||
? 'cccdd42d9f2f648493e402f1da7c855ea798ad510e6bb9ea712dd7bed838e58'
|
|
||||||
: (env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '');
|
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent }) => {
|
|
||||||
const { id } = params;
|
const { id } = params;
|
||||||
|
if (!id) {
|
||||||
|
// realistically this shouldnt happen
|
||||||
|
throw error(400, 'Missing paste id.');
|
||||||
|
}
|
||||||
const parentData = await parent().catch(() => null);
|
const parentData = await parent().catch(() => null);
|
||||||
|
|
||||||
const token = getServerToken(cookies);
|
const token = getServerToken(cookies);
|
||||||
|
const userAgent = request.headers.get('user-agent') ?? 'Sharpbin Client';
|
||||||
|
const clientHeaders = new Headers(request.headers);
|
||||||
|
clientHeaders.set('Authorization', token ? `Bearer ${token}` : '');
|
||||||
|
clientHeaders.set('User-Agent', userAgent);
|
||||||
|
|
||||||
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, {
|
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, { headers: clientHeaders });
|
||||||
headers: {
|
|
||||||
Authorization: token ? `Bearer ${token}` : ''
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (pasteRes.status === 404) {
|
if (pasteRes.status === 404) {
|
||||||
throw error(pasteRes.status, 'Paste not found.');
|
throw error(pasteRes.status, 'Paste not found.');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const viewedHeaders = new Headers(clientHeaders);
|
||||||
|
viewedHeaders.set('X-Internal-API-Key', viewInternalApiKey);
|
||||||
const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, {
|
const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: viewedHeaders
|
||||||
'X-Internal-API-Key': apiKey,
|
|
||||||
Authorization: token ? `Bearer ${token}` : ''
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const pasteData = await pasteRes.json();
|
const pasteData = await pasteRes.json();
|
||||||
@@ -39,28 +36,33 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent
|
|||||||
|
|
||||||
if (viewed.status === 200) {
|
if (viewed.status === 200) {
|
||||||
const viewJson = await viewed.json();
|
const viewJson = await viewed.json();
|
||||||
if (viewJson.success === true && viewJson.message !== 'View already recorded.') {
|
if (viewJson.success === true && viewJson.message === 'Paste view recorded.') {
|
||||||
pasteData.views += 1;
|
pasteData.views += 1;
|
||||||
}
|
}
|
||||||
} else {
|
} else if (viewInternalApiKey === '') {
|
||||||
console.error(
|
console.error(
|
||||||
`Failed to increment view count for paste ${id}, status code ${viewed.status}: ${await viewed.text()}`
|
'The API key for internal requests is not set. Please configure it in the environment variables.'
|
||||||
);
|
);
|
||||||
if (apiKey === '') {
|
|
||||||
console.error(
|
|
||||||
'The API key for internal requests is not set. Please configure it in the environment variables.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const pasteContent = await fetch(`/api/paste/${id}/raw`);
|
const pasteContent = await fetch(`${apiUrl}/api/paste/${id}/raw`, { headers: clientHeaders });
|
||||||
const pasteOptions = await fetch('/api/paste/info');
|
const pasteOptions = await fetch(`${apiUrl}/api/paste/info`, { headers: clientHeaders });
|
||||||
|
const commentsRes = await fetch(`${apiUrl}/api/paste/${id}/comments`, { headers: clientHeaders });
|
||||||
const options = await pasteOptions.json();
|
const options = await pasteOptions.json();
|
||||||
const content = await pasteContent.text();
|
const content = await pasteContent.text();
|
||||||
|
let comments: PasteComment[] = [];
|
||||||
|
|
||||||
|
if (commentsRes.ok) {
|
||||||
|
const commentsJson = await commentsRes.json().catch(() => ({}));
|
||||||
|
comments = Array.isArray(commentsJson?.comments)
|
||||||
|
? (commentsJson.comments as PasteComment[])
|
||||||
|
: [];
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
paste,
|
paste,
|
||||||
content,
|
content,
|
||||||
|
comments,
|
||||||
options,
|
options,
|
||||||
authOptions:
|
authOptions:
|
||||||
parentData && typeof parentData === 'object' && parentData !== null && 'options' in parentData
|
parentData && typeof parentData === 'object' && parentData !== null && 'options' in parentData
|
||||||
|
|||||||
@@ -23,7 +23,11 @@
|
|||||||
Check,
|
Check,
|
||||||
CalendarCog,
|
CalendarCog,
|
||||||
Flag,
|
Flag,
|
||||||
ArrowUp
|
ArrowUp,
|
||||||
|
HatGlasses,
|
||||||
|
MessageCircle,
|
||||||
|
ThumbsUp,
|
||||||
|
ThumbsDown
|
||||||
} from '@lucide/svelte/icons/index';
|
} from '@lucide/svelte/icons/index';
|
||||||
import {
|
import {
|
||||||
formatBytes,
|
formatBytes,
|
||||||
@@ -32,44 +36,82 @@
|
|||||||
dateToRelativeString,
|
dateToRelativeString,
|
||||||
tooltip,
|
tooltip,
|
||||||
isBinaryData
|
isBinaryData
|
||||||
} from '$lib/utils/misc';
|
} from '#lib/utils/misc';
|
||||||
import { parseMarkdown } from '$lib/utils/markdown';
|
import {
|
||||||
import { syntaxes, expiresOptions } from '$lib/consts';
|
getIgnoreExternalMediaWarning,
|
||||||
|
parseMarkdown,
|
||||||
|
setIgnoreExternalMediaWarning
|
||||||
|
} from '#lib/utils/markdown';
|
||||||
|
import { syntaxes, expiresOptions } from '#lib/consts';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { decryptAES, encryptAES } from '$lib/utils/encryption';
|
import { decryptAES, encryptAES } from '#lib/utils/encryption';
|
||||||
|
import { escapeHtml } from '#lib/utils/html';
|
||||||
import { fade } from 'svelte/transition';
|
import { fade } from 'svelte/transition';
|
||||||
import { getToken } from '$lib/utils/auth';
|
import { getToken, hasRole } from '#lib/utils/auth';
|
||||||
import { user } from '$lib/stores/user';
|
import { user } from '#lib/stores/user';
|
||||||
import Dropdown from '$lib/components/Dropdown.svelte';
|
import Dropdown from '#lib/components/Dropdown.svelte';
|
||||||
import { openModal } from '$lib/stores/modal';
|
import PasteComments from '#lib/components/PasteComments.svelte';
|
||||||
import type { Paste } from '$lib/types/paste';
|
import { openModal } from '#lib/stores/modal';
|
||||||
import HighlightWorker from '$lib/workers/highlight.worker?worker';
|
import type { Paste, PasteReaction } from '#lib/types/paste';
|
||||||
export let data: PageData;
|
import HighlightWorker from '#lib/workers/highlight.worker?worker';
|
||||||
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
let reportSiteKey: string | null = null;
|
let { data = $bindable() }: Props = $props();
|
||||||
let editing = false;
|
|
||||||
let editContent: string | null = null;
|
function updatePasteState(patch: Partial<Paste>) {
|
||||||
let editMetadata: Paste | null = data.paste ? { ...data.paste } : null;
|
if (!data?.paste) return;
|
||||||
let editError = '';
|
data = {
|
||||||
let editLoading = false;
|
...data,
|
||||||
let isBinary = false;
|
paste: {
|
||||||
let pasteContent = '';
|
...data.paste,
|
||||||
let decryptedContent: string | null = null;
|
...patch
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function updatePageContent(content: string) {
|
||||||
|
data = {
|
||||||
|
...data,
|
||||||
|
content
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let reportSiteKey = $derived(
|
||||||
|
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
|
||||||
|
?.cf_turnstile_site_key ?? null
|
||||||
|
);
|
||||||
|
let editing = $state(false);
|
||||||
|
let editContent: string | null = $state(null);
|
||||||
|
let editMetadata: Paste | null = $state(data.paste ? { ...data.paste } : null);
|
||||||
|
let editError = $state('');
|
||||||
|
let editLoading = $state(false);
|
||||||
|
let isBinary = $state(false);
|
||||||
|
let pasteContent = $state('');
|
||||||
|
let decryptedContent: string | null = $state(null);
|
||||||
let decryptError = '';
|
let decryptError = '';
|
||||||
let decryptStatus = '';
|
let decryptStatus = $state('');
|
||||||
let contentRendered = false;
|
let contentRendered = $state(false);
|
||||||
let downloadedPaste = false;
|
let downloadedPaste = $state(false);
|
||||||
let copiedPaste = false;
|
let copiedPaste = $state(false);
|
||||||
|
let reactingToPaste = $state(false);
|
||||||
let highlightWorker: Worker | null = null;
|
let highlightWorker: Worker | null = null;
|
||||||
let highlightRequestId = 0;
|
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 = 0;
|
let scrollY = $state(0);
|
||||||
|
|
||||||
let now = new Date();
|
let now = $state(new Date());
|
||||||
$: isExpired =
|
let isExpired = $derived(
|
||||||
data?.paste?.expiresAt && data.paste.expiresAt !== 0
|
data?.paste?.expiresAt && data.paste.expiresAt !== 0
|
||||||
? new Date(data.paste.expiresAt).getTime() <= now.getTime()
|
? new Date(data.paste.expiresAt).getTime() <= now.getTime()
|
||||||
: false;
|
: false
|
||||||
|
);
|
||||||
|
|
||||||
let interval: ReturnType<typeof setInterval> | null = null;
|
let interval: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
@@ -112,7 +154,7 @@
|
|||||||
const numbered = lines
|
const numbered = lines
|
||||||
.map(
|
.map(
|
||||||
(line, i) =>
|
(line, i) =>
|
||||||
`<div class="code-row"><span class="line-number" style="width:${digits}ch">${i + 1}</span><span class="code-line">${line}</span></div>`
|
`<div class="code-row"><span class="line-number" style="--digits:${digits}">${i + 1}</span><span class="code-line">${line}</span></div>`
|
||||||
)
|
)
|
||||||
.join('');
|
.join('');
|
||||||
return html.replace(code, numbered);
|
return html.replace(code, numbered);
|
||||||
@@ -132,7 +174,7 @@
|
|||||||
|
|
||||||
switch (data.paste.syntax) {
|
switch (data.paste.syntax) {
|
||||||
case 'markdown':
|
case 'markdown':
|
||||||
pasteContent = await parseMarkdown(contentToRender);
|
pasteContent = await parseMarkdown(contentToRender, !ignoreExternalMediaWarning);
|
||||||
contentRendered = true;
|
contentRendered = true;
|
||||||
decryptStatus = '';
|
decryptStatus = '';
|
||||||
break;
|
break;
|
||||||
@@ -167,8 +209,6 @@
|
|||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
if (lang === 'plaintext') {
|
if (lang === 'plaintext') {
|
||||||
const escapeHtml = (s: string) =>
|
|
||||||
s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
||||||
highlighted = escapeHtml(code);
|
highlighted = escapeHtml(code);
|
||||||
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
|
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
|
||||||
highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
|
highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
|
||||||
@@ -177,8 +217,6 @@
|
|||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
if (lang === 'plaintext') {
|
if (lang === 'plaintext') {
|
||||||
const escapeHtml = (s: string) =>
|
|
||||||
s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
||||||
highlighted = escapeHtml(code);
|
highlighted = escapeHtml(code);
|
||||||
} else {
|
} else {
|
||||||
highlighted = hljs.highlightAuto(code).value;
|
highlighted = hljs.highlightAuto(code).value;
|
||||||
@@ -209,19 +247,18 @@
|
|||||||
const rows = results.data as string[][];
|
const rows = results.data as string[][];
|
||||||
const [header, ...body] = rows;
|
const [header, ...body] = rows;
|
||||||
|
|
||||||
const escape = (v: string) =>
|
|
||||||
v.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
||||||
|
|
||||||
const tableHtml = `
|
const tableHtml = `
|
||||||
<table class="csv-table">
|
<table class="csv-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
${header.map((c) => `<th>${c ? escape(c) : ''}</th>`).join('')}
|
${header.map((c) => `<th>${c ? escapeHtml(c) : ''}</th>`).join('')}
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
${body
|
${body
|
||||||
.map((row) => `<tr>${row.map((c) => `<td>${c ? escape(c) : ''}</td>`).join('')}</tr>`)
|
.map(
|
||||||
|
(row) => `<tr>${row.map((c) => `<td>${c ? escapeHtml(c) : ''}</td>`).join('')}</tr>`
|
||||||
|
)
|
||||||
.join('')}
|
.join('')}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -283,7 +320,7 @@
|
|||||||
editLoading = false;
|
editLoading = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
data.content = rawContent;
|
updatePageContent(rawContent);
|
||||||
decryptedContent = rawContent;
|
decryptedContent = rawContent;
|
||||||
await renderPaste(rawContent);
|
await renderPaste(rawContent);
|
||||||
}
|
}
|
||||||
@@ -314,10 +351,13 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const resJson = await res.json();
|
const resJson = await res.json();
|
||||||
data.paste.syntax = resJson.paste.syntax ?? data.paste.syntax;
|
updatePasteState({
|
||||||
data.paste.expiresAt = resJson.paste.expiresAt ?? data.paste.expiresAt;
|
syntax: resJson.paste.syntax ?? data.paste.syntax,
|
||||||
data.paste.visibility = resJson.paste.visibility ?? data.paste.visibility;
|
expiresAt: resJson.paste.expiresAt ?? data.paste.expiresAt,
|
||||||
data.paste.title = resJson.paste.title ?? data.paste.title;
|
visibility: resJson.paste.visibility ?? data.paste.visibility,
|
||||||
|
title: resJson.paste.title ?? data.paste.title
|
||||||
|
});
|
||||||
|
editMetadata = data.paste ? { ...data.paste } : null;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
editError = 'An error occurred while updating.';
|
editError = 'An error occurred while updating.';
|
||||||
@@ -328,6 +368,48 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function reactToPaste(target: 1 | 2) {
|
||||||
|
if (!data?.paste || reactingToPaste || $user?.uuid === data.paste.author?.uuid) return;
|
||||||
|
|
||||||
|
const token = getToken();
|
||||||
|
if (!token) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
reactingToPaste = true;
|
||||||
|
const currentReaction = (data.paste.userReaction ?? null) as PasteReaction;
|
||||||
|
const nextReaction: PasteReaction = currentReaction === target ? null : target;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/paste/${data.paste.id}/reaction`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Authorization: `Bearer ${token}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ reaction: nextReaction })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const json = await res.json();
|
||||||
|
const reaction = json?.reaction;
|
||||||
|
if (!reaction) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
updatePasteState({
|
||||||
|
likes: reaction.likes ?? data.paste.likes,
|
||||||
|
dislikes: reaction.dislikes ?? data.paste.dislikes,
|
||||||
|
userReaction: reaction.userReaction ?? null
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
reactingToPaste = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' | 'report' = 'decrypt') {
|
async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' | 'report' = 'decrypt') {
|
||||||
const title = modalTitleMap[mode];
|
const title = modalTitleMap[mode];
|
||||||
if (mode === 'confirm') {
|
if (mode === 'confirm') {
|
||||||
@@ -357,6 +439,13 @@
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
|
||||||
|
if (target.classList.contains('ignore-media-warning-btn')) {
|
||||||
|
ignoreExternalMediaWarning = true;
|
||||||
|
setIgnoreExternalMediaWarning(true);
|
||||||
|
renderPaste();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (target.classList.contains('load-media-btn')) {
|
if (target.classList.contains('load-media-btn')) {
|
||||||
const src = target.getAttribute('data-src');
|
const src = target.getAttribute('data-src');
|
||||||
const tag = target.getAttribute('data-tag');
|
const tag = target.getAttribute('data-tag');
|
||||||
@@ -422,6 +511,8 @@
|
|||||||
|
|
||||||
onMount(async () => {
|
onMount(async () => {
|
||||||
try {
|
try {
|
||||||
|
ignoreExternalMediaWarning = getIgnoreExternalMediaWarning();
|
||||||
|
|
||||||
if (data?.paste && data.paste.visibility === 2) {
|
if (data?.paste && data.paste.visibility === 2) {
|
||||||
contentRendered = false;
|
contentRendered = false;
|
||||||
decryptStatus = 'Preparing decryption...';
|
decryptStatus = 'Preparing decryption...';
|
||||||
@@ -475,10 +566,12 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
$: if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderPaste();
|
$effect(() => {
|
||||||
$: reportSiteKey =
|
if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderPaste();
|
||||||
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
|
});
|
||||||
?.cf_turnstile_site_key ?? null;
|
let pasteImageUrl = $derived(
|
||||||
|
data?.paste && data?.url ? `${new URL(data.url).origin}/${data.paste.id}.jpg` : null
|
||||||
|
);
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:window bind:scrollY />
|
<svelte:window bind:scrollY />
|
||||||
@@ -490,18 +583,37 @@
|
|||||||
: 'Paste Not Found - Sharpbin'}</title
|
: 'Paste Not Found - Sharpbin'}</title
|
||||||
>
|
>
|
||||||
{#if data.paste}
|
{#if data.paste}
|
||||||
<meta property="og:title" content={data.paste.title || 'Untitled Paste'} />
|
{@const pasteDescription = `A ${syntaxes[data.paste.syntax].name} paste on Sharpbin created by ${
|
||||||
|
data.paste.author ? data.paste.author.username : 'an anonymous user'
|
||||||
|
}, created on ${
|
||||||
|
extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'
|
||||||
|
} with ${data.paste.views} view${data.paste.views !== 1 ? 's' : ''}.`}
|
||||||
|
<meta name="description" content={pasteDescription} />
|
||||||
<meta
|
<meta
|
||||||
property="og:description"
|
name="robots"
|
||||||
content={`A ${syntaxes[data.paste.syntax].name} paste on Sharpbin created by ${
|
content={data.paste.visibility === 0 ? 'index, follow' : 'noindex, nofollow'}
|
||||||
data.paste.author ? data.paste.author.username : 'Anonymous'
|
|
||||||
}, created on ${
|
|
||||||
extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'
|
|
||||||
} with ${data.paste.views} view${data.paste.views !== 1 ? 's' : ''}.`}
|
|
||||||
/>
|
/>
|
||||||
|
<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:type" content="article" />
|
||||||
<meta property="og:url" content={data.url} />
|
<meta property="og:url" content={canonicalUrl} />
|
||||||
<meta property="og:site_name" content="Sharpbin" />
|
<meta property="og:site_name" content="Sharpbin" />
|
||||||
|
{#if pasteImageUrl}
|
||||||
|
<meta property="og:image" content={pasteImageUrl} />
|
||||||
|
<meta property="og:image:type" content="image/jpeg" />
|
||||||
|
<meta property="og:image:width" content="1200" />
|
||||||
|
<meta property="og:image:height" content="630" />
|
||||||
|
<meta name="twitter:card" content="summary_large_image" />
|
||||||
|
<meta name="twitter:image" content={pasteImageUrl} />
|
||||||
|
{:else}
|
||||||
|
<meta name="twitter:card" content="summary" />
|
||||||
|
{/if}
|
||||||
|
<meta name="twitter:title" content={data.paste.title || 'Untitled Paste'} />
|
||||||
|
<meta name="twitter:description" content={pasteDescription} />
|
||||||
<meta
|
<meta
|
||||||
property="og:article:published_time"
|
property="og:article:published_time"
|
||||||
content={extractDateFromUUIDv7(data.paste.uuid)?.toISOString() ?? ''}
|
content={extractDateFromUUIDv7(data.paste.uuid)?.toISOString() ?? ''}
|
||||||
@@ -525,8 +637,7 @@
|
|||||||
{#if data.paste}
|
{#if data.paste}
|
||||||
<div class="mb-4 w-full text-center">
|
<div class="mb-4 w-full text-center">
|
||||||
<h1
|
<h1
|
||||||
class="mx-auto max-w-[90%] min-w-0 truncate text-3xl leading-tight font-bold sm:text-4xl"
|
class="mx-auto max-w-[90%] min-w-0 text-3xl leading-tight font-bold wrap-break-word sm:text-4xl"
|
||||||
use:tooltip={data.paste.title && data.paste.title.length > 40 ? data.paste.title : ''}
|
|
||||||
>
|
>
|
||||||
{#if !editing}
|
{#if !editing}
|
||||||
{data.paste.title || 'Untitled Paste'}
|
{data.paste.title || 'Untitled Paste'}
|
||||||
@@ -541,14 +652,15 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</h1>
|
</h1>
|
||||||
<div class="flex items-center justify-center gap-2 text-sm text-neutral-400">
|
<div class="flex items-center justify-center gap-2 text-sm text-neutral-400">
|
||||||
<User class="inline-block h-4 w-4 text-neutral-400" />
|
|
||||||
{#if data.paste.author}
|
{#if data.paste.author}
|
||||||
|
<User class="inline-block h-4 w-4 text-neutral-400" />
|
||||||
<a
|
<a
|
||||||
href={resolve(`/user/${data.paste.author.username}`)}
|
href={resolve(`/user/${data.paste.author.username}`)}
|
||||||
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
|
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
|
||||||
>{data.paste.author.username}</a
|
>{data.paste.author.username}</a
|
||||||
>
|
>
|
||||||
{:else}
|
{:else}
|
||||||
|
<HatGlasses class="inline-block h-4 w-4 text-neutral-400" />
|
||||||
<span class="text-neutral-400">Anonymous</span>
|
<span class="text-neutral-400">Anonymous</span>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -559,7 +671,9 @@
|
|||||||
<div
|
<div
|
||||||
class="flex"
|
class="flex"
|
||||||
use:tooltip={`${
|
use:tooltip={`${
|
||||||
data.paste.isCompressed ? `Compressed Size: ${formatBytes(data.paste.size)}` : ''
|
data.paste.isCompressed
|
||||||
|
? `Compressed Size: ${formatBytes(data.paste.storedSize)}`
|
||||||
|
: ''
|
||||||
}${
|
}${
|
||||||
data.paste.visibility === 2
|
data.paste.visibility === 2
|
||||||
? ` • Decrypted Size: ${formatBytes(decryptedContent ? new TextEncoder().encode(decryptedContent).length : 0)}`
|
? ` • Decrypted Size: ${formatBytes(decryptedContent ? new TextEncoder().encode(decryptedContent).length : 0)}`
|
||||||
@@ -567,7 +681,7 @@
|
|||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<FileBox class="mr-2 h-6 w-6 text-neutral-400" />
|
<FileBox class="mr-2 h-6 w-6 text-neutral-400" />
|
||||||
<span class="text-neutral-400">{formatBytes(data.paste.trueSize)}</span>
|
<span class="text-neutral-400">{formatBytes(data.paste.originalSize)}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -684,7 +798,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="sticky top-0 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row"
|
class="sticky top-15 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row"
|
||||||
>
|
>
|
||||||
{#if !isBinary}
|
{#if !isBinary}
|
||||||
<div class="flex items-center gap-2 text-sm text-neutral-300">
|
<div class="flex items-center gap-2 text-sm text-neutral-300">
|
||||||
@@ -705,6 +819,33 @@
|
|||||||
? 's'
|
? 's'
|
||||||
: ''}</span
|
: ''}</span
|
||||||
>
|
>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="ml-4 rounded border px-2 py-0.5 text-sm transition-colors disabled:cursor-not-allowed! disabled:opacity-60 {data
|
||||||
|
.paste.userReaction === 1
|
||||||
|
? 'border-green-700 bg-green-900 text-green-200'
|
||||||
|
: 'border-neutral-700 bg-neutral-700 text-neutral-300 hover:bg-neutral-600'}"
|
||||||
|
onclick={() => reactToPaste(1)}
|
||||||
|
disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
|
||||||
|
aria-disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
|
||||||
|
>
|
||||||
|
<ThumbsUp class="mr-1 inline-block h-4 w-4 text-green-400" />
|
||||||
|
<span>{formatNumber(data.paste.likes)}</span>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="rounded border px-2 py-0.5 text-sm transition-colors disabled:cursor-not-allowed! disabled:opacity-60 {data
|
||||||
|
.paste.userReaction === 2
|
||||||
|
? 'border-red-700 bg-red-900 text-red-200'
|
||||||
|
: 'border-neutral-700 bg-neutral-700 text-neutral-300 hover:bg-neutral-600'}"
|
||||||
|
onclick={() => reactToPaste(2)}
|
||||||
|
disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
|
||||||
|
aria-disabled={reactingToPaste || !$user || $user?.uuid === data.paste.author?.uuid}
|
||||||
|
>
|
||||||
|
<ThumbsDown class="mr-1 inline-block h-4 w-4 text-red-400" />
|
||||||
|
<span>{formatNumber(data.paste.dislikes)}</span>
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
{:else}
|
{:else}
|
||||||
<div></div>
|
<div></div>
|
||||||
@@ -714,13 +855,13 @@
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
||||||
on:click={() => {
|
onclick={() => {
|
||||||
navigator.clipboard.writeText(decryptedContent ?? data.content);
|
navigator.clipboard.writeText(decryptedContent ?? data.content);
|
||||||
copiedPaste = true;
|
copiedPaste = true;
|
||||||
setTimeout(() => (copiedPaste = false), 1000);
|
setTimeout(() => (copiedPaste = false), 1000);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div class="relative mr-1 h-5 w-5">
|
<div class="relative {iconsOnly ? '' : 'mr-1'} h-5 w-5">
|
||||||
{#if copiedPaste}
|
{#if copiedPaste}
|
||||||
<span
|
<span
|
||||||
transition:fade={{ duration: 200 }}
|
transition:fade={{ duration: 200 }}
|
||||||
@@ -735,14 +876,15 @@
|
|||||||
>
|
>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
{#if !iconsOnly}
|
||||||
<span class="text-neutral-300">Copy</span>
|
<span class="text-neutral-300">Copy</span>
|
||||||
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
||||||
on:click={() => {
|
onclick={() => {
|
||||||
const blob = new Blob([decryptedContent ?? data.content], {
|
const blob = new Blob([decryptedContent ?? data.content], {
|
||||||
type: 'text/plain'
|
type: 'text/plain'
|
||||||
});
|
});
|
||||||
@@ -760,10 +902,13 @@
|
|||||||
|
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
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.href = url;
|
||||||
a.download = data.paste?.title
|
a.download = filename;
|
||||||
? data.paste.title.slice(0, 100) + extension
|
|
||||||
: `paste_${data.paste?.id}${extension}`;
|
|
||||||
document.body.appendChild(a);
|
document.body.appendChild(a);
|
||||||
a.click();
|
a.click();
|
||||||
document.body.removeChild(a);
|
document.body.removeChild(a);
|
||||||
@@ -772,7 +917,7 @@
|
|||||||
setTimeout(() => (downloadedPaste = false), 1000);
|
setTimeout(() => (downloadedPaste = false), 1000);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div class="relative mr-1 h-5 w-5">
|
<div class="relative {iconsOnly ? '' : 'mr-1'} h-5 w-5">
|
||||||
{#if downloadedPaste}
|
{#if downloadedPaste}
|
||||||
<span
|
<span
|
||||||
transition:fade={{ duration: 200 }}
|
transition:fade={{ duration: 200 }}
|
||||||
@@ -787,50 +932,73 @@
|
|||||||
>
|
>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
{#if !iconsOnly}
|
||||||
<span class="text-neutral-300">Download</span>
|
<span class="text-neutral-300">Download</span>
|
||||||
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<a
|
<a
|
||||||
href={resolve(`/raw/${data.paste.id}`)}
|
href={resolve(`/raw/${data.paste.id}`)}
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
||||||
>
|
>
|
||||||
<File class="mr-1 h-5 w-5 text-neutral-400" />
|
<File class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
|
||||||
<span class="text-neutral-300">View Raw</span>
|
{#if !iconsOnly}
|
||||||
|
<span class="text-neutral-300">View Raw</span>
|
||||||
|
{/if}
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
||||||
|
onclick={() => {
|
||||||
|
document.getElementById('comments-section')?.scrollIntoView({
|
||||||
|
behavior: 'smooth',
|
||||||
|
block: 'start'
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MessageCircle class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
|
||||||
|
{#if !iconsOnly}
|
||||||
|
<span class="text-neutral-300">Comments</span>
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
|
||||||
{#if $user !== null && $user.uuid !== data.paste?.author?.uuid}
|
{#if $user !== null && $user.uuid !== data.paste?.author?.uuid}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-amber-600/50"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-amber-600/50"
|
||||||
on:click={() => {
|
onclick={() => {
|
||||||
promptUser('report');
|
promptUser('report');
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Flag class="mr-1 h-5 w-5 text-amber-400" />
|
<Flag class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-amber-400" />
|
||||||
<span class="text-amber-300">Report</span>
|
{#if !iconsOnly}
|
||||||
|
<span class="text-amber-300">Report</span>
|
||||||
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
{#if $user && ($user.uuid === data.paste?.author?.uuid || $user.roles.some((r) => r === 1 || r === 255))}
|
{#if $user && ($user.uuid === data.paste?.author?.uuid || hasRole($user.roles, 2) || hasRole($user.roles, 4))}
|
||||||
{#if !editing}
|
{#if !editing}
|
||||||
{#if !isBinary}
|
{#if !isBinary}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
||||||
on:click={() => {
|
onclick={() => {
|
||||||
editContent = decryptedContent ?? data.content;
|
editContent = decryptedContent ?? data.content;
|
||||||
editError = '';
|
editError = '';
|
||||||
editing = true;
|
editing = true;
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Pencil class="mr-1 h-5 w-5 text-neutral-400" />
|
<Pencil class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
|
||||||
<span class="text-neutral-300">Edit</span>
|
{#if !iconsOnly}
|
||||||
|
<span class="text-neutral-300">Edit</span>
|
||||||
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-red-900"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-red-900"
|
||||||
on:click={() => {
|
onclick={() => {
|
||||||
promptUser('confirm').then(async (value) => {
|
promptUser('confirm').then(async (value) => {
|
||||||
if (value) {
|
if (value) {
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
@@ -852,33 +1020,39 @@
|
|||||||
});
|
});
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Trash2 class="mr-1 h-5 w-5 text-red-400" />
|
<Trash2 class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-red-400" />
|
||||||
<span class="text-red-300">Delete</span>
|
{#if !iconsOnly}
|
||||||
|
<span class="text-red-300">Delete</span>
|
||||||
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
{:else}
|
{:else}
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
||||||
on:click={async () => {
|
onclick={async () => {
|
||||||
if (editContent !== null || editMetadata !== null) {
|
if (editContent !== null || editMetadata !== null) {
|
||||||
await updatePaste(editContent, editMetadata);
|
await updatePaste(editContent, editMetadata);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
disabled={editLoading}
|
disabled={editLoading}
|
||||||
>
|
>
|
||||||
<PencilLine class="mr-1 h-5 w-5 text-neutral-400" />
|
<PencilLine class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
|
||||||
<span class="text-neutral-300">{editLoading ? 'Saving...' : 'Save Edits'}</span>
|
{#if !iconsOnly || editLoading}
|
||||||
|
<span class="text-neutral-300">{editLoading ? 'Saving...' : 'Save Edits'}</span>
|
||||||
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
||||||
on:click={() => {
|
onclick={() => {
|
||||||
editing = false;
|
editing = false;
|
||||||
editError = '';
|
editError = '';
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<PencilOff class="mr-1 h-5 w-5 text-neutral-400" />
|
<PencilOff class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
|
||||||
<span class="text-neutral-300">Cancel Edit</span>
|
{#if !iconsOnly}
|
||||||
|
<span class="text-neutral-300">Cancel Edit</span>
|
||||||
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
{/if}
|
{/if}
|
||||||
@@ -886,11 +1060,13 @@
|
|||||||
<button
|
<button
|
||||||
transition:fade={{ duration: 200 }}
|
transition:fade={{ duration: 200 }}
|
||||||
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
|
||||||
on:click={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
|
onclick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
|
||||||
aria-label="Scroll to top"
|
aria-label="Scroll to top"
|
||||||
>
|
>
|
||||||
<ArrowUp class="mr-1 h-5 w-5 text-neutral-400" />
|
<ArrowUp class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
|
||||||
<span class="text-neutral-300">Scroll to top</span>
|
{#if !iconsOnly}
|
||||||
|
<span class="text-neutral-300">Scroll to top</span>
|
||||||
|
{/if}
|
||||||
</button>
|
</button>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
@@ -924,10 +1100,10 @@
|
|||||||
class={data.paste.syntax === 'markdown'
|
class={data.paste.syntax === 'markdown'
|
||||||
? 'markdown rounded-b-md bg-neutral-800 p-4'
|
? 'markdown rounded-b-md bg-neutral-800 p-4'
|
||||||
: data.paste.syntax === 'csv'
|
: 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'}
|
: 'codeblock-with-lines overflow-x-auto overflow-y-auto'}
|
||||||
class:hidden={!contentRendered}
|
class:hidden={!contentRendered}
|
||||||
on:click={handleMarkdownClick}
|
onclick={handleMarkdownClick}
|
||||||
role="presentation"
|
role="presentation"
|
||||||
>
|
>
|
||||||
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
|
||||||
@@ -940,9 +1116,12 @@
|
|||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<PasteComments pasteId={data.paste.id} initialComments={data.comments ?? []} />
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.hljs {
|
.hljs {
|
||||||
background-color: var(--color-neutral-800) !important;
|
background-color: var(--color-neutral-800) !important;
|
||||||
|
padding: 0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.codeblock-with-lines {
|
.codeblock-with-lines {
|
||||||
@@ -970,29 +1149,42 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
padding: 0.1em 0;
|
padding: 0;
|
||||||
border-radius: 0.15em;
|
|
||||||
}
|
}
|
||||||
.code-row:hover {
|
.code-row:hover {
|
||||||
background-color: rgba(255, 255, 255, 0.05);
|
background-color: rgba(255, 255, 255, 0.05);
|
||||||
}
|
}
|
||||||
.line-number {
|
.line-number {
|
||||||
flex-shrink: 0;
|
display: inline-flex;
|
||||||
|
align-self: stretch;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: flex-end;
|
||||||
|
flex: 0 0 calc(var(--digits, 1) * 1ch + 1.3em);
|
||||||
|
width: calc(var(--digits, 1) * 1ch + 1.3em);
|
||||||
|
box-sizing: border-box;
|
||||||
text-align: right;
|
text-align: right;
|
||||||
color: #888;
|
color: #888;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
margin-right: 1em;
|
margin-right: 0;
|
||||||
|
font-family:
|
||||||
|
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',
|
||||||
|
monospace;
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
|
padding-top: 0.1em;
|
||||||
|
padding-bottom: 0.1em;
|
||||||
padding-right: 0.5em;
|
padding-right: 0.5em;
|
||||||
padding-left: 0.25em;
|
padding-left: 0.9em;
|
||||||
background: none;
|
background: none;
|
||||||
|
border-right: 1px solid var(--color-neutral-700);
|
||||||
}
|
}
|
||||||
.code-line {
|
.code-line {
|
||||||
display: block;
|
display: block;
|
||||||
white-space: pre-wrap;
|
white-space: pre-wrap;
|
||||||
word-break: break-word;
|
word-break: break-word;
|
||||||
overflow-wrap: anywhere;
|
overflow-wrap: anywhere;
|
||||||
padding-left: 0.25em;
|
padding-top: 0.1em;
|
||||||
|
padding-bottom: 0.1em;
|
||||||
|
padding-left: 0.9em;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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' });
|
||||||
|
};
|
||||||
@@ -83,7 +83,8 @@ select {
|
|||||||
color: #3b82f6;
|
color: #3b82f6;
|
||||||
text-decoration: underline;
|
text-decoration: underline;
|
||||||
}
|
}
|
||||||
.markdown .load-media-btn:hover {
|
.markdown .load-media-btn:hover,
|
||||||
|
.markdown .ignore-media-warning-btn:hover {
|
||||||
background-color: #525252 !important;
|
background-color: #525252 !important;
|
||||||
}
|
}
|
||||||
.markdown pre {
|
.markdown pre {
|
||||||
@@ -120,3 +121,7 @@ select {
|
|||||||
.markdown th {
|
.markdown th {
|
||||||
background-color: #2a2a2a;
|
background-color: #2a2a2a;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
|
import { setTokens, startTokenRefreshInterval } from '#lib/utils/auth';
|
||||||
import { extractError } from '$lib/utils/misc';
|
import { extractError } from '#lib/utils/misc';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
|
|
||||||
let username = '';
|
let username = $state('');
|
||||||
let password = '';
|
let password = $state('');
|
||||||
let error = '';
|
let error = $state('');
|
||||||
let totpEnabled = false;
|
let totpEnabled = $state(false);
|
||||||
let totpCode = '';
|
let totpCode = $state('');
|
||||||
export let data: PageData;
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { data }: Props = $props();
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
const render = () => {
|
const render = () => {
|
||||||
@@ -35,7 +39,8 @@
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
async function login() {
|
async function login(event: Event) {
|
||||||
|
event.preventDefault();
|
||||||
const body: { username: string; password: string; token?: string; totpcode?: string } = {
|
const body: { username: string; password: string; token?: string; totpcode?: string } = {
|
||||||
username,
|
username,
|
||||||
password
|
password
|
||||||
@@ -96,7 +101,7 @@
|
|||||||
>
|
>
|
||||||
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||||
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
|
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
|
||||||
<form on:submit|preventDefault={login} class="space-y-4">
|
<form onsubmit={login} class="space-y-4">
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Username"
|
placeholder="Username"
|
||||||
@@ -122,7 +127,7 @@
|
|||||||
inputmode="numeric"
|
inputmode="numeric"
|
||||||
pattern="[0-9]*"
|
pattern="[0-9]*"
|
||||||
required
|
required
|
||||||
on:input={(e) => {
|
oninput={(e) => {
|
||||||
if (e.target instanceof HTMLInputElement) {
|
if (e.target instanceof HTMLInputElement) {
|
||||||
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
|
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
|
||||||
totpCode = e.target.value;
|
totpCode = e.target.value;
|
||||||
@@ -154,5 +159,11 @@
|
|||||||
class="text-neutral-200 transition-colors duration-200 hover:text-white">Register</a
|
class="text-neutral-200 transition-colors duration-200 hover:text-white">Register</a
|
||||||
>
|
>
|
||||||
</p>
|
</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>
|
</div>
|
||||||
</main>
|
</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,19 +1,28 @@
|
|||||||
import type { RequestHandler } from '@sveltejs/kit';
|
import type { RequestHandler } from '@sveltejs/kit';
|
||||||
|
import { apiUrl } from '#lib/server/api';
|
||||||
|
|
||||||
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
|
export const GET: RequestHandler = async ({ params, request }) => {
|
||||||
|
|
||||||
export const GET: RequestHandler = async ({ params }) => {
|
|
||||||
const { id } = params;
|
const { id } = params;
|
||||||
|
const headers = new Headers(request.headers);
|
||||||
|
|
||||||
const res = await fetch(`${apiUrl}/api/paste/${id}/raw`);
|
const res = await fetch(`${apiUrl}/api/paste/${id}/raw`, {
|
||||||
|
headers: headers
|
||||||
|
});
|
||||||
|
|
||||||
if (res.status === 404) {
|
if (res.status === 404) {
|
||||||
return new Response('Paste not found', { status: 404 });
|
return new Response(null, {
|
||||||
|
status: 404,
|
||||||
|
statusText: 'Not Found'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
const content = await res.text();
|
const responseHeaders = new Headers(res.headers);
|
||||||
return new Response(content, {
|
responseHeaders.delete('content-encoding');
|
||||||
headers: {
|
responseHeaders.delete('content-length');
|
||||||
'Content-Type': 'text/plain; charset=utf-8'
|
responseHeaders.delete('transfer-encoding');
|
||||||
}
|
|
||||||
|
return new Response(await res.arrayBuffer(), {
|
||||||
|
status: res.status,
|
||||||
|
statusText: res.statusText,
|
||||||
|
headers: responseHeaders
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,19 +1,15 @@
|
|||||||
import type { PageServerLoad } from './$types';
|
import type { PageServerLoad } from './$types';
|
||||||
import type { Paste } from '$lib/types/paste';
|
import type { Paste } from '#lib/types/paste';
|
||||||
import { extractError } from '$lib/utils/misc';
|
import { extractError } from '#lib/utils/misc';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ fetch }) => {
|
export const load: PageServerLoad = async ({ fetch, request }) => {
|
||||||
try {
|
const headers = new Headers(request.headers);
|
||||||
const res = await fetch('/api/paste/recent');
|
const res = await fetch('/api/paste/recent', { headers });
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
|
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
|
||||||
throw error(res.status, errorMsg);
|
throw error(res.status, errorMsg);
|
||||||
}
|
|
||||||
const recentPastes: Paste[] = await res.json();
|
|
||||||
return { recentPastes };
|
|
||||||
} catch (error) {
|
|
||||||
console.error(error);
|
|
||||||
return { recentPastes: [] };
|
|
||||||
}
|
}
|
||||||
|
const recentPastes: Paste[] = await res.json();
|
||||||
|
return { recentPastes };
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import Paste from '$lib/components/Paste.svelte';
|
import Paste from '#lib/components/Paste.svelte';
|
||||||
|
|
||||||
export let data: PageData;
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
let now = new Date();
|
let { data }: Props = $props();
|
||||||
|
|
||||||
|
let now = $state(new Date());
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
const interval = setInterval(() => {
|
const interval = setInterval(() => {
|
||||||
@@ -19,6 +23,16 @@
|
|||||||
<svelte:head>
|
<svelte:head>
|
||||||
<title>Recent Pastes - Sharpbin</title>
|
<title>Recent Pastes - Sharpbin</title>
|
||||||
<meta name="description" content="Browse the most recent pastes shared on Sharpbin." />
|
<meta name="description" content="Browse the most recent pastes shared on Sharpbin." />
|
||||||
|
<meta name="robots" content="noindex, follow" />
|
||||||
|
<link rel="canonical" href={data.url} />
|
||||||
|
<meta property="og:title" content="Recent Pastes - Sharpbin" />
|
||||||
|
<meta property="og:description" content="Browse the most recent pastes shared on Sharpbin." />
|
||||||
|
<meta property="og:type" content="website" />
|
||||||
|
<meta property="og:url" content={data.url} />
|
||||||
|
<meta property="og:site_name" content="Sharpbin" />
|
||||||
|
<meta name="twitter:card" content="summary" />
|
||||||
|
<meta name="twitter:title" content="Recent Pastes - Sharpbin" />
|
||||||
|
<meta name="twitter:description" content="Browse the most recent pastes shared on Sharpbin." />
|
||||||
</svelte:head>
|
</svelte:head>
|
||||||
|
|
||||||
<main
|
<main
|
||||||
|
|||||||
@@ -1,34 +1,38 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
|
import { setTokens, startTokenRefreshInterval } from '#lib/utils/auth';
|
||||||
import { extractError } from '$lib/utils/misc';
|
import { extractError } from '#lib/utils/misc';
|
||||||
import { Check, X, Eye, EyeClosed } from '@lucide/svelte';
|
import { Check, X, Eye, EyeClosed } from '@lucide/svelte';
|
||||||
import { slide, fade } from 'svelte/transition';
|
import { slide, fade } from 'svelte/transition';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
|
|
||||||
let username = '';
|
let username = $state('');
|
||||||
let password = '';
|
let password = $state('');
|
||||||
let confirmPassword = '';
|
let confirmPassword = $state('');
|
||||||
let email = '';
|
let email = $state('');
|
||||||
let displayName = '';
|
let displayName = $state('');
|
||||||
let error = '';
|
let error = $state('');
|
||||||
|
|
||||||
let passwordFocused = false;
|
let passwordFocused = $state(false);
|
||||||
let showPassword = false;
|
let showPassword = $state(false);
|
||||||
|
|
||||||
let passwordChecks = {
|
let passwordChecks = $state({
|
||||||
minLength: false,
|
minLength: false,
|
||||||
maxLength: false,
|
maxLength: false,
|
||||||
upper: false,
|
upper: false,
|
||||||
lower: false,
|
lower: false,
|
||||||
number: false
|
number: false
|
||||||
};
|
});
|
||||||
let passwordValid = false;
|
let passwordValid = $state(false);
|
||||||
let loading = false;
|
let loading = $state(false);
|
||||||
|
|
||||||
export let data: PageData;
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { data }: Props = $props();
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
const render = () => {
|
const render = () => {
|
||||||
@@ -71,9 +75,12 @@
|
|||||||
passwordChecks.number;
|
passwordChecks.number;
|
||||||
}
|
}
|
||||||
|
|
||||||
$: validatePassword(password);
|
$effect(() => {
|
||||||
|
validatePassword(password);
|
||||||
|
});
|
||||||
|
|
||||||
async function register() {
|
async function register(event: Event) {
|
||||||
|
event.preventDefault();
|
||||||
if (!passwordValid || password !== confirmPassword) return;
|
if (!passwordValid || password !== confirmPassword) return;
|
||||||
loading = true;
|
loading = true;
|
||||||
error = '';
|
error = '';
|
||||||
@@ -143,7 +150,7 @@
|
|||||||
Registration is currently disabled.
|
Registration is currently disabled.
|
||||||
</div>
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
<form on:submit|preventDefault={register} class="space-y-4">
|
<form onsubmit={register} class="space-y-4">
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Username"
|
placeholder="Username"
|
||||||
@@ -179,15 +186,15 @@
|
|||||||
placeholder="Password"
|
placeholder="Password"
|
||||||
bind:value={password}
|
bind:value={password}
|
||||||
required
|
required
|
||||||
on:focus={() => (passwordFocused = true)}
|
onfocus={() => (passwordFocused = true)}
|
||||||
on:blur={() => (passwordFocused = false)}
|
onblur={() => (passwordFocused = false)}
|
||||||
autocomplete="new-password"
|
autocomplete="new-password"
|
||||||
disabled={loading || !data.options?.registration_enabled}
|
disabled={loading || !data.options?.registration_enabled}
|
||||||
class="focus:bg-neutral-750 w-[calc(100%-40px)] rounded-l border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
class="focus:bg-neutral-750 w-[calc(100%-40px)] rounded-l border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
on:click={() => (showPassword = !showPassword)}
|
onclick={() => (showPassword = !showPassword)}
|
||||||
disabled={loading || !data.options?.registration_enabled}
|
disabled={loading || !data.options?.registration_enabled}
|
||||||
class="ml-2 flex w-10 items-center rounded-r border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200 hover:bg-neutral-700 focus:outline-none"
|
class="ml-2 flex w-10 items-center rounded-r border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200 hover:bg-neutral-700 focus:outline-none"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,33 +1,24 @@
|
|||||||
import type { PageServerLoad } from './$types';
|
import type { PageServerLoad } from './$types';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
import { env } from '$env/dynamic/private';
|
import { apiUrl } from '#lib/server/api';
|
||||||
import { getServerToken } from '$lib/utils/auth';
|
import { getServerToken, clearServerTokens, roles, getUserFromToken } from '#lib/utils/auth';
|
||||||
import type { Report } from '$lib/types/report';
|
import type { Report } from '#lib/types/report';
|
||||||
|
|
||||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
export const load: PageServerLoad = async ({ fetch, cookies, params, url, request }) => {
|
||||||
|
|
||||||
function decodeJwtRoles(token?: string | null): number[] {
|
|
||||||
try {
|
|
||||||
if (!token) return [];
|
|
||||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
|
||||||
const roles = payload?.role;
|
|
||||||
if (Array.isArray(roles)) {
|
|
||||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
|
||||||
}
|
|
||||||
return [];
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
|
|
||||||
const token = getServerToken(cookies);
|
const token = getServerToken(cookies);
|
||||||
if (!token) throw error(401, 'Login required');
|
if (!token) throw error(401, 'Login required');
|
||||||
const roles = decodeJwtRoles(token);
|
|
||||||
const canEdit = roles.includes(1) || roles.includes(255);
|
|
||||||
|
|
||||||
const res = await fetch(`${API_URL}/api/report/${params.reportId}`, {
|
const user = getUserFromToken(token);
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
if (!user) {
|
||||||
|
clearServerTokens(cookies);
|
||||||
|
throw error(401, 'Invalid token');
|
||||||
|
}
|
||||||
|
const canEdit = (user.roles & roles.Admin) !== 0 || (user.roles & roles.Moderator) !== 0;
|
||||||
|
const headers = new Headers(request.headers);
|
||||||
|
headers.set('Authorization', `Bearer ${token}`);
|
||||||
|
|
||||||
|
const res = await fetch(`${apiUrl}/api/report/${params.reportId}`, {
|
||||||
|
headers: headers
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -36,7 +27,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const report = (await res.json()) as Report;
|
const report = (await res.json()) as Report;
|
||||||
const optionsRes = await fetch(`${API_URL}/api/report/options`);
|
const optionsRes = await fetch(`${apiUrl}/api/report/options`);
|
||||||
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
|
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
|
||||||
|
|
||||||
return { report, url: url.href, canEdit, options };
|
return { report, url: url.href, canEdit, options };
|
||||||
|
|||||||
@@ -1,19 +1,24 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
|
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '#lib/types/report';
|
||||||
import { tooltip } from '$lib/utils/misc';
|
import { tooltip } from '#lib/utils/misc';
|
||||||
import { getToken } from '$lib/utils/auth';
|
import { getToken } from '#lib/utils/auth';
|
||||||
|
|
||||||
export let data: PageData;
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
const report = data.report;
|
let { data }: Props = $props();
|
||||||
let saving = false;
|
const initialReport = () => ({ ...data.report });
|
||||||
let saveError = '';
|
|
||||||
const statusOptions = data.options?.statuses ?? [];
|
let report = $state(initialReport());
|
||||||
const typeOptions = data.options?.types ?? [];
|
let saving = $state(false);
|
||||||
let statusValue = reportStatusLabels[report.status] ?? '';
|
let saveError = $state('');
|
||||||
let typeValue = reportTypeLabels[report.type] ?? '';
|
let statusOptions = $derived(data.options?.statuses ?? []);
|
||||||
|
let typeOptions = $derived(data.options?.types ?? []);
|
||||||
|
let statusValue = $state(reportStatusLabels[report.status] ?? '');
|
||||||
|
let typeValue = $state(reportTypeLabels[report.type] ?? '');
|
||||||
|
|
||||||
async function updateReport() {
|
async function updateReport() {
|
||||||
saveError = '';
|
saveError = '';
|
||||||
@@ -143,7 +148,7 @@
|
|||||||
<div class="flex items-center gap-3">
|
<div class="flex items-center gap-3">
|
||||||
<button
|
<button
|
||||||
class="rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-60"
|
class="rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-60"
|
||||||
on:click={updateReport}
|
onclick={updateReport}
|
||||||
disabled={saving}
|
disabled={saving}
|
||||||
>
|
>
|
||||||
{saving ? 'Saving...' : 'Update Report'}
|
{saving ? 'Saving...' : 'Update Report'}
|
||||||
|
|||||||
@@ -1,37 +1,32 @@
|
|||||||
import type { PageServerLoad } from './$types';
|
import type { PageServerLoad } from './$types';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
import { env } from '$env/dynamic/private';
|
import { apiUrl } from '#lib/server/api';
|
||||||
import { getServerToken } from '$lib/utils/auth';
|
import {
|
||||||
import type { ReportListResponse } from '$lib/types/report';
|
getServerToken,
|
||||||
import { extractError } from '$lib/utils/misc';
|
getUserFromToken,
|
||||||
|
clearServerTokens,
|
||||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
hasRole,
|
||||||
|
roles
|
||||||
function decodeJwtRoles(token?: string | null): number[] {
|
} from '#lib/utils/auth';
|
||||||
try {
|
import type { ReportListResponse } from '#lib/types/report';
|
||||||
if (!token) return [];
|
import { extractError } from '#lib/utils/misc';
|
||||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
|
||||||
const roles = payload?.role;
|
|
||||||
if (Array.isArray(roles)) {
|
|
||||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
|
||||||
}
|
|
||||||
return [];
|
|
||||||
} catch {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTarget(value: string | null): 'all' | 'pastes' | 'users' {
|
function normalizeTarget(value: string | null): 'all' | 'pastes' | 'users' {
|
||||||
if (value === 'pastes' || value === 'users') return value;
|
if (value === 'pastes' || value === 'users') return value;
|
||||||
return 'all';
|
return 'all';
|
||||||
}
|
}
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
|
export const load: PageServerLoad = async ({ fetch, cookies, url, request }) => {
|
||||||
const token = getServerToken(cookies);
|
const token = getServerToken(cookies);
|
||||||
if (!token) throw error(401, 'Login required');
|
if (!token) throw error(401, 'Login required');
|
||||||
|
|
||||||
const roles = decodeJwtRoles(token);
|
const user = getUserFromToken(token);
|
||||||
if (!roles.includes(1) && !roles.includes(255)) {
|
if (!user) {
|
||||||
|
clearServerTokens(cookies);
|
||||||
|
throw error(401, 'Invalid token');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasRole(user.roles, roles.Admin) && !hasRole(user.roles, roles.Moderator)) {
|
||||||
throw error(403, 'You do not have permission to view reports.');
|
throw error(403, 'You do not have permission to view reports.');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,8 +44,11 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
|
|||||||
if ((target === 'pastes' || target === 'all') && pasteId) query.set('pasteId', pasteId);
|
if ((target === 'pastes' || target === 'all') && pasteId) query.set('pasteId', pasteId);
|
||||||
if ((target === 'users' || target === 'all') && userUuid) query.set('userUUID', userUuid);
|
if ((target === 'users' || target === 'all') && userUuid) query.set('userUUID', userUuid);
|
||||||
|
|
||||||
const reportsRes = await fetch(`${API_URL}/api/report/${target}?${query.toString()}`, {
|
const headers = new Headers(request.headers);
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
headers.set('Authorization', `Bearer ${token}`);
|
||||||
|
|
||||||
|
const reportsRes = await fetch(`${apiUrl}/api/report/${target}?${query.toString()}`, {
|
||||||
|
headers: headers
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!reportsRes.ok) {
|
if (!reportsRes.ok) {
|
||||||
@@ -60,7 +58,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
|
|||||||
|
|
||||||
const reports = (await reportsRes.json()) as ReportListResponse;
|
const reports = (await reportsRes.json()) as ReportListResponse;
|
||||||
|
|
||||||
const optionsRes = await fetch(`${API_URL}/api/report/options`);
|
const optionsRes = await fetch(`${apiUrl}/api/report/options`);
|
||||||
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
|
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -1,19 +1,38 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { createBubbler, stopPropagation } from 'svelte/legacy';
|
||||||
|
|
||||||
|
const bubble = createBubbler();
|
||||||
import type { PageData } from './$types';
|
import type { PageData } from './$types';
|
||||||
import { resolve } from '$app/paths';
|
import { resolve } from '$app/paths';
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
|
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '#lib/types/report';
|
||||||
import { tooltip } from '$lib/utils/misc';
|
import { tooltip } from '#lib/utils/misc';
|
||||||
import { SvelteURLSearchParams } from 'svelte/reactivity';
|
import { SvelteURLSearchParams } from 'svelte/reactivity';
|
||||||
|
|
||||||
export let data: PageData;
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
let target = data.filters.target;
|
let { data }: Props = $props();
|
||||||
let status = data.filters.status;
|
const initialFilters = (() => {
|
||||||
let type = data.filters.type ?? '';
|
const filters = data.filters;
|
||||||
let pasteId = data.filters.pasteId;
|
return {
|
||||||
let userUuid = data.filters.userUuid;
|
target: (filters.target as 'all' | 'pastes' | 'users') ?? 'all',
|
||||||
let mixedTarget = target === 'all' ? pasteId || userUuid : '';
|
status: filters.status ?? '',
|
||||||
|
type: filters.type ?? '',
|
||||||
|
pasteId: filters.pasteId ?? '',
|
||||||
|
userUuid: filters.userUuid ?? ''
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
|
||||||
|
let target = $state(initialFilters.target);
|
||||||
|
let status = $state(initialFilters.status);
|
||||||
|
let type = $state(initialFilters.type);
|
||||||
|
let pasteId = $state(initialFilters.pasteId);
|
||||||
|
let userUuid = $state(initialFilters.userUuid);
|
||||||
|
let mixedTarget = $state(
|
||||||
|
initialFilters.target === 'all' ? initialFilters.pasteId || initialFilters.userUuid : ''
|
||||||
|
);
|
||||||
let inputTimer: ReturnType<typeof setTimeout> | null = null;
|
let inputTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
const targets = [
|
const targets = [
|
||||||
@@ -22,8 +41,8 @@
|
|||||||
{ value: 'users', label: 'Users' }
|
{ value: 'users', label: 'Users' }
|
||||||
];
|
];
|
||||||
|
|
||||||
const statuses = data.options?.statuses ?? [];
|
let statuses = $derived(data.options?.statuses ?? []);
|
||||||
const types = data.options?.types ?? [];
|
let types = $derived(data.options?.types ?? []);
|
||||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
function applyFilters(page = 1) {
|
function applyFilters(page = 1) {
|
||||||
@@ -108,7 +127,7 @@
|
|||||||
id="report-target"
|
id="report-target"
|
||||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||||
bind:value={target}
|
bind:value={target}
|
||||||
on:change={(e) => {
|
onchange={(e) => {
|
||||||
if (e.currentTarget instanceof HTMLSelectElement) {
|
if (e.currentTarget instanceof HTMLSelectElement) {
|
||||||
handleTargetChange(e.currentTarget.value);
|
handleTargetChange(e.currentTarget.value);
|
||||||
}
|
}
|
||||||
@@ -125,7 +144,7 @@
|
|||||||
id="report-status"
|
id="report-status"
|
||||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||||
bind:value={status}
|
bind:value={status}
|
||||||
on:change={() => applyFilters(1)}
|
onchange={() => applyFilters(1)}
|
||||||
>
|
>
|
||||||
<option value="">Any</option>
|
<option value="">Any</option>
|
||||||
{#each statuses as s (s)}
|
{#each statuses as s (s)}
|
||||||
@@ -139,7 +158,7 @@
|
|||||||
id="report-type"
|
id="report-type"
|
||||||
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
class="rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||||
bind:value={type}
|
bind:value={type}
|
||||||
on:change={() => applyFilters(1)}
|
onchange={() => applyFilters(1)}
|
||||||
>
|
>
|
||||||
<option value="">Any</option>
|
<option value="">Any</option>
|
||||||
{#each types as t (t)}
|
{#each types as t (t)}
|
||||||
@@ -165,7 +184,7 @@
|
|||||||
? 'User UUID'
|
? 'User UUID'
|
||||||
: 'Paste ID or User UUID'}
|
: 'Paste ID or User UUID'}
|
||||||
value={target === 'pastes' ? pasteId : target === 'users' ? userUuid : mixedTarget}
|
value={target === 'pastes' ? pasteId : target === 'users' ? userUuid : mixedTarget}
|
||||||
on:input={(e) => {
|
oninput={(e) => {
|
||||||
if (e.currentTarget instanceof HTMLInputElement) {
|
if (e.currentTarget instanceof HTMLInputElement) {
|
||||||
handleTargetInput(e.currentTarget.value);
|
handleTargetInput(e.currentTarget.value);
|
||||||
}
|
}
|
||||||
@@ -181,8 +200,8 @@
|
|||||||
class="flex cursor-pointer flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
|
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"
|
role="link"
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
on:click={() => goto(resolve(`/report/${report.reportID}`))}
|
onclick={() => goto(resolve(`/report/${report.reportID}`))}
|
||||||
on:keydown={(e) => {
|
onkeydown={(e) => {
|
||||||
if (e.key === 'Enter' || e.key === ' ') {
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
goto(resolve(`/report/${report.reportID}`));
|
goto(resolve(`/report/${report.reportID}`));
|
||||||
@@ -204,7 +223,7 @@
|
|||||||
<a
|
<a
|
||||||
href={resolve(`/${report.pasteId}`)}
|
href={resolve(`/${report.pasteId}`)}
|
||||||
class="text-neutral-300 hover:text-white"
|
class="text-neutral-300 hover:text-white"
|
||||||
on:click|stopPropagation
|
onclick={stopPropagation(bubble('click'))}
|
||||||
>
|
>
|
||||||
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
|
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
|
||||||
</a>
|
</a>
|
||||||
@@ -215,7 +234,7 @@
|
|||||||
href={resolve(`/user/${report.targetUsername}`)}
|
href={resolve(`/user/${report.targetUsername}`)}
|
||||||
class="text-neutral-300 hover:text-white"
|
class="text-neutral-300 hover:text-white"
|
||||||
use:tooltip={report.userUUID}
|
use:tooltip={report.userUUID}
|
||||||
on:click|stopPropagation
|
onclick={stopPropagation(bubble('click'))}
|
||||||
>
|
>
|
||||||
{report.targetDisplayName || report.targetUsername}
|
{report.targetDisplayName || report.targetUsername}
|
||||||
</a>
|
</a>
|
||||||
@@ -228,7 +247,7 @@
|
|||||||
href={resolve(`/user/${report.reporterUsername}`)}
|
href={resolve(`/user/${report.reporterUsername}`)}
|
||||||
class="text-neutral-300 hover:text-white"
|
class="text-neutral-300 hover:text-white"
|
||||||
use:tooltip={report.reporterUUID}
|
use:tooltip={report.reporterUUID}
|
||||||
on:click|stopPropagation
|
onclick={stopPropagation(bubble('click'))}
|
||||||
>
|
>
|
||||||
{report.reporterDisplayName || report.reporterUsername}
|
{report.reporterDisplayName || report.reporterUsername}
|
||||||
</a>
|
</a>
|
||||||
@@ -251,7 +270,7 @@
|
|||||||
<div class="mt-6 flex items-center justify-center gap-4">
|
<div class="mt-6 flex items-center justify-center gap-4">
|
||||||
<button
|
<button
|
||||||
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
|
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
|
||||||
on:click={() => applyFilters(data.reports.pagination.page - 1)}
|
onclick={() => applyFilters(data.reports.pagination.page - 1)}
|
||||||
disabled={data.reports.pagination.page <= 1}
|
disabled={data.reports.pagination.page <= 1}
|
||||||
>
|
>
|
||||||
Prev
|
Prev
|
||||||
@@ -261,7 +280,7 @@
|
|||||||
</span>
|
</span>
|
||||||
<button
|
<button
|
||||||
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
|
class="rounded bg-neutral-700 px-3 py-1 disabled:opacity-50"
|
||||||
on:click={() => applyFilters(data.reports.pagination.page + 1)}
|
onclick={() => applyFilters(data.reports.pagination.page + 1)}
|
||||||
disabled={data.reports.pagination.page >= data.reports.pagination.totalPages}
|
disabled={data.reports.pagination.page >= data.reports.pagination.totalPages}
|
||||||
>
|
>
|
||||||
Next
|
Next
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { apiUrl } from '#lib/server/api';
|
||||||
|
import { extractError } from '#lib/utils/misc';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
import type { PageServerLoad } from './$types';
|
||||||
|
|
||||||
|
export const load: PageServerLoad = async ({ url, request }) => {
|
||||||
|
const token = url.searchParams.get('token');
|
||||||
|
if (!token) {
|
||||||
|
throw error(400, 'Reset token is required.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = new Headers(request.headers);
|
||||||
|
const res = await fetch(`${apiUrl}/api/auth/password/reset-info?token=${token}`, { headers });
|
||||||
|
const json = await res.json().catch(() => null);
|
||||||
|
if (!res.ok) {
|
||||||
|
const message = extractError(json);
|
||||||
|
throw error(res.status, message ?? 'Request failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
token,
|
||||||
|
username: typeof json?.username === 'string' ? json.username : undefined,
|
||||||
|
requiresTotp: Boolean(json?.requiresTotp)
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { resolve } from '$app/paths';
|
||||||
|
import { extractError } from '#lib/utils/misc';
|
||||||
|
import { Check, X } from '@lucide/svelte';
|
||||||
|
import { slide, fade } from 'svelte/transition';
|
||||||
|
import type { PageData } from './$types';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
|
let { data }: Props = $props();
|
||||||
|
let password = $state('');
|
||||||
|
let confirmPassword = $state('');
|
||||||
|
let totpCode = $state('');
|
||||||
|
let error = $state('');
|
||||||
|
let message = $state('');
|
||||||
|
let complete = $state(false);
|
||||||
|
let loading = $state(false);
|
||||||
|
let passwordFocused = $state(false);
|
||||||
|
let passwordChecks = $state({
|
||||||
|
minLength: false,
|
||||||
|
maxLength: false,
|
||||||
|
upper: false,
|
||||||
|
lower: false,
|
||||||
|
number: false
|
||||||
|
});
|
||||||
|
let passwordValid = $state(false);
|
||||||
|
|
||||||
|
function validatePassword(pw: string) {
|
||||||
|
passwordChecks.minLength = pw.length >= 8;
|
||||||
|
passwordChecks.maxLength = pw.length <= 128;
|
||||||
|
passwordChecks.upper = /[A-Z]/.test(pw);
|
||||||
|
passwordChecks.lower = /[a-z]/.test(pw);
|
||||||
|
passwordChecks.number = /[0-9]/.test(pw);
|
||||||
|
passwordValid =
|
||||||
|
passwordChecks.minLength &&
|
||||||
|
passwordChecks.maxLength &&
|
||||||
|
passwordChecks.upper &&
|
||||||
|
passwordChecks.lower &&
|
||||||
|
passwordChecks.number;
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
validatePassword(password);
|
||||||
|
});
|
||||||
|
|
||||||
|
async function submit(event: Event) {
|
||||||
|
event.preventDefault();
|
||||||
|
error = '';
|
||||||
|
message = '';
|
||||||
|
|
||||||
|
if (!password || !confirmPassword) {
|
||||||
|
error = 'Both password fields are required.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (password !== confirmPassword) {
|
||||||
|
error = 'Passwords do not match.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!passwordValid) {
|
||||||
|
error =
|
||||||
|
'Password should have at least 8 characters, no more than 128 characters, including uppercase, lowercase, and digits.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
loading = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/password/reset', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
token: data.token,
|
||||||
|
newPassword: password,
|
||||||
|
...(data.requiresTotp ? { totpCode } : {})
|
||||||
|
})
|
||||||
|
});
|
||||||
|
const json = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) {
|
||||||
|
error = extractError(json) || 'Password reset failed.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
complete = true;
|
||||||
|
message = json.message || 'Password reset successfully.';
|
||||||
|
} finally {
|
||||||
|
loading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:head>
|
||||||
|
<title>Reset Password - Sharpbin</title>
|
||||||
|
<meta name="description" content="Set a new password for your Sharpbin account." />
|
||||||
|
</svelte:head>
|
||||||
|
|
||||||
|
<main
|
||||||
|
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
|
||||||
|
>
|
||||||
|
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||||
|
{#if complete}
|
||||||
|
<h1 class="mb-2 text-center text-3xl font-bold">Password Reset</h1>
|
||||||
|
<p class="text-center text-sm text-neutral-400">{message}</p>
|
||||||
|
<p class="mt-4 text-center text-sm text-neutral-400">
|
||||||
|
<a
|
||||||
|
href={resolve('/login')}
|
||||||
|
class="text-neutral-200 transition-colors duration-200 hover:text-white">Back to login</a
|
||||||
|
>
|
||||||
|
</p>
|
||||||
|
{:else}
|
||||||
|
<h1 class="mb-2 text-center text-3xl font-bold">Reset Password</h1>
|
||||||
|
<p class="mb-6 text-center text-sm text-neutral-400">
|
||||||
|
{#if data.username}
|
||||||
|
Reset the password for {data.username}.
|
||||||
|
{:else}
|
||||||
|
Set a new password for your account.
|
||||||
|
{/if}
|
||||||
|
</p>
|
||||||
|
<form onsubmit={submit} class="space-y-4">
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
placeholder="New password"
|
||||||
|
bind:value={password}
|
||||||
|
autocomplete="new-password"
|
||||||
|
required
|
||||||
|
onfocus={() => (passwordFocused = true)}
|
||||||
|
onblur={() => (passwordFocused = false)}
|
||||||
|
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
||||||
|
/>
|
||||||
|
{#if passwordFocused}
|
||||||
|
<ul
|
||||||
|
transition:slide
|
||||||
|
class="space-y-2 rounded border border-neutral-700 bg-neutral-800 p-3 text-sm"
|
||||||
|
>
|
||||||
|
<li
|
||||||
|
class="flex items-center gap-2 {passwordChecks.minLength
|
||||||
|
? 'text-green-400'
|
||||||
|
: 'text-red-400'}"
|
||||||
|
>
|
||||||
|
{#if passwordChecks.minLength}<Check class="h-4 w-4" />{:else}<X
|
||||||
|
class="h-4 w-4"
|
||||||
|
/>{/if}
|
||||||
|
At least 8 characters
|
||||||
|
</li>
|
||||||
|
<li
|
||||||
|
class="flex items-center gap-2 {passwordChecks.maxLength
|
||||||
|
? 'text-green-400'
|
||||||
|
: 'text-red-400'}"
|
||||||
|
>
|
||||||
|
{#if passwordChecks.maxLength}<Check class="h-4 w-4" />{:else}<X
|
||||||
|
class="h-4 w-4"
|
||||||
|
/>{/if}
|
||||||
|
No more than 128 characters
|
||||||
|
</li>
|
||||||
|
<li
|
||||||
|
class="flex items-center gap-2 {passwordChecks.upper
|
||||||
|
? 'text-green-400'
|
||||||
|
: 'text-red-400'}"
|
||||||
|
>
|
||||||
|
{#if passwordChecks.upper}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
|
||||||
|
At least one uppercase letter
|
||||||
|
</li>
|
||||||
|
<li
|
||||||
|
class="flex items-center gap-2 {passwordChecks.lower
|
||||||
|
? 'text-green-400'
|
||||||
|
: 'text-red-400'}"
|
||||||
|
>
|
||||||
|
{#if passwordChecks.lower}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
|
||||||
|
At least one lowercase letter
|
||||||
|
</li>
|
||||||
|
<li
|
||||||
|
class="flex items-center gap-2 {passwordChecks.number
|
||||||
|
? 'text-green-400'
|
||||||
|
: 'text-red-400'}"
|
||||||
|
>
|
||||||
|
{#if passwordChecks.number}<Check class="h-4 w-4" />{:else}<X class="h-4 w-4" />{/if}
|
||||||
|
At least one number
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
{/if}
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
placeholder="Confirm new password"
|
||||||
|
bind:value={confirmPassword}
|
||||||
|
autocomplete="new-password"
|
||||||
|
required
|
||||||
|
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
||||||
|
/>
|
||||||
|
{#if confirmPassword && password !== confirmPassword}
|
||||||
|
<div
|
||||||
|
transition:fade
|
||||||
|
class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
|
||||||
|
>
|
||||||
|
Passwords do not match.
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if data.requiresTotp}
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="TOTP Code"
|
||||||
|
bind:value={totpCode}
|
||||||
|
maxlength="6"
|
||||||
|
inputmode="numeric"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
required
|
||||||
|
oninput={(e) => {
|
||||||
|
if (e.target instanceof HTMLInputElement) {
|
||||||
|
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
|
||||||
|
totpCode = e.target.value;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
|
||||||
|
/>
|
||||||
|
{/if}
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading || !passwordValid || password !== confirmPassword}
|
||||||
|
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{loading ? 'Updating...' : 'Reset Password'}
|
||||||
|
</button>
|
||||||
|
{#if error}
|
||||||
|
<div
|
||||||
|
class="rounded border border-red-900 bg-red-950 p-2 text-sm whitespace-pre-line text-red-200"
|
||||||
|
>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</form>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
@@ -1,13 +1,11 @@
|
|||||||
import type { PageServerLoad } from './$types';
|
import type { PageServerLoad } from './$types';
|
||||||
import { env } from '$env/dynamic/private';
|
import { apiUrl } from '#lib/server/api';
|
||||||
import { error, isHttpError } from '@sveltejs/kit';
|
import { error, isHttpError } from '@sveltejs/kit';
|
||||||
import { extractError } from '$lib/utils/misc';
|
import { extractError } from '#lib/utils/misc';
|
||||||
|
|
||||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ fetch }) => {
|
export const load: PageServerLoad = async ({ fetch }) => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/api/stats`);
|
const res = await fetch(`${apiUrl}/api/stats`);
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const json = await res.json().catch(() => ({}));
|
const json = await res.json().catch(() => ({}));
|
||||||
|
|||||||
@@ -1,13 +1,19 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { PageData } from './$types';
|
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';
|
import { FileText, Users, Database, TrendingUp } from '@lucide/svelte';
|
||||||
|
|
||||||
export let data: PageData;
|
interface Props {
|
||||||
$: stats = data.stats.stats;
|
data: PageData;
|
||||||
|
}
|
||||||
|
|
||||||
$: dailyData = stats.pastes.daily || [];
|
let { data }: Props = $props();
|
||||||
$: maxCount = Math.max(...dailyData.map((d: { count: number; date: number }) => d.count), 5);
|
let stats = $derived(data.stats.stats);
|
||||||
|
|
||||||
|
let dailyData = $derived(stats.pastes.daily || []);
|
||||||
|
let maxCount = $derived(
|
||||||
|
Math.max(...dailyData.map((d: { count: number; date: number }) => d.count), 5)
|
||||||
|
);
|
||||||
|
|
||||||
function getOrdinal(n: number) {
|
function getOrdinal(n: number) {
|
||||||
const s = ['th', 'st', 'nd', 'rd'];
|
const s = ['th', 'st', 'nd', 'rd'];
|
||||||
@@ -74,9 +80,12 @@
|
|||||||
<p class="text-sm text-neutral-400">Total Storage Used</p>
|
<p class="text-sm text-neutral-400">Total Storage Used</p>
|
||||||
<p
|
<p
|
||||||
class="text-2xl font-bold"
|
class="text-2xl font-bold"
|
||||||
use:tooltip={[formatBytes(stats.pastes.trueTotalSizeInBytes), true]}
|
use:tooltip={[
|
||||||
|
`${stats.pastes.totalStoredSizeInBytes != stats.pastes.totalOriginalSizeInBytes ? `Uncompressed Size: ${formatBytes(stats.pastes.totalOriginalSizeInBytes)}` : ''}`,
|
||||||
|
true
|
||||||
|
]}
|
||||||
>
|
>
|
||||||
{formatBytes(stats.pastes.totalSizeInBytes)}
|
{formatBytes(stats.pastes.totalStoredSizeInBytes)}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,25 +1,25 @@
|
|||||||
import type { PageServerLoad } from './$types';
|
import type { PageServerLoad } from './$types';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
import { env } from '$env/dynamic/private';
|
import { apiUrl } from '#lib/server/api';
|
||||||
import { getServerToken } from '$lib/utils/auth';
|
import { getServerToken } from '#lib/utils/auth';
|
||||||
import type { User } from '$lib/types/user';
|
import type { User } from '#lib/types/user';
|
||||||
import type { Paste } from '$lib/types/paste';
|
import type { Paste } from '#lib/types/paste';
|
||||||
import type { Pagination } from '$lib/types/pagination';
|
import type { Pagination } from '#lib/types/pagination';
|
||||||
import type { Report, ReportListResponse } from '$lib/types/report';
|
import type { Report, ReportListResponse } from '#lib/types/report';
|
||||||
|
|
||||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
function decodeJwtRoles(token?: string | null): number {
|
||||||
|
|
||||||
function decodeJwtRoles(token?: string | null): number[] {
|
|
||||||
try {
|
try {
|
||||||
if (!token) return [];
|
if (!token) return 0;
|
||||||
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
|
||||||
const roles = payload?.role;
|
const roles = payload?.role;
|
||||||
if (Array.isArray(roles)) {
|
if (typeof roles === 'number') return roles;
|
||||||
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
|
if (typeof roles === 'string') {
|
||||||
|
const parsed = parseInt(roles, 10);
|
||||||
|
return isNaN(parsed) ? 0 : parsed;
|
||||||
}
|
}
|
||||||
return [];
|
return 0;
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,14 +34,19 @@ function decodeJwtUuid(token?: string | null): string | null {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent }) => {
|
export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent, request }) => {
|
||||||
const token = getServerToken(cookies);
|
const token = getServerToken(cookies);
|
||||||
const { username } = params;
|
const { username } = params;
|
||||||
const { options } = await parent();
|
const { options } = await parent();
|
||||||
const jwtUuid = decodeJwtUuid(token);
|
const jwtUuid = decodeJwtUuid(token);
|
||||||
|
const asGuest = url.searchParams.get('guest') === '1';
|
||||||
|
const headers = new Headers(request.headers);
|
||||||
|
if (token && !asGuest) {
|
||||||
|
headers.set('Authorization', `Bearer ${token}`);
|
||||||
|
}
|
||||||
|
|
||||||
const res = await fetch(`${API_URL}/api/user/${username}`, {
|
const res = await fetch(`${apiUrl}/api/user/${username}`, {
|
||||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined
|
headers: headers
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -60,8 +65,8 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
|
|||||||
const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
|
const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
|
||||||
let reportsTarget: ReportListResponse | null = null;
|
let reportsTarget: ReportListResponse | null = null;
|
||||||
let reportsSubmitted: ReportListResponse | null = null;
|
let reportsSubmitted: ReportListResponse | null = null;
|
||||||
const roles = token ? decodeJwtRoles(token) : [];
|
const roles = token ? decodeJwtRoles(token) : 0;
|
||||||
const canModerate = roles.includes(255) || roles.includes(1);
|
const canModerate = (roles & 4) !== 0 || (roles & 2) !== 0;
|
||||||
|
|
||||||
if (isOwner && reports && reportsPagination) {
|
if (isOwner && reports && reportsPagination) {
|
||||||
reportsSubmitted = {
|
reportsSubmitted = {
|
||||||
@@ -70,20 +75,20 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (token && canModerate && (!reportsSubmitted || !isOwner)) {
|
if (token && !asGuest && canModerate && (!reportsSubmitted || !isOwner)) {
|
||||||
const submittedRes = await fetch(`${API_URL}/api/user/${user.uuid}/reports/submitted`, {
|
headers.set('Authorization', `Bearer ${token}`);
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
const submittedRes = await fetch(`${apiUrl}/api/report/users/${user.uuid}/reports/submitted`, {
|
||||||
|
headers: headers
|
||||||
});
|
});
|
||||||
if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
|
if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (token && !isOwner) {
|
if (token && !asGuest && !isOwner && canModerate) {
|
||||||
if (canModerate) {
|
headers.set('Authorization', `Bearer ${token}`);
|
||||||
const r = await fetch(`${API_URL}/api/user/${user.uuid}/reports`, {
|
const r = await fetch(`${apiUrl}/api/report/users/${user.uuid}/reports`, {
|
||||||
headers: { Authorization: `Bearer ${token}` }
|
headers: headers
|
||||||
});
|
});
|
||||||
if (r.ok) reportsTarget = await r.json();
|
if (r.ok) reportsTarget = await r.json();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
|||||||
|
import type { RequestEvent } from '@sveltejs/kit';
|
||||||
|
import { error, redirect } from '@sveltejs/kit';
|
||||||
|
import { apiUrl } from '#lib/server/api';
|
||||||
|
import { getServerToken } from '#lib/utils/auth';
|
||||||
|
|
||||||
|
export const load = async ({ params, fetch, cookies }: RequestEvent) => {
|
||||||
|
const token = getServerToken(cookies);
|
||||||
|
const uuid = (params as Record<string, string | undefined>).uuid;
|
||||||
|
|
||||||
|
if (!uuid) throw error(404, 'User not found');
|
||||||
|
|
||||||
|
const res = await fetch(`${apiUrl}/api/user/uuid/${uuid}`, {
|
||||||
|
headers: token ? { Authorization: `Bearer ${token}` } : undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
const { message } = await res.json().catch(() => ({}));
|
||||||
|
throw error(res.status, message ?? 'Request failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const { user } = (await res.json()) as { user: { username: string } };
|
||||||
|
throw redirect(302, `/user/${encodeURIComponent(user.username)}`);
|
||||||
|
};
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { apiUrl } from '#lib/server/api';
|
||||||
|
import { extractError } from '#lib/utils/misc';
|
||||||
|
import { error } from '@sveltejs/kit';
|
||||||
|
|
||||||
|
export const load = async ({ url, request }) => {
|
||||||
|
const token = url.searchParams.get('token');
|
||||||
|
if (token) {
|
||||||
|
const headers = new Headers(request.headers);
|
||||||
|
const res = await fetch(`${apiUrl}/api/auth/verify-email?token=${token}`, { headers });
|
||||||
|
if (!res.ok) {
|
||||||
|
const json = await res.json().catch();
|
||||||
|
const message = extractError(json);
|
||||||
|
throw error(res.status, message ?? 'Request failed');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<main
|
||||||
|
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="w-[95%] max-w-7xl rounded border-2
|
||||||
|
border-neutral-800 bg-neutral-900 p-6 text-center"
|
||||||
|
>
|
||||||
|
<h1 class="mb-4 text-4xl font-bold">Email verified.</h1>
|
||||||
|
<p class="mb-2 text-lg">You may close this page.</p>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
# allow crawling everything by default
|
|
||||||
User-agent: *
|
User-agent: *
|
||||||
Disallow:
|
Allow: /$
|
||||||
|
Allow: /recent
|
||||||
|
Allow: /stats
|
||||||
|
Allow: /user/
|
||||||
|
Disallow: /api/
|
||||||
|
Disallow: /login
|
||||||
|
Disallow: /register
|
||||||
|
Disallow: /verify-email
|
||||||
|
Disallow: /report/
|
||||||
|
Disallow: /reports
|
||||||
|
Disallow: /health
|
||||||
|
Disallow: /raw/
|
||||||
|
|||||||
@@ -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;
|
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
{
|
{
|
||||||
"extends": "./.svelte-kit/tsconfig.json",
|
"extends": "$app/tsconfig",
|
||||||
|
"include": ["src", "test", "*"],
|
||||||
|
"exclude": ["src/service-worker"],
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"rewriteRelativeImportExtensions": true,
|
"rewriteRelativeImportExtensions": true,
|
||||||
"allowJs": true,
|
"allowJs": true,
|
||||||
@@ -10,10 +12,13 @@
|
|||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
"sourceMap": true,
|
"sourceMap": true,
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"moduleResolution": "bundler"
|
"moduleResolution": "bundler",
|
||||||
|
"paths": {
|
||||||
|
"#lib/*": ["./src/lib/*"]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
|
// 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
|
// 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
|
// the generated config; see https://svelte.dev/docs/kit/configuration#typescript
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import tailwindcss from '@tailwindcss/vite';
|
import tailwindcss from '@tailwindcss/vite';
|
||||||
import { sveltekit } from '@sveltejs/kit/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 { defineConfig } from 'vite';
|
||||||
import { readFileSync } from 'fs';
|
import { readFileSync } from 'fs';
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
@@ -14,9 +16,10 @@ const allowedHosts = process.env.VITE_ALLOWED_HOSTS
|
|||||||
: ['localhost'];
|
: ['localhost'];
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [tailwindcss(), sveltekit()],
|
plugins: [tailwindcss(), sveltekit({ adapter: adapter(), preprocess: vitePreprocess() })],
|
||||||
define: {
|
define: {
|
||||||
__APP_VERSION__: JSON.stringify(pkg.version)
|
__APP_VERSION__: JSON.stringify(pkg.version),
|
||||||
|
COMMIT_HASH: JSON.stringify(process.env.GIT_COMMIT_HASH || 'unknown')
|
||||||
},
|
},
|
||||||
server: {
|
server: {
|
||||||
host: true,
|
host: true,
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using SharpbinV3.Server.Extensions;
|
||||||
|
using SharpbinV3.Server.Services;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.Authentication
|
||||||
|
{
|
||||||
|
public sealed class ApiKeyAuthenticationHandler(
|
||||||
|
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||||
|
ILoggerFactory logger,
|
||||||
|
UrlEncoder encoder,
|
||||||
|
ApiKeyService apiKeyService
|
||||||
|
) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||||
|
{
|
||||||
|
private readonly ApiKeyService _apiKeyService = apiKeyService;
|
||||||
|
|
||||||
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||||
|
{
|
||||||
|
var apiKeyString = Context.GetApiKey();
|
||||||
|
if (string.IsNullOrEmpty(apiKeyString))
|
||||||
|
return AuthenticateResult.NoResult();
|
||||||
|
|
||||||
|
var apiKey = await _apiKeyService.GetByKeyAsync(apiKeyString);
|
||||||
|
if (apiKey == null || apiKey.User == null)
|
||||||
|
return AuthenticateResult.Fail("Invalid API key.");
|
||||||
|
|
||||||
|
var claims = new List<Claim>
|
||||||
|
{
|
||||||
|
new("uuid", apiKey.User.UUID.ToString()),
|
||||||
|
new("username", apiKey.User.Username ?? ""),
|
||||||
|
new("displayname", apiKey.User.DisplayName ?? ""),
|
||||||
|
new("totp_enabled", (apiKey.User.Totp != null).ToString()),
|
||||||
|
new("roles", ((int)apiKey.User.Roles).ToString()),
|
||||||
|
new("is_banned", apiKey.User.IsBanned.ToString()),
|
||||||
|
};
|
||||||
|
|
||||||
|
var identity = new ClaimsIdentity(claims, AuthSchemes.ApiKey);
|
||||||
|
var principal = new ClaimsPrincipal(identity);
|
||||||
|
var ticket = new AuthenticationTicket(principal, AuthSchemes.ApiKey);
|
||||||
|
|
||||||
|
Context.SetApiKeyContext(apiKey);
|
||||||
|
await _apiKeyService.UpdateLastUsedAsync(apiKey.UUID);
|
||||||
|
|
||||||
|
return AuthenticateResult.Success(ticket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace SharpbinV3.Server.Authentication
|
||||||
|
{
|
||||||
|
public static class AuthSchemes
|
||||||
|
{
|
||||||
|
public const string Combined = "Combined";
|
||||||
|
public const string ApiKey = "ApiKey";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using SharpbinV3.Server.Extensions;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.Authorization
|
namespace SharpbinV3.Server.Authorization
|
||||||
{
|
{
|
||||||
@@ -9,12 +10,29 @@ namespace SharpbinV3.Server.Authorization
|
|||||||
|
|
||||||
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
|
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, NotBannedRequirement requirement)
|
||||||
{
|
{
|
||||||
|
var httpContext = context.Resource as HttpContext;
|
||||||
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
|
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
|
||||||
|
|
||||||
|
if (!isAuthenticated && httpContext != null)
|
||||||
|
{
|
||||||
|
var apiKey = httpContext.GetApiKeyFromContext();
|
||||||
|
if (apiKey != null)
|
||||||
|
{
|
||||||
|
isAuthenticated = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (_requireAuth && !isAuthenticated)
|
if (_requireAuth && !isAuthenticated)
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
|
|
||||||
var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403");
|
var isBanned =
|
||||||
|
bool.TryParse(context.User.Claims.FirstOrDefault(c => c.Type == "is_banned")?.Value, out var parsedIsBanned) && parsedIsBanned;
|
||||||
|
|
||||||
|
if (!isBanned && httpContext?.GetJwtUser()?.IsBanned == true)
|
||||||
|
isBanned = true;
|
||||||
|
|
||||||
|
if (httpContext?.GetApiKeyFromContext()?.User?.IsBanned == true)
|
||||||
|
isBanned = true;
|
||||||
|
|
||||||
if (!isBanned)
|
if (!isBanned)
|
||||||
context.Succeed(requirement);
|
context.Succeed(requirement);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ using Microsoft.Extensions.Options;
|
|||||||
using SharpbinV3.Server.Data;
|
using SharpbinV3.Server.Data;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
using SharpbinV3.Server.DTOs;
|
using SharpbinV3.Server.DTOs;
|
||||||
|
using SharpbinV3.Server.DTOs.ApiKey;
|
||||||
using SharpbinV3.Server.DTOs.Auth;
|
using SharpbinV3.Server.DTOs.Auth;
|
||||||
using SharpbinV3.Server.DTOs.User;
|
using SharpbinV3.Server.DTOs.User;
|
||||||
using SharpbinV3.Server.Extensions;
|
using SharpbinV3.Server.Extensions;
|
||||||
@@ -22,6 +23,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
public class AuthController(
|
public class AuthController(
|
||||||
UserService userService,
|
UserService userService,
|
||||||
AuthService authService,
|
AuthService authService,
|
||||||
|
ApiKeyService apiKeyService,
|
||||||
IOptions<AuthSettings> options,
|
IOptions<AuthSettings> options,
|
||||||
VerificationService verification,
|
VerificationService verification,
|
||||||
TotpVerificationProvider totp,
|
TotpVerificationProvider totp,
|
||||||
@@ -30,6 +32,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
{
|
{
|
||||||
private readonly AuthService _authService = authService;
|
private readonly AuthService _authService = authService;
|
||||||
private readonly UserService _userService = userService;
|
private readonly UserService _userService = userService;
|
||||||
|
private readonly ApiKeyService _apiKeyService = apiKeyService;
|
||||||
private readonly VerificationService _verification = verification;
|
private readonly VerificationService _verification = verification;
|
||||||
private readonly TotpVerificationProvider _totp = totp;
|
private readonly TotpVerificationProvider _totp = totp;
|
||||||
private readonly AppDbContext _db = db;
|
private readonly AppDbContext _db = db;
|
||||||
@@ -49,16 +52,36 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
var existingUser = await _userService.GetByUsername(request.Username);
|
var existingUser = await _userService.GetByUsername(request.Username);
|
||||||
if (existingUser != null)
|
if (existingUser != null)
|
||||||
return Conflict(new { success = false, message = "Username already exists." });
|
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)
|
if (existingEmailUser != null)
|
||||||
return Conflict(new { success = false, message = "Email already in use." });
|
return Conflict(new { success = false, message = "Email already in use." });
|
||||||
}
|
}
|
||||||
if (!string.IsNullOrEmpty(request.DisplayName) && request.DisplayName.Length > 26)
|
if (!string.IsNullOrEmpty(request.DisplayName) && request.DisplayName.Length > 26)
|
||||||
return BadRequest(new { success = false, message = "Display name should not exceed 26 characters." });
|
return BadRequest(new { success = false, message = "Display name should not exceed 26 characters." });
|
||||||
|
|
||||||
var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
|
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);
|
||||||
|
|
||||||
return Ok(
|
return Ok(
|
||||||
new
|
new
|
||||||
{
|
{
|
||||||
@@ -71,6 +94,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
DisplayName = user.DisplayName,
|
DisplayName = user.DisplayName,
|
||||||
Email = user.Email,
|
Email = user.Email,
|
||||||
Roles = user.Roles,
|
Roles = user.Roles,
|
||||||
|
IsBanned = user.IsBanned,
|
||||||
Visibility = user.Visibility,
|
Visibility = user.Visibility,
|
||||||
LastLogin = user.LastLogin,
|
LastLogin = user.LastLogin,
|
||||||
},
|
},
|
||||||
@@ -159,12 +183,13 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
{
|
{
|
||||||
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
|
cf_turnstile_site_key = string.IsNullOrEmpty(authSettings.CF_Turnstile_SiteKey) ? null : authSettings.CF_Turnstile_SiteKey,
|
||||||
registration_enabled = authSettings.Registration_Enabled,
|
registration_enabled = authSettings.Registration_Enabled,
|
||||||
|
admins_require_2fa = authSettings.Admins_Require_2FA,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[Authorize]
|
[Authorize(Policy = "JwtOnly")]
|
||||||
[Route("totp/enroll")]
|
[Route("totp/enroll")]
|
||||||
public async Task<IActionResult> StartTotpEnrollment()
|
public async Task<IActionResult> StartTotpEnrollment()
|
||||||
{
|
{
|
||||||
@@ -187,16 +212,12 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[Authorize]
|
[Authorize(Policy = "JwtOnly")]
|
||||||
[Route("totp/enable")]
|
[Route("totp/enable")]
|
||||||
[EnableRateLimiting("Sensitive")]
|
[EnableRateLimiting("Sensitive")]
|
||||||
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
|
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
|
||||||
{
|
{
|
||||||
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
|
var uuid = Guid.Parse(User.FindFirst("uuid")!.Value);
|
||||||
if (string.IsNullOrEmpty(uuidClaim))
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var uuid = Guid.Parse(uuidClaim);
|
|
||||||
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
|
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
|
||||||
return BadRequest(new { success = false, message = "Secret and code are required." });
|
return BadRequest(new { success = false, message = "Secret and code are required." });
|
||||||
|
|
||||||
@@ -221,7 +242,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[Authorize]
|
[Authorize(Policy = "JwtOnly")]
|
||||||
[Route("totp/disable")]
|
[Route("totp/disable")]
|
||||||
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
|
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
|
||||||
{
|
{
|
||||||
@@ -240,5 +261,341 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
return Ok(new { success = true, message = "TOTP disabled." });
|
return Ok(new { success = true, message = "TOTP disabled." });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[Authorize(Policy = "JwtOnly")]
|
||||||
|
[Route("apikey/create")]
|
||||||
|
[EnableRateLimiting("Strict")]
|
||||||
|
public async Task<IActionResult> CreateApiKey([FromBody] CreateApiKeyRequest request)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Name))
|
||||||
|
return BadRequest(new { success = false, message = "API key name is required." });
|
||||||
|
if (request.Name.Length > 26)
|
||||||
|
return BadRequest(new { success = false, message = "API key name must not exceed 26 characters." });
|
||||||
|
|
||||||
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
|
if (user == null)
|
||||||
|
return BadRequest(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
var existingKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
|
||||||
|
if (existingKeys.Count >= 10)
|
||||||
|
return BadRequest(new { success = false, message = "API key limit reached. Please delete existing keys before creating new ones." });
|
||||||
|
|
||||||
|
var (apiKey, key) = await _apiKeyService.CreateAsync(user.UUID, request.Name);
|
||||||
|
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
message = "API key created. Save it now as you won't be able to see it again.",
|
||||||
|
apiKey = new ApiKeyResponseDto
|
||||||
|
{
|
||||||
|
UUID = apiKey.UUID,
|
||||||
|
Key = key,
|
||||||
|
Name = apiKey.Name,
|
||||||
|
CreatedAt = apiKey.CreatedAt,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
[Authorize]
|
||||||
|
[Route("apikey/list")]
|
||||||
|
public async Task<IActionResult> ListApiKeys()
|
||||||
|
{
|
||||||
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
|
if (user == null)
|
||||||
|
return BadRequest(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
var apiKeys = await _apiKeyService.GetUserKeysAsync(user.UUID);
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
apiKeys = apiKeys
|
||||||
|
.Select(k => new ApiKeyListItemDto
|
||||||
|
{
|
||||||
|
UUID = k.UUID,
|
||||||
|
Name = k.Name,
|
||||||
|
CreatedAt = k.CreatedAt,
|
||||||
|
LastUsedAt = k.LastUsedAt,
|
||||||
|
})
|
||||||
|
.ToList(),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete]
|
||||||
|
[Authorize(Policy = "JwtOnly")]
|
||||||
|
[Route("apikey/{uuid}")]
|
||||||
|
public async Task<IActionResult> DeleteApiKey(string uuid)
|
||||||
|
{
|
||||||
|
if (!Guid.TryParse(uuid, out var keyUUID))
|
||||||
|
return BadRequest(new { success = false, message = "Invalid API key UUID." });
|
||||||
|
|
||||||
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
|
if (user == null)
|
||||||
|
return BadRequest(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
var deleted = await _apiKeyService.DeleteAsync(user.UUID, keyUUID);
|
||||||
|
if (!deleted)
|
||||||
|
return NotFound(new { success = false, message = "API key not found." });
|
||||||
|
|
||||||
|
return Ok(new { success = true, message = "API key deleted." });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
[Route("verify-email")]
|
||||||
|
public async Task<IActionResult> VerifyEmail(string token)
|
||||||
|
{
|
||||||
|
(bool verifiedEmail, string message) = await _authService.VerifyEmailVerificationToken(token);
|
||||||
|
if (verifiedEmail)
|
||||||
|
return Ok(new { success = true, message });
|
||||||
|
else
|
||||||
|
return BadRequest(new { success = false, message });
|
||||||
|
}
|
||||||
|
|
||||||
|
[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 });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
using Microsoft.AspNetCore.Authorization;
|
using System.Text;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.RateLimiting;
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
|
using SharpbinV3.Server.Data.Enums;
|
||||||
using SharpbinV3.Server.DTOs.Paste;
|
using SharpbinV3.Server.DTOs.Paste;
|
||||||
using SharpbinV3.Server.DTOs.Report;
|
using SharpbinV3.Server.DTOs.Report;
|
||||||
using SharpbinV3.Server.DTOs.User;
|
using SharpbinV3.Server.DTOs.User;
|
||||||
@@ -17,17 +19,21 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
public class PasteController(
|
public class PasteController(
|
||||||
PasteService pasteService,
|
PasteService pasteService,
|
||||||
|
CommentService commentService,
|
||||||
VerificationService verificationService,
|
VerificationService verificationService,
|
||||||
AuthService authService,
|
AuthService authService,
|
||||||
ReportService reportService,
|
ReportService reportService,
|
||||||
|
ICompressionService compressionService,
|
||||||
IOptions<PasteSettings> options,
|
IOptions<PasteSettings> options,
|
||||||
IOptions<AuthSettings> authSettings
|
IOptions<AuthSettings> authSettings
|
||||||
) : ControllerBase
|
) : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly PasteService _pasteService = pasteService;
|
private readonly PasteService _pasteService = pasteService;
|
||||||
|
private readonly CommentService _commentService = commentService;
|
||||||
private readonly VerificationService _verificationService = verificationService;
|
private readonly VerificationService _verificationService = verificationService;
|
||||||
private readonly AuthService _authService = authService;
|
private readonly AuthService _authService = authService;
|
||||||
private readonly ReportService _reportService = reportService;
|
private readonly ReportService _reportService = reportService;
|
||||||
|
private readonly ICompressionService _compressionService = compressionService;
|
||||||
private readonly PasteSettings _pasteSettings = options.Value;
|
private readonly PasteSettings _pasteSettings = options.Value;
|
||||||
private readonly AuthSettings _authSettings = authSettings.Value;
|
private readonly AuthSettings _authSettings = authSettings.Value;
|
||||||
|
|
||||||
@@ -38,9 +44,9 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
public async Task<IActionResult> CreatePaste(
|
public async Task<IActionResult> CreatePaste(
|
||||||
string title = "",
|
string title = "",
|
||||||
string syntax = "plaintext",
|
string syntax = "plaintext",
|
||||||
int visibility = 0,
|
Visibility visibility = Visibility.Public,
|
||||||
long expiresAt = 0,
|
long expiresAt = 0,
|
||||||
string? token = null
|
string? verificationToken = null
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
if (!_pasteService.ValidateExpiresAt(expiresAt))
|
if (!_pasteService.ValidateExpiresAt(expiresAt))
|
||||||
@@ -60,11 +66,18 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
|
new { success = false, message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }
|
||||||
);
|
);
|
||||||
|
|
||||||
if (
|
if (_pasteSettings.RequiresVerification && !HttpContext.IsApiKeyAuthenticated())
|
||||||
_pasteSettings.RequiresVerification
|
{
|
||||||
&& !await _verificationService.VerifyAsync(new VerificationContext { Token = token, Ip = HttpContext.GetRequestIP() })
|
var providedApiKey = HttpContext.GetApiKey();
|
||||||
)
|
if (providedApiKey != null)
|
||||||
return BadRequest(new { success = false, message = "Verification failed." });
|
return BadRequest(new { success = false, message = "Invalid API key." });
|
||||||
|
|
||||||
|
var verifyResult = await _verificationService.VerifyAsync(
|
||||||
|
new VerificationContext { Token = verificationToken, Ip = HttpContext.GetRequestIP() }
|
||||||
|
);
|
||||||
|
if (!verifyResult)
|
||||||
|
return BadRequest(new { success = false, message = "Verification failed." });
|
||||||
|
}
|
||||||
|
|
||||||
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
|
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt, _pasteSettings.EnablePasteCompression);
|
||||||
@@ -75,24 +88,30 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
UUID = paste.UUID,
|
UUID = paste.UUID,
|
||||||
CreatedAt = paste.CreatedAt,
|
CreatedAt = paste.CreatedAt,
|
||||||
IsCompressed = paste.IsCompressed,
|
IsCompressed = paste.IsCompressed,
|
||||||
Size = paste.Size,
|
StoredSize = paste.StoredSize,
|
||||||
TrueSize = paste.TrueSize,
|
OriginalSize = paste.OriginalSize,
|
||||||
ExpiresAt = paste.ExpiresAt,
|
ExpiresAt = paste.ExpiresAt,
|
||||||
|
Visibility = paste.Visibility,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
|
[EnableRateLimiting("NoLimit")]
|
||||||
[Route("{id}")]
|
[Route("{id}")]
|
||||||
public async Task<IActionResult> GetPasteByID(string id)
|
public async Task<IActionResult> GetPasteByID(string id)
|
||||||
{
|
{
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||||
return NotFound(new { success = false, message = "Paste not found" });
|
return NotFound(new { success = false, message = "Paste not found" });
|
||||||
|
|
||||||
var jwtUser = HttpContext.GetJwtUser();
|
var jwtUser = HttpContext.GetJwtUser();
|
||||||
|
PasteInteraction? userInteraction = null;
|
||||||
|
if (jwtUser != null)
|
||||||
|
userInteraction = await _pasteService.GetUserInteraction(paste, jwtUser.UUID);
|
||||||
|
|
||||||
int? reportCount = null;
|
int? reportCount = null;
|
||||||
if (jwtUser != null && jwtUser.Roles.Any(r => r == 1 || r == 255))
|
if (jwtUser != null && (jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator)))
|
||||||
{
|
{
|
||||||
var query = new ReportQuery { PastePID = paste.PID };
|
var query = new ReportQuery { PastePID = paste.PID };
|
||||||
reportCount = await _reportService.GetReportCount(query);
|
reportCount = await _reportService.GetReportCount(query);
|
||||||
@@ -108,8 +127,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
UUID = paste.UUID,
|
UUID = paste.UUID,
|
||||||
CreatedAt = paste.CreatedAt,
|
CreatedAt = paste.CreatedAt,
|
||||||
Title = paste.Title,
|
Title = paste.Title,
|
||||||
Size = paste.Size,
|
StoredSize = paste.StoredSize,
|
||||||
TrueSize = paste.TrueSize,
|
OriginalSize = paste.OriginalSize,
|
||||||
IsCompressed = paste.IsCompressed,
|
IsCompressed = paste.IsCompressed,
|
||||||
Views = paste.Views,
|
Views = paste.Views,
|
||||||
Syntax = paste.Syntax,
|
Syntax = paste.Syntax,
|
||||||
@@ -117,6 +136,9 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
ExpiresAt = paste.ExpiresAt,
|
ExpiresAt = paste.ExpiresAt,
|
||||||
EditedAt = paste.EditedAt,
|
EditedAt = paste.EditedAt,
|
||||||
ReportCount = reportCount,
|
ReportCount = reportCount,
|
||||||
|
UserReaction = userInteraction != null ? userInteraction.Type : null,
|
||||||
|
Likes = paste.PositiveInteractionCount,
|
||||||
|
Dislikes = paste.NegativeInteractionCount,
|
||||||
Author =
|
Author =
|
||||||
paste.User != null && paste.User.Visibility == 0
|
paste.User != null && paste.User.Visibility == 0
|
||||||
? new UserSimpleDto
|
? new UserSimpleDto
|
||||||
@@ -127,6 +149,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
DisplayName = paste.User.DisplayName,
|
DisplayName = paste.User.DisplayName,
|
||||||
Visibility = paste.User.Visibility,
|
Visibility = paste.User.Visibility,
|
||||||
Roles = paste.User.Roles,
|
Roles = paste.User.Roles,
|
||||||
|
IsBanned = paste.User.IsBanned,
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
},
|
},
|
||||||
@@ -135,11 +158,12 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
|
[EnableRateLimiting("NoLimit")]
|
||||||
[Route("{id}/raw")]
|
[Route("{id}/raw")]
|
||||||
public async Task<IActionResult> GetRawPasteByID(string id)
|
public async Task<IActionResult> GetRawPasteByID(string id)
|
||||||
{
|
{
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||||
return NotFound();
|
return NotFound();
|
||||||
if (paste.IsCompressed)
|
if (paste.IsCompressed)
|
||||||
Response.Headers.Append("Content-Encoding", "gzip");
|
Response.Headers.Append("Content-Encoding", "gzip");
|
||||||
@@ -149,26 +173,26 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
|
|
||||||
[HttpPut]
|
[HttpPut]
|
||||||
[Route("{id}")]
|
[Route("{id}")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
public async Task<IActionResult> EditPaste(string id)
|
public async Task<IActionResult> EditPaste(string id)
|
||||||
{
|
{
|
||||||
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
string content = await new StreamReader(Request.Body).ReadToEndAsync();
|
||||||
if (content == null || id == null)
|
if (content == null || id == null)
|
||||||
return StatusCode(400, new { success = false, message = "Invalid request." });
|
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);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null)
|
||||||
return StatusCode(404, new { success = false, message = "Paste not found." });
|
return StatusCode(404, new { success = false, message = "Paste not found." });
|
||||||
|
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser()!;
|
||||||
if (user == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." });
|
||||||
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
|
||||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
|
||||||
|
|
||||||
bool result = await _pasteService.EditText(paste, content);
|
bool result = await _pasteService.EditText(paste, content);
|
||||||
if (!result)
|
if (!result)
|
||||||
@@ -178,23 +202,20 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
|
|
||||||
[HttpPatch]
|
[HttpPatch]
|
||||||
[Route("{id}")]
|
[Route("{id}")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
|
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
|
||||||
{
|
{
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null)
|
||||||
return NotFound(new { success = false, message = "Paste not found." });
|
return NotFound(new { success = false, message = "Paste not found." });
|
||||||
|
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser()!;
|
||||||
if (user == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||||
|
|
||||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to modify this paste." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to modify this paste." });
|
||||||
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
|
||||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
|
||||||
if (request.Title != null)
|
if (request.Title != null)
|
||||||
paste.Title = request.Title;
|
paste.Title = request.Title;
|
||||||
if (request.Syntax != null)
|
if (request.Syntax != null)
|
||||||
@@ -225,8 +246,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
UUID = newPaste.UUID,
|
UUID = newPaste.UUID,
|
||||||
CreatedAt = newPaste.CreatedAt,
|
CreatedAt = newPaste.CreatedAt,
|
||||||
Title = newPaste.Title,
|
Title = newPaste.Title,
|
||||||
Size = newPaste.Size,
|
OriginalSize = newPaste.OriginalSize,
|
||||||
TrueSize = newPaste.TrueSize,
|
StoredSize = newPaste.StoredSize,
|
||||||
IsCompressed = newPaste.IsCompressed,
|
IsCompressed = newPaste.IsCompressed,
|
||||||
Views = newPaste.Views,
|
Views = newPaste.Views,
|
||||||
Syntax = newPaste.Syntax,
|
Syntax = newPaste.Syntax,
|
||||||
@@ -239,22 +260,18 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
|
|
||||||
[HttpDelete]
|
[HttpDelete]
|
||||||
[Route("{id}")]
|
[Route("{id}")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
public async Task<IActionResult> DeletePaste(string id)
|
public async Task<IActionResult> DeletePaste(string id)
|
||||||
{
|
{
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null)
|
||||||
return NotFound(new { success = false, message = "Paste not found." });
|
return NotFound(new { success = false, message = "Paste not found." });
|
||||||
|
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser()!;
|
||||||
if (user == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this paste." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to delete this paste." });
|
||||||
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
|
||||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
|
||||||
|
|
||||||
bool result = await _pasteService.Delete(paste);
|
bool result = await _pasteService.Delete(paste);
|
||||||
if (!result)
|
if (!result)
|
||||||
@@ -267,6 +284,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[Authorize(Policy = "NotBanned")]
|
[Authorize(Policy = "NotBanned")]
|
||||||
public async Task<IActionResult> RecordPasteView(string id)
|
public async Task<IActionResult> RecordPasteView(string id)
|
||||||
{
|
{
|
||||||
|
if (HttpContext.IsKnownBot())
|
||||||
|
return Ok(new { success = true, message = "View not recorded for known bot." });
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null)
|
||||||
return NotFound(new { success = false, message = "Paste not found." });
|
return NotFound(new { success = false, message = "Paste not found." });
|
||||||
@@ -279,6 +298,11 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
)
|
)
|
||||||
return Unauthorized(new { success = false, message = "Invalid API key." });
|
return Unauthorized(new { success = false, message = "Invalid API key." });
|
||||||
|
|
||||||
|
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 != 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);
|
var result = await _pasteService.RecordView(paste, HttpContext);
|
||||||
|
|
||||||
if (result.paste is null && !result.alreadyExists)
|
if (result.paste is null && !result.alreadyExists)
|
||||||
@@ -290,122 +314,69 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[Route("{id}/report")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Route("{id}/reaction")]
|
||||||
[EnableRateLimiting("Sensitive")]
|
public async Task<IActionResult> ReactToPaste(string id, [FromBody] ReactToPasteDto request)
|
||||||
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
|
|
||||||
{
|
{
|
||||||
var paste = await _pasteService.Get(id);
|
var paste = await _pasteService.Get(id);
|
||||||
if (paste == null)
|
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||||
return NotFound(new { success = false, message = "Paste not found." });
|
return NotFound(new { success = false, message = "Paste not found" });
|
||||||
var user = HttpContext.GetJwtUser();
|
|
||||||
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
if (user == null)
|
if (user == null)
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
return Unauthorized(new { success = false, message = "User not authenticated." });
|
||||||
|
if (paste.AuthorUUID == user.UUID)
|
||||||
|
return BadRequest(new { success = false, message = "You cannot react to your own paste." });
|
||||||
|
|
||||||
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
var existingInteraction = await _pasteService.GetUserInteraction(paste, user.UUID);
|
||||||
if (!Enum.IsDefined(reportType))
|
|
||||||
return BadRequest(new { success = false, message = "Invalid report type." });
|
|
||||||
|
|
||||||
if (
|
if (request.Reaction.HasValue)
|
||||||
!await _verificationService.VerifyAsync(
|
{
|
||||||
new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
|
if (existingInteraction == null)
|
||||||
)
|
{
|
||||||
)
|
var created = await _pasteService.RecordInteraction(paste, user, request.Reaction.Value);
|
||||||
return BadRequest(new { success = false, message = "Verification failed." });
|
if (created == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "Could not save reaction." });
|
||||||
|
}
|
||||||
|
else if (existingInteraction.Type != request.Reaction.Value)
|
||||||
|
{
|
||||||
|
var removed = await _pasteService.RemoveInteraction(paste, user);
|
||||||
|
if (!removed)
|
||||||
|
return StatusCode(500, new { success = false, message = "Could not update reaction." });
|
||||||
|
|
||||||
Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description);
|
var created = await _pasteService.RecordInteraction(paste, user, request.Reaction.Value);
|
||||||
if (report == null)
|
if (created == null)
|
||||||
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
|
return StatusCode(500, new { success = false, message = "Could not update reaction." });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (existingInteraction != null)
|
||||||
|
{
|
||||||
|
var removed = await _pasteService.RemoveInteraction(paste, user);
|
||||||
|
if (!removed)
|
||||||
|
return StatusCode(500, new { success = false, message = "Could not remove reaction." });
|
||||||
|
}
|
||||||
|
|
||||||
|
var updatedPaste = await _pasteService.Get(id);
|
||||||
|
if (updatedPaste == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "Could not load updated paste." });
|
||||||
|
|
||||||
|
var updatedInteraction = await _pasteService.GetUserInteraction(updatedPaste, user.UUID);
|
||||||
|
|
||||||
return Ok(
|
return Ok(
|
||||||
new
|
new
|
||||||
{
|
{
|
||||||
success = true,
|
success = true,
|
||||||
message = "Paste reported successfully.",
|
reaction = new PasteReactionResponseDto
|
||||||
report = new ReportResponseDto
|
|
||||||
{
|
{
|
||||||
ReportID = report.ReportID,
|
PasteID = updatedPaste.ID,
|
||||||
Type = report.Type,
|
Likes = updatedPaste.PositiveInteractionCount,
|
||||||
Status = report.Status,
|
Dislikes = updatedPaste.NegativeInteractionCount,
|
||||||
Description = report.Description,
|
UserReaction = updatedInteraction?.Type,
|
||||||
CreatedAt = report.CreatedAt,
|
|
||||||
UpdatedAt = report.UpdatedAt,
|
|
||||||
ReporterUUID = report.ReporterUUID,
|
|
||||||
TargetType = report.TargetType,
|
|
||||||
UserUUID = report.UserUUID,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPatch]
|
|
||||||
[Route("{id}/report/{reportId}")]
|
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
|
||||||
[EnableRateLimiting("Sensitive")]
|
|
||||||
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
|
|
||||||
{
|
|
||||||
var paste = await _pasteService.Get(id);
|
|
||||||
if (paste == null)
|
|
||||||
return NotFound(new { success = false, message = "Paste not found." });
|
|
||||||
|
|
||||||
var report = await _reportService.GetReportByID(reportId);
|
|
||||||
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
|
|
||||||
return NotFound(new { success = false, message = "Report not found." });
|
|
||||||
|
|
||||||
var user = HttpContext.GetJwtUser();
|
|
||||||
if (user == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
|
||||||
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." });
|
|
||||||
|
|
||||||
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
|
||||||
if (!Enum.IsDefined(reportType))
|
|
||||||
return BadRequest(new { success = false, message = "Invalid report type." });
|
|
||||||
|
|
||||||
report.Type = reportType;
|
|
||||||
report.Description = request.Description;
|
|
||||||
|
|
||||||
var updatedReport = await _reportService.UpdateReport(report);
|
|
||||||
if (updatedReport == null)
|
|
||||||
return StatusCode(500, new { success = false, message = "An error occurred while updating the report." });
|
|
||||||
|
|
||||||
return Ok(new { success = true, message = "Report updated successfully." });
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpDelete]
|
|
||||||
[Route("{id}/report/{reportId}")]
|
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
|
||||||
[EnableRateLimiting("Sensitive")]
|
|
||||||
public async Task<IActionResult> DeletePasteReport(string id, int reportId)
|
|
||||||
{
|
|
||||||
var paste = await _pasteService.Get(id);
|
|
||||||
if (paste == null)
|
|
||||||
return NotFound(new { success = false, message = "Paste not found." });
|
|
||||||
|
|
||||||
var report = await _reportService.GetReportByID(reportId);
|
|
||||||
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
|
|
||||||
return NotFound(new { success = false, message = "Report not found." });
|
|
||||||
|
|
||||||
var user = HttpContext.GetJwtUser();
|
|
||||||
if (user == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
|
||||||
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." });
|
|
||||||
|
|
||||||
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
|
||||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
|
||||||
|
|
||||||
bool result = await _reportService.DeleteReport(report);
|
|
||||||
if (!result)
|
|
||||||
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
|
|
||||||
|
|
||||||
return Ok(new { success = true, message = "Report deleted successfully." });
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[Route("recent")]
|
[Route("recent")]
|
||||||
public async Task<IActionResult> GetRecentPastes()
|
public async Task<IActionResult> GetRecentPastes()
|
||||||
@@ -418,14 +389,16 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
UUID = p.UUID,
|
UUID = p.UUID,
|
||||||
CreatedAt = p.CreatedAt,
|
CreatedAt = p.CreatedAt,
|
||||||
Title = p.Title,
|
Title = p.Title,
|
||||||
Size = p.Size,
|
StoredSize = p.StoredSize,
|
||||||
TrueSize = p.TrueSize,
|
OriginalSize = p.OriginalSize,
|
||||||
IsCompressed = p.IsCompressed,
|
IsCompressed = p.IsCompressed,
|
||||||
Views = p.Views,
|
Views = p.Views,
|
||||||
Syntax = p.Syntax,
|
Syntax = p.Syntax,
|
||||||
Visibility = p.Visibility,
|
Visibility = p.Visibility,
|
||||||
ExpiresAt = p.ExpiresAt,
|
ExpiresAt = p.ExpiresAt,
|
||||||
EditedAt = p.EditedAt,
|
EditedAt = p.EditedAt,
|
||||||
|
Likes = p.PositiveInteractionCount,
|
||||||
|
Dislikes = p.NegativeInteractionCount,
|
||||||
Author =
|
Author =
|
||||||
p.User != null && p.User.Visibility == 0
|
p.User != null && p.User.Visibility == 0
|
||||||
? new UserSimpleDto
|
? new UserSimpleDto
|
||||||
@@ -436,12 +409,153 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
DisplayName = p.User.DisplayName,
|
DisplayName = p.User.DisplayName,
|
||||||
Visibility = p.User.Visibility,
|
Visibility = p.User.Visibility,
|
||||||
Roles = p.User.Roles,
|
Roles = p.User.Roles,
|
||||||
|
IsBanned = p.User.IsBanned,
|
||||||
}
|
}
|
||||||
: null,
|
: null,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
[EnableRateLimiting("NoLimit")]
|
||||||
|
[Route("{id}/comments")]
|
||||||
|
public async Task<IActionResult> GetComments(string id)
|
||||||
|
{
|
||||||
|
var paste = await _pasteService.Get(id);
|
||||||
|
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||||
|
return NotFound(new { success = false, message = "Paste not found" });
|
||||||
|
|
||||||
|
var comments = await _commentService.GetCommentsByPaste(paste);
|
||||||
|
|
||||||
|
Dictionary<long, Interaction>? userInteractionMap = null;
|
||||||
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
|
if (user != null)
|
||||||
|
userInteractionMap = await _commentService.GetUserInteractions(comments.Select(c => c.Id).ToList(), user.UUID);
|
||||||
|
|
||||||
|
return Ok(new { success = true, comments = comments.Select(c => ToCommentResponse(c, userInteractionMap)) });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
|
[Route("{id}/comments")]
|
||||||
|
public async Task<IActionResult> CreateComment(string id, [FromBody] CreateCommentDto request)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(request.Content))
|
||||||
|
return BadRequest(new { success = false, message = "Comment content cannot be empty." });
|
||||||
|
|
||||||
|
var paste = await _pasteService.Get(id);
|
||||||
|
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||||
|
return NotFound(new { success = false, message = "Paste not found" });
|
||||||
|
|
||||||
|
if (Encoding.UTF8.GetByteCount(request.Content) > 5000)
|
||||||
|
return BadRequest(new { success = false, message = "Comment content exceeds maximum size of 5000 bytes." });
|
||||||
|
|
||||||
|
if (request.ParentCommentID.HasValue)
|
||||||
|
{
|
||||||
|
var parent = await _commentService.GetCommentByID(request.ParentCommentID.Value, paste.PID);
|
||||||
|
if (parent == null)
|
||||||
|
return BadRequest(new { success = false, message = "Parent comment not found for this paste." });
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
|
if (user == null)
|
||||||
|
return Unauthorized(new { success = false, message = "User not authenticated." });
|
||||||
|
|
||||||
|
var comment = await _commentService.CreateComment(user, paste, request.Content, request.ParentCommentID);
|
||||||
|
var created = await _commentService.GetCommentByID(comment.Id);
|
||||||
|
if (created == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "Failed to load created comment." });
|
||||||
|
|
||||||
|
var userInteractionMap = new Dictionary<long, Interaction>();
|
||||||
|
return Ok(new { success = true, comment = ToCommentResponse(created, userInteractionMap) });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
|
[Route("{id}/comments/{commentId}/reaction")]
|
||||||
|
public async Task<IActionResult> ReactToComment(string id, long commentId, [FromBody] ReactToCommentDto request)
|
||||||
|
{
|
||||||
|
var paste = await _pasteService.Get(id);
|
||||||
|
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||||
|
return NotFound(new { success = false, message = "Paste not found" });
|
||||||
|
|
||||||
|
var comment = await _commentService.GetCommentByID(commentId, paste.PID);
|
||||||
|
if (comment == null)
|
||||||
|
return NotFound(new { success = false, message = "Comment not found for this paste." });
|
||||||
|
|
||||||
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
|
if (user == null)
|
||||||
|
return Unauthorized(new { success = false, message = "User not authenticated." });
|
||||||
|
|
||||||
|
if (request.Reaction.HasValue)
|
||||||
|
{
|
||||||
|
var result = await _commentService.UpsertInteraction(comment, user, request.Reaction.Value);
|
||||||
|
if (result == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "Could not save reaction." });
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _commentService.RemoveInteraction(comment, user);
|
||||||
|
}
|
||||||
|
|
||||||
|
var updated = await _commentService.GetCommentByID(commentId);
|
||||||
|
if (updated == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "Could not load updated comment." });
|
||||||
|
|
||||||
|
var interactionMap = await _commentService.GetUserInteractions([commentId], user.UUID);
|
||||||
|
Interaction? userReaction = null;
|
||||||
|
if (interactionMap.TryGetValue(commentId, out var mappedReaction))
|
||||||
|
userReaction = mappedReaction;
|
||||||
|
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
reaction = new CommentReactionResponseDto
|
||||||
|
{
|
||||||
|
CommentID = updated.Id,
|
||||||
|
Likes = updated.PositiveInteractionCount,
|
||||||
|
Dislikes = updated.NegativeInteractionCount,
|
||||||
|
UserReaction = userReaction,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete]
|
||||||
|
[Authorize(Policy = "JwtOnly")]
|
||||||
|
[Route("{id}/comments/{commentId}")]
|
||||||
|
public async Task<IActionResult> DeleteComment(string id, long commentId, bool hardDelete = false)
|
||||||
|
{
|
||||||
|
var paste = await _pasteService.Get(id);
|
||||||
|
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||||
|
return NotFound(new { success = false, message = "Paste not found" });
|
||||||
|
|
||||||
|
var comment = await _commentService.GetCommentByID(commentId, paste.PID);
|
||||||
|
if (comment == null)
|
||||||
|
return NotFound(new { success = false, message = "Comment not found for this paste." });
|
||||||
|
|
||||||
|
var user = await _authService.GetUserFromHttpContext(HttpContext);
|
||||||
|
if (user == null)
|
||||||
|
return Unauthorized(new { success = false, message = "User not authenticated." });
|
||||||
|
|
||||||
|
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||||
|
if (comment.UserUUID != user.UUID && !hasPrivilegedRole)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to delete this comment." });
|
||||||
|
if (hardDelete && !hasPrivilegedRole)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to hard delete this comment." });
|
||||||
|
|
||||||
|
bool result;
|
||||||
|
if (hardDelete)
|
||||||
|
result = await _commentService.HardDeleteComment(comment);
|
||||||
|
else
|
||||||
|
result = await _commentService.DeleteComment(comment);
|
||||||
|
|
||||||
|
if (!result)
|
||||||
|
return StatusCode(500, new { success = false, message = "An error occurred while deleting the comment." });
|
||||||
|
return Ok(new { success = true, message = "Comment deleted successfully." });
|
||||||
|
}
|
||||||
|
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[EnableRateLimiting("NoLimit")]
|
[EnableRateLimiting("NoLimit")]
|
||||||
[Route("info")]
|
[Route("info")]
|
||||||
@@ -463,5 +577,47 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private CommentResponseDto ToCommentResponse(Comment comment, Dictionary<long, Interaction>? userInteractionMap)
|
||||||
|
{
|
||||||
|
string? content = null;
|
||||||
|
if (comment.Content != null)
|
||||||
|
{
|
||||||
|
var bytes = comment.IsCompressed ? _compressionService.Decompress(comment.Content) : comment.Content;
|
||||||
|
content = Encoding.UTF8.GetString(bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
Interaction? userReaction = null;
|
||||||
|
if (userInteractionMap != null && userInteractionMap.TryGetValue(comment.Id, out var mappedReaction))
|
||||||
|
userReaction = mappedReaction;
|
||||||
|
|
||||||
|
return new CommentResponseDto
|
||||||
|
{
|
||||||
|
Id = comment.Id,
|
||||||
|
ParentCommentID = comment.ParentCommentID,
|
||||||
|
Content = content,
|
||||||
|
StoredSize = comment.StoredSize,
|
||||||
|
OriginalSize = comment.OriginalSize,
|
||||||
|
IsCompressed = comment.IsCompressed,
|
||||||
|
CreatedAt = comment.CreatedAt,
|
||||||
|
UpdatedAt = comment.UpdatedAt,
|
||||||
|
Likes = comment.PositiveInteractionCount,
|
||||||
|
Dislikes = comment.NegativeInteractionCount,
|
||||||
|
UserReaction = userReaction,
|
||||||
|
Author =
|
||||||
|
comment.User != null && comment.User.Visibility == 0
|
||||||
|
? new UserSimpleDto
|
||||||
|
{
|
||||||
|
UID = comment.User.UID,
|
||||||
|
UUID = comment.User.UUID,
|
||||||
|
Username = comment.User.Username,
|
||||||
|
DisplayName = comment.User.DisplayName,
|
||||||
|
Visibility = comment.User.Visibility,
|
||||||
|
Roles = comment.User.Roles,
|
||||||
|
IsBanned = comment.User.IsBanned,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,35 +2,45 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.RateLimiting;
|
using Microsoft.AspNetCore.RateLimiting;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
|
using SharpbinV3.Server.Data.Enums;
|
||||||
using SharpbinV3.Server.DTOs.Report;
|
using SharpbinV3.Server.DTOs.Report;
|
||||||
using SharpbinV3.Server.Extensions;
|
using SharpbinV3.Server.Extensions;
|
||||||
using SharpbinV3.Server.Services;
|
using SharpbinV3.Server.Services;
|
||||||
|
using SharpbinV3.Server.Services.Verification;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.Controllers
|
namespace SharpbinV3.Server.Controllers
|
||||||
{
|
{
|
||||||
[Route("api/[controller]")]
|
[Route("api/[controller]")]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
public class ReportController(ReportService reportService) : Controller
|
public class ReportController(
|
||||||
|
ReportService reportService,
|
||||||
|
PasteService pasteService,
|
||||||
|
UserService userService,
|
||||||
|
VerificationService verificationService
|
||||||
|
) : Controller
|
||||||
{
|
{
|
||||||
|
private readonly ReportService _reportService = reportService;
|
||||||
|
private readonly PasteService _pasteService = pasteService;
|
||||||
|
private readonly UserService _userService = userService;
|
||||||
|
private readonly VerificationService _verificationService = verificationService;
|
||||||
|
|
||||||
[Route("{reportId:int}")]
|
[Route("{reportId:int}")]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[EnableRateLimiting("Sliding")]
|
[EnableRateLimiting("Sliding")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
public async Task<IActionResult> GetReportById(int reportId)
|
public async Task<IActionResult> GetReportById(int reportId)
|
||||||
{
|
{
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser()!;
|
||||||
if (user is null)
|
|
||||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
|
||||||
|
|
||||||
var report = await reportService.GetReportByID(reportId);
|
var report = await _reportService.GetReportByID(reportId);
|
||||||
if (report is null)
|
if (report is null)
|
||||||
return NotFound(new { success = false, message = "Report not found." });
|
return NotFound(new { success = false, message = "Report not found." });
|
||||||
|
|
||||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||||
if (!hasPrivilegedRole && report.ReporterUUID != user.UUID)
|
if (!hasPrivilegedRole && report.ReporterUUID != user.UUID)
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to view this report." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to view this report." });
|
||||||
|
|
||||||
var (Username, DisplayName) = await reportService.GetReporterInfo(report.ReporterUUID);
|
var (Username, DisplayName) = await _reportService.GetReporterInfo(report.ReporterUUID);
|
||||||
|
|
||||||
return Ok(
|
return Ok(
|
||||||
new ReportResponseDto
|
new ReportResponseDto
|
||||||
@@ -57,16 +67,14 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[Route("{reportId:int}")]
|
[Route("{reportId:int}")]
|
||||||
[HttpPatch]
|
[HttpPatch]
|
||||||
[EnableRateLimiting("Sensitive")]
|
[EnableRateLimiting("Sensitive")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
|
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
|
||||||
{
|
{
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser()!;
|
||||||
if (user is null)
|
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
|
||||||
return Unauthorized(new { success = false, message = "You must be logged in to update reports." });
|
|
||||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
|
||||||
|
|
||||||
var report = await reportService.GetReportByID(reportId);
|
var report = await _reportService.GetReportByID(reportId);
|
||||||
if (report is null)
|
if (report is null)
|
||||||
return NotFound(new { success = false, message = "Report not found." });
|
return NotFound(new { success = false, message = "Report not found." });
|
||||||
|
|
||||||
@@ -90,8 +98,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
report.Description = request.Description;
|
report.Description = request.Description;
|
||||||
|
|
||||||
report.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
report.UpdatedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||||
var updated = await reportService.UpdateReport(report);
|
var updated = await _reportService.UpdateReport(report);
|
||||||
var (Username, DisplayName) = await reportService.GetReporterInfo(updated.ReporterUUID);
|
var (Username, DisplayName) = await _reportService.GetReporterInfo(updated.ReporterUUID);
|
||||||
|
|
||||||
return Ok(
|
return Ok(
|
||||||
new ReportResponseDto
|
new ReportResponseDto
|
||||||
@@ -127,19 +135,17 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[Route("pastes")]
|
[Route("pastes")]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[EnableRateLimiting("Sliding")]
|
[EnableRateLimiting("Sliding")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
|
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
|
||||||
{
|
{
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser()!;
|
||||||
if (user is null)
|
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
|
||||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
|
||||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
|
||||||
|
|
||||||
var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null };
|
var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null };
|
||||||
|
|
||||||
var reports = await reportService.GetPasteReports(query);
|
var reports = await _reportService.GetPasteReports(query);
|
||||||
var totalCount = await reportService.GetReportCount(query);
|
var totalCount = await _reportService.GetReportCount(query);
|
||||||
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
return Ok(
|
return Ok(
|
||||||
new
|
new
|
||||||
@@ -159,13 +165,11 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[Route("users")]
|
[Route("users")]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[EnableRateLimiting("Sliding")]
|
[EnableRateLimiting("Sliding")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
|
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
|
||||||
{
|
{
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser()!;
|
||||||
if (user is null)
|
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
|
||||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
|
||||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
|
||||||
|
|
||||||
var query = request with
|
var query = request with
|
||||||
@@ -176,8 +180,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
PasteId = null,
|
PasteId = null,
|
||||||
};
|
};
|
||||||
|
|
||||||
var reports = await reportService.GetUserReports(query);
|
var reports = await _reportService.GetUserReports(query);
|
||||||
var totalCount = await reportService.GetReportCount(query);
|
var totalCount = await _reportService.GetReportCount(query);
|
||||||
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
return Ok(
|
return Ok(
|
||||||
new
|
new
|
||||||
@@ -197,7 +201,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[Route("all")]
|
[Route("all")]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
[EnableRateLimiting("Sliding")]
|
[EnableRateLimiting("Sliding")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
public async Task<IActionResult> GetAllReports(
|
public async Task<IActionResult> GetAllReports(
|
||||||
[FromQuery] Guid? reporterUuid,
|
[FromQuery] Guid? reporterUuid,
|
||||||
[FromQuery] ReportTargetType? targetType,
|
[FromQuery] ReportTargetType? targetType,
|
||||||
@@ -207,10 +211,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[FromQuery] int pageSize = 20
|
[FromQuery] int pageSize = 20
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
var user = HttpContext.GetJwtUser();
|
var user = HttpContext.GetJwtUser()!;
|
||||||
if (user is null)
|
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
|
||||||
return Unauthorized(new { success = false, message = "You must be logged in to view reports." });
|
|
||||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
|
||||||
|
|
||||||
var query = new ReportQuery
|
var query = new ReportQuery
|
||||||
@@ -223,8 +225,8 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
PageSize = Math.Clamp(pageSize, 1, 100),
|
PageSize = Math.Clamp(pageSize, 1, 100),
|
||||||
};
|
};
|
||||||
|
|
||||||
var reports = await reportService.GetReports(query);
|
var reports = await _reportService.GetReports(query);
|
||||||
var totalCount = await reportService.GetReportCount(query);
|
var totalCount = await _reportService.GetReportCount(query);
|
||||||
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
return Ok(
|
return Ok(
|
||||||
new
|
new
|
||||||
@@ -240,5 +242,287 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost("pastes/{id}/report")]
|
||||||
|
[HttpPost("/api/paste/{id}/report")]
|
||||||
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
|
[EnableRateLimiting("Sensitive")]
|
||||||
|
public async Task<IActionResult> ReportPaste(string id, [FromBody] ReportDto request)
|
||||||
|
{
|
||||||
|
var paste = await _pasteService.Get(id);
|
||||||
|
if (paste == null)
|
||||||
|
return NotFound(new { success = false, message = "Paste not found." });
|
||||||
|
var user = HttpContext.GetJwtUser()!;
|
||||||
|
|
||||||
|
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
||||||
|
if (!Enum.IsDefined(reportType))
|
||||||
|
return BadRequest(new { success = false, message = "Invalid report type." });
|
||||||
|
|
||||||
|
if (
|
||||||
|
!await _verificationService.VerifyAsync(
|
||||||
|
new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return BadRequest(new { success = false, message = "Verification failed." });
|
||||||
|
|
||||||
|
Report report = await _reportService.CreateReport(user.UUID, ReportTargetType.Paste, paste.PID, reportType, request.Description);
|
||||||
|
if (report == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "An error occurred while reporting the paste." });
|
||||||
|
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
message = "Paste reported successfully.",
|
||||||
|
report = new ReportResponseDto
|
||||||
|
{
|
||||||
|
ReportID = report.ReportID,
|
||||||
|
Type = report.Type,
|
||||||
|
Status = report.Status,
|
||||||
|
Description = report.Description,
|
||||||
|
CreatedAt = report.CreatedAt,
|
||||||
|
UpdatedAt = report.UpdatedAt,
|
||||||
|
ReporterUUID = report.ReporterUUID,
|
||||||
|
TargetType = report.TargetType,
|
||||||
|
UserUUID = report.UserUUID,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPatch("pastes/{id}/report/{reportId}")]
|
||||||
|
[HttpPatch("/api/paste/{id}/report/{reportId}")]
|
||||||
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
|
[EnableRateLimiting("Sensitive")]
|
||||||
|
public async Task<IActionResult> ModifyPasteReport(string id, int reportId, [FromBody] ReportDto request)
|
||||||
|
{
|
||||||
|
var paste = await _pasteService.Get(id);
|
||||||
|
if (paste == null)
|
||||||
|
return NotFound(new { success = false, message = "Paste not found." });
|
||||||
|
|
||||||
|
var report = await _reportService.GetReportByID(reportId);
|
||||||
|
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
|
||||||
|
return NotFound(new { success = false, message = "Report not found." });
|
||||||
|
|
||||||
|
var user = HttpContext.GetJwtUser()!;
|
||||||
|
|
||||||
|
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||||
|
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." });
|
||||||
|
|
||||||
|
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
||||||
|
if (!Enum.IsDefined(reportType))
|
||||||
|
return BadRequest(new { success = false, message = "Invalid report type." });
|
||||||
|
|
||||||
|
report.Type = reportType;
|
||||||
|
report.Description = request.Description;
|
||||||
|
|
||||||
|
var updatedReport = await _reportService.UpdateReport(report);
|
||||||
|
if (updatedReport == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "An error occurred while updating the report." });
|
||||||
|
|
||||||
|
return Ok(new { success = true, message = "Report updated successfully." });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("pastes/{id}/report/{reportId}")]
|
||||||
|
[HttpDelete("/api/paste/{id}/report/{reportId}")]
|
||||||
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
|
[EnableRateLimiting("Sensitive")]
|
||||||
|
public async Task<IActionResult> DeletePasteReport(string id, int reportId)
|
||||||
|
{
|
||||||
|
var paste = await _pasteService.Get(id);
|
||||||
|
if (paste == null)
|
||||||
|
return NotFound(new { success = false, message = "Paste not found." });
|
||||||
|
|
||||||
|
var report = await _reportService.GetReportByID(reportId);
|
||||||
|
if (report == null || report.TargetType != ReportTargetType.Paste || report.PastePID != paste.PID)
|
||||||
|
return NotFound(new { success = false, message = "Report not found." });
|
||||||
|
|
||||||
|
var user = HttpContext.GetJwtUser()!;
|
||||||
|
|
||||||
|
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||||
|
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." });
|
||||||
|
|
||||||
|
bool result = await _reportService.DeleteReport(report);
|
||||||
|
if (!result)
|
||||||
|
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
|
||||||
|
|
||||||
|
return Ok(new { success = true, message = "Report deleted successfully." });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("users/{uuid}/report")]
|
||||||
|
[HttpPost("/api/user/{uuid}/report")]
|
||||||
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
|
[EnableRateLimiting("Sensitive")]
|
||||||
|
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
|
||||||
|
{
|
||||||
|
var reporter = HttpContext.GetJwtUser()!;
|
||||||
|
|
||||||
|
var reportedUser = await _userService.GetByUUID(uuid);
|
||||||
|
if (reportedUser == null)
|
||||||
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
if (reportedUser.UUID == reporter.UUID)
|
||||||
|
return BadRequest(new { success = false, message = "You cannot report yourself." });
|
||||||
|
if (reportedUser.Roles.HasFlag(Role.Admin) || reportedUser.Roles.HasFlag(Role.Moderator))
|
||||||
|
return BadRequest(new { success = false, message = "You cannot report staff members." });
|
||||||
|
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
||||||
|
if (!Enum.IsDefined(reportType))
|
||||||
|
return BadRequest(new { success = false, message = "Invalid report type." });
|
||||||
|
|
||||||
|
if (
|
||||||
|
!await _verificationService.VerifyAsync(
|
||||||
|
new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return Unauthorized(new { success = false, message = "Invalid verification token." });
|
||||||
|
|
||||||
|
Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description);
|
||||||
|
if (report == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "An error occurred while creating the report." });
|
||||||
|
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
message = "User reported successfully.",
|
||||||
|
report = new ReportResponseDto
|
||||||
|
{
|
||||||
|
ReportID = report.ReportID,
|
||||||
|
Type = report.Type,
|
||||||
|
Status = report.Status,
|
||||||
|
Description = report.Description,
|
||||||
|
CreatedAt = report.CreatedAt,
|
||||||
|
UpdatedAt = report.UpdatedAt,
|
||||||
|
ReporterUUID = report.ReporterUUID,
|
||||||
|
TargetType = report.TargetType,
|
||||||
|
UserUUID = report.UserUUID,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPatch("users/{uuid}/report/{reportId}")]
|
||||||
|
[HttpPatch("/api/user/{uuid}/report/{reportId}")]
|
||||||
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
|
[EnableRateLimiting("Sensitive")]
|
||||||
|
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
|
||||||
|
{
|
||||||
|
var jwtUser = HttpContext.GetJwtUser()!;
|
||||||
|
|
||||||
|
var user = await _userService.GetByUUID(uuid);
|
||||||
|
if (user == null)
|
||||||
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
var report = await _reportService.GetReportByID(reportId);
|
||||||
|
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
|
||||||
|
return NotFound(new { success = false, message = "Report not found." });
|
||||||
|
|
||||||
|
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
||||||
|
if (!Enum.IsDefined(reportType))
|
||||||
|
return BadRequest(new { success = false, message = "Invalid report type." });
|
||||||
|
|
||||||
|
report.Type = reportType;
|
||||||
|
report.Description = request.Description ?? report.Description;
|
||||||
|
|
||||||
|
var updatedReport = await _reportService.UpdateReport(report);
|
||||||
|
if (updatedReport == null)
|
||||||
|
return StatusCode(500, new { success = false, message = "An error occurred while updating the report." });
|
||||||
|
|
||||||
|
return Ok(new { success = true, message = "Report updated successfully." });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpDelete("users/{uuid}/report/{reportId}")]
|
||||||
|
[HttpDelete("/api/user/{uuid}/report/{reportId}")]
|
||||||
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
|
[EnableRateLimiting("Sensitive")]
|
||||||
|
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
|
||||||
|
{
|
||||||
|
var jwtUser = HttpContext.GetJwtUser()!;
|
||||||
|
|
||||||
|
var user = await _userService.GetByUUID(uuid);
|
||||||
|
if (user == null)
|
||||||
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
var report = await _reportService.GetReportByID(reportId);
|
||||||
|
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
|
||||||
|
return NotFound(new { success = false, message = "Report not found." });
|
||||||
|
|
||||||
|
var result = await _reportService.DeleteReport(report);
|
||||||
|
if (!result)
|
||||||
|
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
|
||||||
|
|
||||||
|
return Ok(new { success = true, message = "Report deleted successfully." });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("users/{uuid}/reports")]
|
||||||
|
[HttpGet("/api/user/{uuid}/reports")]
|
||||||
|
[Authorize(Policy = "JwtOnly")]
|
||||||
|
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
|
||||||
|
{
|
||||||
|
var jwtUser = HttpContext.GetJwtUser()!;
|
||||||
|
|
||||||
|
var user = await _userService.GetByUUID(uuid);
|
||||||
|
if (user == null)
|
||||||
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
if (!jwtUser.Roles.HasFlag(Role.Admin))
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
|
||||||
|
|
||||||
|
var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
|
||||||
|
var reports = await _reportService.GetUserReports(query);
|
||||||
|
var totalCount = await _reportService.GetReportCount(query);
|
||||||
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
Reports = reports,
|
||||||
|
Pagination = new
|
||||||
|
{
|
||||||
|
query.Page,
|
||||||
|
query.PageSize,
|
||||||
|
TotalCount = totalCount,
|
||||||
|
TotalPages = totalPages,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("users/{uuid}/reports/submitted")]
|
||||||
|
[HttpGet("/api/user/{uuid}/reports/submitted")]
|
||||||
|
[Authorize(Policy = "JwtOnly")]
|
||||||
|
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
|
||||||
|
{
|
||||||
|
var jwtUser = HttpContext.GetJwtUser()!;
|
||||||
|
|
||||||
|
var user = await _userService.GetByUUID(uuid);
|
||||||
|
if (user == null)
|
||||||
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
var isOwner = user.UUID == jwtUser.UUID;
|
||||||
|
var hasPrivilegedRole = jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator);
|
||||||
|
if (!isOwner && !hasPrivilegedRole)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
|
||||||
|
|
||||||
|
var query = request with { ReporterUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
|
||||||
|
|
||||||
|
var reports = await _reportService.GetReports(query);
|
||||||
|
var totalCount = await _reportService.GetReportCount(query);
|
||||||
|
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
||||||
|
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
Reports = reports,
|
||||||
|
Pagination = new
|
||||||
|
{
|
||||||
|
query.Page,
|
||||||
|
query.PageSize,
|
||||||
|
TotalCount = totalCount,
|
||||||
|
TotalPages = totalPages,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore;
|
|||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using SharpbinV3.Server.Data;
|
using SharpbinV3.Server.Data;
|
||||||
using SharpbinV3.Server.Data.Entities;
|
using SharpbinV3.Server.Data.Entities;
|
||||||
|
using SharpbinV3.Server.Data.Enums;
|
||||||
using SharpbinV3.Server.DTOs;
|
using SharpbinV3.Server.DTOs;
|
||||||
using SharpbinV3.Server.DTOs.Paste;
|
using SharpbinV3.Server.DTOs.Paste;
|
||||||
using SharpbinV3.Server.DTOs.Report;
|
using SharpbinV3.Server.DTOs.Report;
|
||||||
@@ -21,6 +22,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[Route("api/[controller]")]
|
[Route("api/[controller]")]
|
||||||
public class UserController(
|
public class UserController(
|
||||||
UserService userService,
|
UserService userService,
|
||||||
|
AuthService authService,
|
||||||
AppDbContext db,
|
AppDbContext db,
|
||||||
TotpVerificationProvider totp,
|
TotpVerificationProvider totp,
|
||||||
VerificationService verificationService,
|
VerificationService verificationService,
|
||||||
@@ -29,6 +31,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
) : ControllerBase
|
) : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly UserService _userService = userService;
|
private readonly UserService _userService = userService;
|
||||||
|
private readonly AuthService _authService = authService;
|
||||||
private readonly AppDbContext _db = db;
|
private readonly AppDbContext _db = db;
|
||||||
private readonly TotpVerificationProvider _totp = totp;
|
private readonly TotpVerificationProvider _totp = totp;
|
||||||
private readonly VerificationService _verificationService = verificationService;
|
private readonly VerificationService _verificationService = verificationService;
|
||||||
@@ -53,59 +56,125 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
[Authorize]
|
[Authorize]
|
||||||
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
|
public async Task<IActionResult> GetMe([FromQuery] int page = 1)
|
||||||
{
|
{
|
||||||
var userUUID = HttpContext.User?.FindFirst("uuid")?.Value;
|
var userUUID = HttpContext.User.FindFirst("uuid")!.Value;
|
||||||
if (userUUID is null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
|
var user = await _userService.GetByUUID(Guid.Parse(userUUID), withPastes: true);
|
||||||
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
|
return user == null ? NotFound(new { success = false, message = "User not found." }) : await BuildUserResponse(user, page);
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPatch("uuid/{uuid}")]
|
[HttpGet("uuid/{uuid}/requirements")]
|
||||||
[Authorize]
|
[Authorize(Policy = "JwtOnly")]
|
||||||
[EnableRateLimiting("Strict")]
|
[EnableRateLimiting("Strict")]
|
||||||
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
|
public async Task<IActionResult> GetUserActionRequirements(Guid uuid, [FromQuery] SecurityAction action)
|
||||||
{
|
{
|
||||||
Console.WriteLine($"{ModelState.IsValid}");
|
var jwtUser = HttpContext.GetJwtUser()!;
|
||||||
if (!ModelState.IsValid)
|
var targetUser = await _userService.GetByUUID(uuid);
|
||||||
return BadRequest(ModelState);
|
if (targetUser == null)
|
||||||
|
|
||||||
var jwtUser = HttpContext.GetJwtUser();
|
|
||||||
if (jwtUser == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var user = await _userService.GetByUUID(uuid);
|
|
||||||
if (user == null)
|
|
||||||
return NotFound(new { success = false, message = "User not found." });
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
if (
|
if (
|
||||||
(user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
|
(targetUser.Roles.HasFlag(Role.Admin) && !jwtUser.Roles.HasFlag(Role.Admin))
|
||||||
|| (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID)
|
|| (!jwtUser.Roles.HasFlag(Role.Admin) && targetUser.UUID != jwtUser.UUID)
|
||||||
)
|
)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." });
|
||||||
|
|
||||||
|
if (action == SecurityAction.UpdateRoles && !jwtUser.Roles.HasFlag(Role.Admin))
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to perform this action." });
|
||||||
|
|
||||||
|
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||||
|
{
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
action,
|
||||||
|
requiresTotp = false,
|
||||||
|
blocked = true,
|
||||||
|
message = "2FA is required to perform this action.",
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(
|
||||||
|
new
|
||||||
|
{
|
||||||
|
success = true,
|
||||||
|
action,
|
||||||
|
requiresTotp = jwtUser.TotpEnabled,
|
||||||
|
blocked = false,
|
||||||
|
message = jwtUser.TotpEnabled ? "TOTP verification is required." : "No TOTP verification required.",
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPatch("uuid/{uuid}")]
|
||||||
|
[Authorize(Policy = "JwtOnly")]
|
||||||
|
[EnableRateLimiting("Strict")]
|
||||||
|
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
|
||||||
|
{
|
||||||
|
if (!ModelState.IsValid)
|
||||||
|
return BadRequest(ModelState);
|
||||||
|
|
||||||
|
var jwtUser = HttpContext.GetJwtUser()!;
|
||||||
|
var actorUser = await _userService.GetByUUID(jwtUser.UUID);
|
||||||
|
if (actorUser == null)
|
||||||
|
return Unauthorized(new { success = false, message = "User not authenticated." });
|
||||||
|
|
||||||
|
var targetUser = await _userService.GetByUUID(uuid);
|
||||||
|
if (targetUser == null)
|
||||||
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
|
var actorIsAdmin = actorUser.Roles.HasFlag(Role.Admin);
|
||||||
|
var isSelfUpdate = targetUser.UUID == actorUser.UUID;
|
||||||
|
|
||||||
|
if ((targetUser.Roles.HasFlag(Role.Admin) && !actorIsAdmin) || (!actorIsAdmin && !isSelfUpdate))
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
|
||||||
|
|
||||||
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
if ((updatedUser.Roles.HasValue || updatedUser.IsBanned.HasValue) && !actorIsAdmin)
|
||||||
|
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
|
||||||
|
|
||||||
|
if (updatedUser.Email != null)
|
||||||
|
return BadRequest(new { success = false, message = "Use the email change endpoint to update email addresses." });
|
||||||
|
|
||||||
|
bool isSensitiveUpdate =
|
||||||
|
(updatedUser.Roles.HasValue && updatedUser.Roles.Value != targetUser.Roles) // updating roles
|
||||||
|
|| (updatedUser.IsBanned.HasValue && updatedUser.IsBanned.Value != targetUser.IsBanned); // updating ban status
|
||||||
|
|
||||||
|
if (actorIsAdmin && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA && isSensitiveUpdate)
|
||||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||||
|
|
||||||
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
|
if (isSensitiveUpdate && jwtUser.TotpEnabled)
|
||||||
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self
|
|
||||||
{
|
{
|
||||||
user.Email = updatedUser.Email ?? user.Email;
|
if (
|
||||||
user.Visibility = updatedUser.Visibility ?? user.Visibility;
|
string.IsNullOrEmpty(updatedUser.TotpCode)
|
||||||
}
|
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = actorUser.UUID, Code = updatedUser.TotpCode })
|
||||||
if (jwtUser.Roles.Contains(255))
|
)
|
||||||
{
|
|
||||||
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled)
|
|
||||||
{
|
{
|
||||||
if (
|
return Unauthorized(new { message = "Invalid TOTP code." });
|
||||||
string.IsNullOrEmpty(updatedUser.TotpCode)
|
|
||||||
|| !await _totp.VerifyAsync(new VerificationContext { UserUUID = jwtUser.UUID, Code = updatedUser.TotpCode })
|
|
||||||
)
|
|
||||||
{
|
|
||||||
return Unauthorized(new { message = "Invalid TOTP code." });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
user.Roles = updatedUser.Roles ?? user.Roles;
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
updatedUser.Roles.HasValue
|
||||||
|
&& targetUser.Roles.HasFlag(Role.Admin)
|
||||||
|
&& !updatedUser.Roles.Value.HasFlag(Role.Admin)
|
||||||
|
&& !isSelfUpdate
|
||||||
|
&& actorUser.UID > targetUser.UID
|
||||||
|
)
|
||||||
|
// prevents demoting of other older admins by newer admins
|
||||||
|
// allows self demotion in case of compromisation
|
||||||
|
{
|
||||||
|
return StatusCode(403, new { success = false, message = "You cannot remove the admin role from this user." });
|
||||||
|
}
|
||||||
|
|
||||||
|
targetUser.DisplayName = updatedUser.DisplayName ?? targetUser.DisplayName;
|
||||||
|
if (actorIsAdmin || isSelfUpdate)
|
||||||
|
{
|
||||||
|
targetUser.Visibility = updatedUser.Visibility ?? targetUser.Visibility;
|
||||||
|
}
|
||||||
|
if (actorIsAdmin)
|
||||||
|
{
|
||||||
|
targetUser.Roles = updatedUser.Roles ?? targetUser.Roles;
|
||||||
|
targetUser.IsBanned = updatedUser.IsBanned ?? targetUser.IsBanned;
|
||||||
}
|
}
|
||||||
|
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
@@ -113,22 +182,24 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
[HttpDelete("uuid/{uuid}")]
|
[HttpDelete("uuid/{uuid}")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
[EnableRateLimiting("Sensitive")]
|
[EnableRateLimiting("Sensitive")]
|
||||||
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
|
public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
|
||||||
{
|
{
|
||||||
var jwtUser = HttpContext.GetJwtUser();
|
var jwtUser = HttpContext.GetJwtUser()!;
|
||||||
if (jwtUser == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var user = await _userService.GetByUUID(uuid);
|
var user = await _userService.GetByUUID(uuid);
|
||||||
if (user == null)
|
if (user == null)
|
||||||
return NotFound(new { success = false, message = "User not found." });
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
|
|
||||||
if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID)
|
if (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
|
||||||
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
|
||||||
|
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." });
|
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||||
|
if (user.Roles.HasFlag(Role.Admin))
|
||||||
|
return StatusCode(403, new { success = false, message = "You cannot delete an admin user." });
|
||||||
|
|
||||||
if (jwtUser.TotpEnabled)
|
if (jwtUser.TotpEnabled)
|
||||||
{
|
{
|
||||||
@@ -140,211 +211,87 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
return Unauthorized(new { message = "Invalid TOTP code." });
|
return Unauthorized(new { message = "Invalid TOTP code." });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
else if (isSelfDelete && user.EmailVerified && !string.IsNullOrWhiteSpace(user.Email))
|
||||||
{
|
{
|
||||||
if (
|
if (string.IsNullOrEmpty(dto.Token) || !await _authService.VerifyAccountDeletionToken(user, dto.Token))
|
||||||
string.IsNullOrEmpty(dto.Token)
|
|
||||||
|| !await _verificationService.VerifyAsync(new VerificationContext { Token = dto.Token, Ip = HttpContext.GetRequestIP() })
|
|
||||||
)
|
|
||||||
{
|
{
|
||||||
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);
|
_db.Users.Remove(user);
|
||||||
await _db.SaveChangesAsync();
|
await _db.SaveChangesAsync();
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(deletedEmail))
|
||||||
|
await _authService.SendAccountDeletedNotification(deletedEmail, deletedUsername);
|
||||||
|
|
||||||
return Ok(new { message = "User deleted successfully." });
|
return Ok(new { message = "User deleted successfully." });
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost("uuid/{uuid}/delete-verification")]
|
||||||
[Route("{uuid}/report")]
|
[Authorize(Policy = "JwtOnlyAndNotBanned")]
|
||||||
[EnableRateLimiting("Sensitive")]
|
[EnableRateLimiting("Sensitive")]
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
public async Task<IActionResult> RequestDeleteVerification(Guid uuid)
|
||||||
public async Task<IActionResult> ReportUser(Guid uuid, [FromBody] ReportDto request)
|
|
||||||
{
|
{
|
||||||
var reporter = HttpContext.GetJwtUser();
|
var jwtUser = HttpContext.GetJwtUser()!;
|
||||||
if (reporter == null)
|
if (jwtUser.UUID != uuid)
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
|
||||||
|
|
||||||
var reportedUser = await _userService.GetByUUID(uuid);
|
var user = await _userService.GetByUUID(uuid);
|
||||||
if (reportedUser == null)
|
if (user == null)
|
||||||
return NotFound(new { success = false, message = "User not found." });
|
return NotFound(new { success = false, message = "User not found." });
|
||||||
if (reportedUser.UUID == reporter.UUID)
|
|
||||||
return BadRequest(new { success = false, message = "You cannot report yourself." });
|
|
||||||
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
|
||||||
if (!Enum.IsDefined(reportType))
|
|
||||||
return BadRequest(new { success = false, message = "Invalid report type." });
|
|
||||||
|
|
||||||
if (
|
if (user.Roles.HasFlag(Role.Admin))
|
||||||
!await _verificationService.VerifyAsync(
|
return StatusCode(403, new { success = false, message = "You cannot delete an admin user." });
|
||||||
new VerificationContext { Token = request.VerificationToken, Ip = HttpContext.GetRequestIP() }
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid verification token." });
|
|
||||||
|
|
||||||
Report report = await _reportService.CreateReport(reporter.UUID, ReportTargetType.User, uuid, reportType, request.Description);
|
if (jwtUser.TotpEnabled)
|
||||||
if (report == null)
|
return BadRequest(new { success = false, message = "Use TOTP to delete this account." });
|
||||||
return StatusCode(500, new { success = false, message = "An error occurred while creating the report." });
|
|
||||||
|
|
||||||
return Ok(
|
if (!user.EmailVerified || string.IsNullOrWhiteSpace(user.Email))
|
||||||
new
|
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)
|
||||||
{
|
{
|
||||||
success = true,
|
Response.Headers.RetryAfter = Math.Ceiling(result.retryAfter.Value / 1000d).ToString();
|
||||||
message = "User reported successfully.",
|
return StatusCode(
|
||||||
report = new ReportResponseDto
|
StatusCodes.Status429TooManyRequests,
|
||||||
{
|
new
|
||||||
ReportID = report.ReportID,
|
{
|
||||||
Type = report.Type,
|
success = false,
|
||||||
Status = report.Status,
|
message = result.message,
|
||||||
Description = report.Description,
|
retryAfter = result.retryAfter,
|
||||||
CreatedAt = report.CreatedAt,
|
}
|
||||||
UpdatedAt = report.UpdatedAt,
|
);
|
||||||
ReporterUUID = report.ReporterUUID,
|
|
||||||
TargetType = report.TargetType,
|
|
||||||
UserUUID = report.UserUUID,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpPatch]
|
return BadRequest(new { success = false, message = result.message });
|
||||||
[Route("{uuid}/report/{reportId}")]
|
}
|
||||||
[EnableRateLimiting("Sensitive")]
|
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
|
||||||
public async Task<IActionResult> UpdateUserReport(Guid uuid, int reportId, [FromBody] ReportDto request)
|
|
||||||
{
|
|
||||||
var jwtUser = HttpContext.GetJwtUser();
|
|
||||||
if (jwtUser == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var user = await _userService.GetByUUID(uuid);
|
return Ok(new { success = true, message = result.message });
|
||||||
if (user == null)
|
|
||||||
return NotFound(new { success = false, message = "User not found." });
|
|
||||||
|
|
||||||
var report = await _reportService.GetReportByID(reportId);
|
|
||||||
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
|
|
||||||
return NotFound(new { success = false, message = "Report not found." });
|
|
||||||
|
|
||||||
Enum.TryParse<ReportType>(request.ReportType, true, out var reportType);
|
|
||||||
if (!Enum.IsDefined(reportType))
|
|
||||||
return BadRequest(new { success = false, message = "Invalid report type." });
|
|
||||||
|
|
||||||
report.Type = reportType;
|
|
||||||
report.Description = request.Description ?? report.Description;
|
|
||||||
|
|
||||||
await _db.SaveChangesAsync();
|
|
||||||
return Ok(new { success = true, message = "Report updated successfully." });
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpDelete]
|
|
||||||
[Route("{uuid}/report/{reportId}")]
|
|
||||||
[EnableRateLimiting("Sensitive")]
|
|
||||||
[Authorize(Policy = "AuthAndNotBanned")]
|
|
||||||
public async Task<IActionResult> DeleteUserReport(Guid uuid, int reportId)
|
|
||||||
{
|
|
||||||
var jwtUser = HttpContext.GetJwtUser();
|
|
||||||
if (jwtUser == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var user = await _userService.GetByUUID(uuid);
|
|
||||||
if (user == null)
|
|
||||||
return NotFound(new { success = false, message = "User not found." });
|
|
||||||
|
|
||||||
var report = await _reportService.GetReportByID(reportId);
|
|
||||||
if (report == null || report.UserUUID != user.UUID || report.ReporterUUID != jwtUser.UUID)
|
|
||||||
return NotFound(new { success = false, message = "Report not found." });
|
|
||||||
|
|
||||||
var result = await _reportService.DeleteReport(report);
|
|
||||||
if (!result)
|
|
||||||
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
|
|
||||||
|
|
||||||
return Ok(new { success = true, message = "Report deleted successfully." });
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpGet]
|
|
||||||
[Authorize]
|
|
||||||
[Route("{uuid}/reports")]
|
|
||||||
public async Task<IActionResult> GetUserReports(Guid uuid, [FromQuery] ReportQuery request)
|
|
||||||
{
|
|
||||||
var jwtUser = HttpContext.GetJwtUser();
|
|
||||||
if (jwtUser == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var user = await _userService.GetByUUID(uuid);
|
|
||||||
if (user == null)
|
|
||||||
return NotFound(new { success = false, message = "User not found." });
|
|
||||||
|
|
||||||
if (!jwtUser.Roles.Any(r => r == 1 || r == 255))
|
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
|
|
||||||
|
|
||||||
var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
|
|
||||||
var reports = await _reportService.GetUserReports(query);
|
|
||||||
var totalCount = await _reportService.GetReportCount(query);
|
|
||||||
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
|
||||||
return Ok(
|
|
||||||
new
|
|
||||||
{
|
|
||||||
Reports = reports,
|
|
||||||
Pagination = new
|
|
||||||
{
|
|
||||||
query.Page,
|
|
||||||
query.PageSize,
|
|
||||||
TotalCount = totalCount,
|
|
||||||
TotalPages = totalPages,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpGet]
|
|
||||||
[Authorize]
|
|
||||||
[Route("{uuid}/reports/submitted")]
|
|
||||||
public async Task<IActionResult> GetUserSubmittedReports(Guid uuid, [FromQuery] ReportQuery request)
|
|
||||||
{
|
|
||||||
var jwtUser = HttpContext.GetJwtUser();
|
|
||||||
if (jwtUser == null)
|
|
||||||
return Unauthorized(new { success = false, message = "Invalid token." });
|
|
||||||
|
|
||||||
var user = await _userService.GetByUUID(uuid);
|
|
||||||
if (user == null)
|
|
||||||
return NotFound(new { success = false, message = "User not found." });
|
|
||||||
|
|
||||||
var isOwner = user.UUID == jwtUser.UUID;
|
|
||||||
var hasPrivilegedRole = jwtUser.Roles.Any(r => r == 1 || r == 255);
|
|
||||||
if (!isOwner && !hasPrivilegedRole)
|
|
||||||
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
|
|
||||||
|
|
||||||
var query = request with { ReporterUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
|
|
||||||
|
|
||||||
var reports = await _reportService.GetReports(query);
|
|
||||||
var totalCount = await _reportService.GetReportCount(query);
|
|
||||||
var totalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize);
|
|
||||||
|
|
||||||
return Ok(
|
|
||||||
new
|
|
||||||
{
|
|
||||||
Reports = reports,
|
|
||||||
Pagination = new
|
|
||||||
{
|
|
||||||
query.Page,
|
|
||||||
query.PageSize,
|
|
||||||
TotalCount = totalCount,
|
|
||||||
TotalPages = totalPages,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<IActionResult> BuildUserResponse(User user, int page = 1)
|
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);
|
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
|
||||||
if (!isAuthenticatedUser)
|
if (!isRequestedUser)
|
||||||
{
|
{
|
||||||
if (user.Visibility == 2)
|
if (user.Visibility == Visibility.Private && !requesterIsStaff)
|
||||||
return NotFound();
|
return NotFound();
|
||||||
else if (user.Visibility != 1)
|
|
||||||
pasteQuery = pasteQuery.Where(p => p.Visibility == 0);
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (page < 1)
|
if (page < 1)
|
||||||
@@ -366,12 +313,14 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
CreatedAt = p.CreatedAt,
|
CreatedAt = p.CreatedAt,
|
||||||
Title = p.Title,
|
Title = p.Title,
|
||||||
Syntax = p.Syntax,
|
Syntax = p.Syntax,
|
||||||
Size = p.Size,
|
OriginalSize = p.OriginalSize,
|
||||||
TrueSize = p.TrueSize,
|
StoredSize = p.StoredSize,
|
||||||
Views = p.Views,
|
Views = p.Views,
|
||||||
Visibility = p.Visibility,
|
Visibility = p.Visibility,
|
||||||
EditedAt = p.EditedAt,
|
EditedAt = p.EditedAt,
|
||||||
ExpiresAt = p.ExpiresAt,
|
ExpiresAt = p.ExpiresAt,
|
||||||
|
Likes = p.Interactions.Count(i => i.Type == Interaction.Positive),
|
||||||
|
Dislikes = p.Interactions.Count(i => i.Type == Interaction.Negative),
|
||||||
})
|
})
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
@@ -383,7 +332,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
TotalPages = totalPages,
|
TotalPages = totalPages,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isAuthenticatedUser)
|
if (isRequestedUser)
|
||||||
{
|
{
|
||||||
var reports = await _reportService.GetReports(
|
var reports = await _reportService.GetReports(
|
||||||
new ReportQuery
|
new ReportQuery
|
||||||
@@ -406,8 +355,10 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
CreatedAt = user.CreatedAt,
|
CreatedAt = user.CreatedAt,
|
||||||
DisplayName = user.DisplayName,
|
DisplayName = user.DisplayName,
|
||||||
Email = user.Email,
|
Email = user.Email,
|
||||||
|
EmailVerified = user.EmailVerified,
|
||||||
LastLogin = user.LastLogin,
|
LastLogin = user.LastLogin,
|
||||||
Roles = user.Roles,
|
Roles = user.Roles,
|
||||||
|
IsBanned = user.IsBanned,
|
||||||
Visibility = user.Visibility,
|
Visibility = user.Visibility,
|
||||||
},
|
},
|
||||||
Pastes = pastes,
|
Pastes = pastes,
|
||||||
@@ -435,6 +386,7 @@ namespace SharpbinV3.Server.Controllers
|
|||||||
CreatedAt = user.CreatedAt,
|
CreatedAt = user.CreatedAt,
|
||||||
DisplayName = user.DisplayName,
|
DisplayName = user.DisplayName,
|
||||||
Roles = user.Roles,
|
Roles = user.Roles,
|
||||||
|
IsBanned = user.IsBanned,
|
||||||
Visibility = user.Visibility,
|
Visibility = user.Visibility,
|
||||||
},
|
},
|
||||||
Pastes = pastes,
|
Pastes = pastes,
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace SharpbinV3.Server.DTOs.ApiKey
|
||||||
|
{
|
||||||
|
public sealed class ApiKeyListItemDto
|
||||||
|
{
|
||||||
|
public required string Name { get; set; }
|
||||||
|
public required Guid UUID { get; set; }
|
||||||
|
public required long CreatedAt { get; set; }
|
||||||
|
public long? LastUsedAt { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace SharpbinV3.Server.DTOs.ApiKey
|
||||||
|
{
|
||||||
|
public sealed class ApiKeyResponseDto
|
||||||
|
{
|
||||||
|
public required string Key { get; set; }
|
||||||
|
public required string Name { get; set; }
|
||||||
|
public required Guid UUID { get; set; }
|
||||||
|
public required long CreatedAt { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace SharpbinV3.Server.DTOs.ApiKey
|
||||||
|
{
|
||||||
|
public sealed class CreateApiKeyRequest
|
||||||
|
{
|
||||||
|
public required string Name { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace SharpbinV3.Server.DTOs.Auth
|
||||||
|
{
|
||||||
|
public sealed class AdminPasswordResetLinkDto
|
||||||
|
{
|
||||||
|
public string? TotpCode { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Auth
|
||||||
|
{
|
||||||
|
public sealed class ChangeEmailDto
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
[EmailAddress]
|
||||||
|
public string Email { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public string? TotpCode { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Auth
|
||||||
|
{
|
||||||
|
public sealed class PasswordChangeDto
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
public string CurrentPassword { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
[StringLength(128, MinimumLength = 8)]
|
||||||
|
public string NewPassword { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public string? TotpCode { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Auth
|
||||||
|
{
|
||||||
|
public sealed class PasswordResetDto
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
public string Token { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[Required]
|
||||||
|
[StringLength(128, MinimumLength = 8)]
|
||||||
|
public string NewPassword { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public string? TotpCode { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Auth
|
||||||
|
{
|
||||||
|
public sealed class PasswordResetRequestDto
|
||||||
|
{
|
||||||
|
[Required]
|
||||||
|
[EmailAddress]
|
||||||
|
public string Email { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public string? Token { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using SharpbinV3.Server.Data.Enums;
|
||||||
|
using SharpbinV3.Server.DTOs.User;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Paste
|
||||||
|
{
|
||||||
|
public class CreateCommentDto
|
||||||
|
{
|
||||||
|
public string Content { get; set; } = string.Empty;
|
||||||
|
public long? ParentCommentID { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ReactToCommentDto
|
||||||
|
{
|
||||||
|
public Interaction? Reaction { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class ReactToPasteDto
|
||||||
|
{
|
||||||
|
public Interaction? Reaction { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CommentResponseDto
|
||||||
|
{
|
||||||
|
public long Id { get; set; }
|
||||||
|
public long? ParentCommentID { get; set; }
|
||||||
|
public string? Content { get; set; }
|
||||||
|
public long StoredSize { get; set; }
|
||||||
|
public long OriginalSize { get; set; }
|
||||||
|
public bool IsCompressed { get; set; }
|
||||||
|
public long CreatedAt { get; set; }
|
||||||
|
public long? UpdatedAt { get; set; }
|
||||||
|
public int Likes { get; set; }
|
||||||
|
public int Dislikes { get; set; }
|
||||||
|
public Interaction? UserReaction { get; set; }
|
||||||
|
public UserSimpleDto? Author { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class CommentReactionResponseDto
|
||||||
|
{
|
||||||
|
public long CommentID { get; set; }
|
||||||
|
public int Likes { get; set; }
|
||||||
|
public int Dislikes { get; set; }
|
||||||
|
public Interaction? UserReaction { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PasteReactionResponseDto
|
||||||
|
{
|
||||||
|
public string PasteID { get; set; } = string.Empty;
|
||||||
|
public int Likes { get; set; }
|
||||||
|
public int Dislikes { get; set; }
|
||||||
|
public Interaction? UserReaction { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using SharpbinV3.Server.Data.Enums;
|
||||||
using SharpbinV3.Server.DTOs.User;
|
using SharpbinV3.Server.DTOs.User;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.DTOs.Paste
|
namespace SharpbinV3.Server.DTOs.Paste
|
||||||
@@ -9,14 +10,17 @@ namespace SharpbinV3.Server.DTOs.Paste
|
|||||||
public long CreatedAt { get; set; }
|
public long CreatedAt { get; set; }
|
||||||
public string? Title { get; set; }
|
public string? Title { get; set; }
|
||||||
public string? Syntax { get; set; }
|
public string? Syntax { get; set; }
|
||||||
public long Size { get; set; }
|
public long StoredSize { get; set; }
|
||||||
public long TrueSize { get; set; }
|
public long OriginalSize { get; set; }
|
||||||
public bool IsCompressed { get; set; }
|
public bool IsCompressed { get; set; }
|
||||||
public int Views { get; set; }
|
public int Views { get; set; }
|
||||||
public int Visibility { get; set; }
|
public Visibility Visibility { get; set; }
|
||||||
public long? EditedAt { get; set; }
|
public long? EditedAt { get; set; }
|
||||||
public long ExpiresAt { get; set; }
|
public long ExpiresAt { get; set; }
|
||||||
public int? ReportCount { get; set; }
|
public int? ReportCount { get; set; }
|
||||||
|
public int Likes { get; set; }
|
||||||
|
public int Dislikes { get; set; }
|
||||||
|
public Interaction? UserReaction { get; set; }
|
||||||
public UserSimpleDto? Author { get; set; }
|
public UserSimpleDto? Author { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -26,9 +30,10 @@ namespace SharpbinV3.Server.DTOs.Paste
|
|||||||
public Guid UUID { get; set; }
|
public Guid UUID { get; set; }
|
||||||
public long CreatedAt { get; set; }
|
public long CreatedAt { get; set; }
|
||||||
public bool IsCompressed { get; set; }
|
public bool IsCompressed { get; set; }
|
||||||
public long Size { get; set; }
|
public long StoredSize { get; set; }
|
||||||
public long TrueSize { get; set; }
|
public long OriginalSize { get; set; }
|
||||||
public long ExpiresAt { get; set; }
|
public long ExpiresAt { get; set; }
|
||||||
|
public Visibility Visibility { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public class PasteOptionsDto
|
public class PasteOptionsDto
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
namespace SharpbinV3.Server.DTOs.Paste
|
using SharpbinV3.Server.Data.Enums;
|
||||||
|
|
||||||
|
namespace SharpbinV3.Server.DTOs.Paste
|
||||||
{
|
{
|
||||||
public class UpdatePasteDto
|
public class UpdatePasteDto
|
||||||
{
|
{
|
||||||
public string? Title { get; set; }
|
public string? Title { get; set; }
|
||||||
public string? Syntax { get; set; }
|
public string? Syntax { get; set; }
|
||||||
public int? Visibility { get; set; }
|
public Visibility? Visibility { get; set; }
|
||||||
public long? ExpiresAt { get; set; }
|
public long? ExpiresAt { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ namespace SharpbinV3.Server.DTOs.Report
|
|||||||
{
|
{
|
||||||
public Guid? ReporterUUID { get; init; }
|
public Guid? ReporterUUID { get; init; }
|
||||||
public Guid? UserUUID { get; init; }
|
public Guid? UserUUID { get; init; }
|
||||||
public int? PastePID { get; init; }
|
public long? PastePID { get; init; }
|
||||||
public string? PasteId { get; init; }
|
public string? PasteId { get; init; }
|
||||||
public ReportTargetType? TargetType { get; init; }
|
public ReportTargetType? TargetType { get; init; }
|
||||||
public ReportType? Type { get; init; }
|
public ReportType? Type { get; init; }
|
||||||
|
|||||||
@@ -8,8 +8,9 @@ namespace SharpbinV3.Server.DTOs.User
|
|||||||
public string? Username { get; set; }
|
public string? Username { get; set; }
|
||||||
public string? Email { get; set; }
|
public string? Email { get; set; }
|
||||||
|
|
||||||
|
[Required]
|
||||||
[StringLength(128, MinimumLength = 6)]
|
[StringLength(128, MinimumLength = 6)]
|
||||||
public string? Password { get; set; }
|
public required string Password { get; set; }
|
||||||
public string? Token { get; set; }
|
public string? Token { get; set; }
|
||||||
public string? TotpCode { get; set; }
|
public string? TotpCode { get; set; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
|
using SharpbinV3.Server.Data.Entities;
|
||||||
|
using SharpbinV3.Server.Data.Enums;
|
||||||
|
|
||||||
namespace SharpbinV3.Server.DTOs
|
namespace SharpbinV3.Server.DTOs
|
||||||
{
|
{
|
||||||
@@ -7,8 +9,9 @@ namespace SharpbinV3.Server.DTOs
|
|||||||
{
|
{
|
||||||
public string? DisplayName { get; set; }
|
public string? DisplayName { get; set; }
|
||||||
public string? Email { get; set; }
|
public string? Email { get; set; }
|
||||||
public int? Visibility { get; set; } = 0;
|
public Visibility? Visibility { get; set; }
|
||||||
public int[]? Roles { get; set; }
|
public Role? Roles { get; set; }
|
||||||
|
public bool? IsBanned { get; set; }
|
||||||
public string? TotpCode { get; set; }
|
public string? TotpCode { get; set; }
|
||||||
|
|
||||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||||
@@ -34,19 +37,14 @@ namespace SharpbinV3.Server.DTOs
|
|||||||
}
|
}
|
||||||
if (Visibility != null && Visibility.HasValue)
|
if (Visibility != null && Visibility.HasValue)
|
||||||
{
|
{
|
||||||
if (Visibility < 0 || Visibility > 2)
|
if (!Enum.IsDefined(typeof(Visibility), Visibility.Value))
|
||||||
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)]));
|
results.Add(new ValidationResult($"Invalid visibility: {Visibility.Value}.", [nameof(Visibility)]));
|
||||||
}
|
}
|
||||||
if (Roles != null && Roles.Length > 0)
|
if (Roles != null && Roles.HasValue)
|
||||||
{
|
{
|
||||||
if (Roles.Length == 0)
|
int validBits = Enum.GetValues(typeof(Role)).Cast<Role>().Aggregate(0, (acc, role) => acc | (int)role);
|
||||||
results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)]));
|
if ((((int)Roles.Value) & validBits) != (int)Roles.Value || Roles.Value == 0)
|
||||||
int[] validRoles = [0, 1, 255, 403];
|
results.Add(new ValidationResult($"Invalid role: {Roles.Value}.", [nameof(Roles)]));
|
||||||
foreach (var role in Roles)
|
|
||||||
{
|
|
||||||
if (!validRoles.Contains(role))
|
|
||||||
results.Add(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)]));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user