mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
898e4aa9a8
|
||
|
|
f7e493100e
|
||
|
|
219b8c1415 | ||
|
|
7281166aca
|
||
|
|
9bc5d0318d
|
||
|
|
78c26fa2d2
|
||
|
|
57d9a4e3b2
|
||
|
|
f64b617089
|
||
|
|
57f1709032
|
||
|
|
f82edc6b40 | ||
|
|
fbd200b159 | ||
|
|
b95f540ef4
|
||
|
|
bea106ac72
|
||
|
|
fddfeb6525
|
||
|
|
ed98238c40
|
||
|
|
181c401af7
|
||
|
|
3eb7374a07
|
||
|
|
cc0c6a8286
|
||
|
|
73ac667c15
|
||
|
|
89e9673a00
|
||
|
|
63323b1aa7 | ||
|
|
73248e723a
|
||
|
|
e6e6bf9ee6
|
||
|
|
a338b8814a
|
||
|
|
725d8a5732 | ||
|
|
86b90050bd | ||
|
|
357a57a6fb | ||
|
|
7c1e0d77d9 | ||
|
|
45f20772a5 | ||
|
|
1881c8a90d
|
||
|
|
38411ca7c0
|
||
|
|
f8a58740fa | ||
|
|
73743399f1 | ||
|
|
2126c3a078 | ||
|
|
1382fb9f07 | ||
|
|
704d7149fc | ||
|
|
2a25ab1ab8 | ||
|
|
94fb936b32 | ||
|
|
e0a2f20546 | ||
|
|
8f42dd55ae | ||
|
|
01a637f5dd | ||
|
|
d0cf36108f |
+5
-2
@@ -1,8 +1,6 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/backend.env
|
||||
**/frontend.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
@@ -30,3 +28,8 @@ README.md
|
||||
!.git/config
|
||||
!.git/packed-refs
|
||||
!.git/refs/heads/**
|
||||
|
||||
SharpbinV2.Server/*.db
|
||||
SharpbinV2.Server/logs
|
||||
SharpbinV2.Server/pastes
|
||||
SharpbinV2.Server/.env
|
||||
@@ -1,26 +0,0 @@
|
||||
# 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
|
||||
@@ -1,2 +0,0 @@
|
||||
# These are supported funding model platforms
|
||||
ko_fi: whoswhip
|
||||
@@ -1,35 +0,0 @@
|
||||
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
|
||||
+8
-13
@@ -33,6 +33,10 @@ bld/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
p/
|
||||
privp/
|
||||
raw/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
@@ -314,17 +318,8 @@ MigrationBackup/
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
|
||||
# Database
|
||||
**/*.db
|
||||
**/*.wal
|
||||
**/*.db-wal
|
||||
**/*.db-shm
|
||||
**/*.sqlite
|
||||
SharpbinV2.Server/*.db
|
||||
SharpbinV2.Server/logs
|
||||
SharpbinV2.Server/pastes
|
||||
SharpbinV2.Server/.env
|
||||
|
||||
Data
|
||||
!SharpbinV3.Server/Data
|
||||
.idea
|
||||
|
||||
**/.env
|
||||
backend.env
|
||||
frontend.env
|
||||
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"name": "C#: SharpbinV2.Server Debug",
|
||||
"type": "dotnet",
|
||||
"request": "launch",
|
||||
"projectPath": "${workspaceFolder}/SharpbinV2.Server/SharpbinV2.Server.csproj"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
-6
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"*.css": "tailwindcss"
|
||||
},
|
||||
"tailwindCSS.experimental.configFile": "SharpbinV3.Client/src/routes/layout.css"
|
||||
}
|
||||
-362
@@ -1,362 +0,0 @@
|
||||
## [3.1.0](https://github.com/whoswhip/Sharpbin/compare/v3.0.5...v3.1.0) (2026-10-18)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add docker entrypoint sccript ([045a193](https://github.com/whoswhip/Sharpbin/commit/045a1934d80277b75b34d7566ea283c57a7b1e83))
|
||||
* add tooltip to comment timestamp for better context ([c98e5e5](https://github.com/whoswhip/Sharpbin/commit/c98e5e53b02002ac0328947cdbabddaa60ebe877))
|
||||
* allow null display name when saving display name ([20473da](https://github.com/whoswhip/Sharpbin/commit/20473da0bacc891354ef75cd05b4fdb3443ae629))
|
||||
* always underline users in comments ([e239bf2](https://github.com/whoswhip/Sharpbin/commit/e239bf2ae5a4ca0f93cfc197d9658df459b87d10))
|
||||
* compact paste smaller; better edited display ([e8cd93e](https://github.com/whoswhip/Sharpbin/commit/e8cd93e7bdfc47e0c105935182c7062fd191cb57))
|
||||
* disable but show buttons for author or anon users ([77f6623](https://github.com/whoswhip/Sharpbin/commit/77f6623fcf6b9b50e26ce533cee7b83c26836051))
|
||||
* disable styles on comment reactions ([23f0c92](https://github.com/whoswhip/Sharpbin/commit/23f0c92aed9bd8235ad1cc6b62aa3c9bf8674370))
|
||||
* disabled:cursor-not-allowed on like buttons ([95a5c18](https://github.com/whoswhip/Sharpbin/commit/95a5c18dc57ad33701bbd6d9f5cfcf6a1cda6f49))
|
||||
* enforce 2fa only on certain update actions ([a55268a](https://github.com/whoswhip/Sharpbin/commit/a55268afdc171d3d7f074ee008be3434e14c0482))
|
||||
* enhance user update permissions and authentication checks ([6c810b0](https://github.com/whoswhip/Sharpbin/commit/6c810b07b738ca2cb0cfe87c264e26395254024b))
|
||||
* handle username conflict during user creation ([f5a7aab](https://github.com/whoswhip/Sharpbin/commit/f5a7aabf42a67969baf6e307b3178e89c75a4716))
|
||||
* improve paste description ([60796a8](https://github.com/whoswhip/Sharpbin/commit/60796a85fb3f287cc88d42dda7f9bc446d0d5f97))
|
||||
* include '.' before extension on paste download ([ee6a6d5](https://github.com/whoswhip/Sharpbin/commit/ee6a6d5e6d3f4d5ef2fb2c8f6032e695b228fcf9))
|
||||
* lower vulnerabilities + harden docker setup ([d16f1f8](https://github.com/whoswhip/Sharpbin/commit/d16f1f872fa34de460f9ee8903b4eefbe780c041))
|
||||
* make cursor-not-allowed !important ([9916930](https://github.com/whoswhip/Sharpbin/commit/99169305c7b496eef51cfb5493cd3c8548f366e7))
|
||||
* multiple vulnerabilities ([6a7b865](https://github.com/whoswhip/Sharpbin/commit/6a7b8653dc154366c85de32dccf242a071eebdf0))
|
||||
* normalize canonical URL to prevent duplicate content issues ([ad693b2](https://github.com/whoswhip/Sharpbin/commit/ad693b28ea701554fceede1f8e30e7990240281c))
|
||||
* normalize cononical ([d45f253](https://github.com/whoswhip/Sharpbin/commit/d45f253c000e834db584fed89ddb541c09f466c7))
|
||||
* only show report button if logged in ([40c6ac6](https://github.com/whoswhip/Sharpbin/commit/40c6ac663f95c40a154dc56598bdfe6e59f38703))
|
||||
* prevent admins and moderators from being reported ([f2c67ae](https://github.com/whoswhip/Sharpbin/commit/f2c67ae3677658efaf84811271f62c5043797460))
|
||||
* prevent authors from reacting to their pas6te ([3da7f99](https://github.com/whoswhip/Sharpbin/commit/3da7f99feba4aaaa02a6e9f0c7771a548e6530c3))
|
||||
* remove recipient information from warning log when email settings are incomplete ([b65d3f8](https://github.com/whoswhip/Sharpbin/commit/b65d3f8726f77f2b7260e97ba439bfea4e2ad908))
|
||||
* remove trailing '.' in filename ([b0e9f51](https://github.com/whoswhip/Sharpbin/commit/b0e9f5104c92a3cb6a8965d23460c86a64595d12))
|
||||
* show uncompressed size in stats ([61efbf8](https://github.com/whoswhip/Sharpbin/commit/61efbf8b0415fe159b5e777f737ee4e8b25beb02))
|
||||
* sizeStored -> StoredSize in typescript paste type ([6c65a52](https://github.com/whoswhip/Sharpbin/commit/6c65a52ee06c266eeeb5519e779eb49f73be33b7))
|
||||
* update robots.txt to specify allowed and disallowed paths for web crawlers ([ea634fd](https://github.com/whoswhip/Sharpbin/commit/ea634fd85135d2996e96f6a48ce2fbccbb75b7e2))
|
||||
* update TypeScript configuration to extend from $app/tsconfig and adjust include/exclude paths ([f2559ea](https://github.com/whoswhip/Sharpbin/commit/f2559eaad0ac79ac2ee18f3b9388ce62b11b5543))
|
||||
* use #lib instead of $lib ([8d06020](https://github.com/whoswhip/Sharpbin/commit/8d060204c890018f49147e681f94a6737ac1c4b1)), closes [#lib](https://github.com/whoswhip/Sharpbin/issues/lib)
|
||||
* use node env instead of sveltekit env ([0e3a6d9](https://github.com/whoswhip/Sharpbin/commit/0e3a6d97e395c605d419c2464c3b7fccbcdd5c6f))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add /[@username](https://github.com/username) redirect to /user/username ([70e637b](https://github.com/whoswhip/Sharpbin/commit/70e637b281ae060e40ceb6e312591276d1c68540))
|
||||
* add bot detection to skip recording views for known bots ([41d4411](https://github.com/whoswhip/Sharpbin/commit/41d441135cdef6c22df34a512507ef7032009db9))
|
||||
* add sub tab to the settings tab ([e20a620](https://github.com/whoswhip/Sharpbin/commit/e20a6200dd3c1f0dfe26645c625cac448dc50d76))
|
||||
* allow staff members to see user's unlisted pastes; show dislikes in the paste lists ([6ed2974](https://github.com/whoswhip/Sharpbin/commit/6ed2974e42df9d10da755af6897b4eea4ee6d34a))
|
||||
* **auth:** enhance token management and synchronization with user data ([2864c81](https://github.com/whoswhip/Sharpbin/commit/2864c81f83ca49032a803f8ca2ccad19a1f8d9fe))
|
||||
* comments & paste/comment reactions; renames/refactors ([63b77be](https://github.com/whoswhip/Sharpbin/commit/63b77bece9b71d547d15403257da44e8597db97b))
|
||||
* **comments:** implement delete comment functionality with confirmation modal ([95ca811](https://github.com/whoswhip/Sharpbin/commit/95ca811d4295759b3fc161eff9ba81c7499be254))
|
||||
* **comments:** implement recursive comment deletion in HardDeleteComment method ([8d3caf5](https://github.com/whoswhip/Sharpbin/commit/8d3caf5375a8065281b917b1c24970580799a059))
|
||||
* enhance SEO for home, recent, and paste pages ([edffd54](https://github.com/whoswhip/Sharpbin/commit/edffd5490fae8274293982ded81c7971b614fd28))
|
||||
* improve rate limit partition keys + less strict limits ([6cadc0b](https://github.com/whoswhip/Sharpbin/commit/6cadc0b74d3b5cb340347b1fc8dbaf8f06318e5b))
|
||||
* **modal:** refactor modal types and integrate security action requirements ([f82d314](https://github.com/whoswhip/Sharpbin/commit/f82d314d80dcd8e70f197c254bb4e7ba2fee67f0))
|
||||
* password resets ([d4976ac](https://github.com/whoswhip/Sharpbin/commit/d4976ac9aac41cb7ad23070480862bf2cec89095))
|
||||
|
||||
|
||||
|
||||
## [3.0.5](https://github.com/whoswhip/Sharpbin/compare/v3.0.4...v3.0.5) (2026-03-31)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add back CSV syntax support in consts and appsettings ([3ba63f6](https://github.com/whoswhip/Sharpbin/commit/3ba63f692c25e016f226fccc9120a3649c7150d9))
|
||||
* **auth:** replace HMAC token generation with SHA256 for email verification ([49e73cd](https://github.com/whoswhip/Sharpbin/commit/49e73cde9c856bee9f36e2cedb9742bd6a3e9942))
|
||||
* **backend:paste:** check expiration before returning paste data or recording views; prevent paste authors from adding views to their own paste ([ec0635d](https://github.com/whoswhip/Sharpbin/commit/ec0635dd3b6401679e1a4a923302de5dcdbecda8))
|
||||
* **cache:** ensure pasteExpiresAt is valid before cache deletion ([c98aca9](https://github.com/whoswhip/Sharpbin/commit/c98aca92b68a761056b5610d893c7be17da06d96))
|
||||
* **controller:** only return paste not found if null or expired ([f70328c](https://github.com/whoswhip/Sharpbin/commit/f70328c93d8b008f6015ec239cc984bbcc0b57e3))
|
||||
* **controller:** update paste expiration check to handle zero expiration case ([797747f](https://github.com/whoswhip/Sharpbin/commit/797747f718913f1b52d0d17caf7fc1f720bde59b))
|
||||
* correct expiration time for 'Expire in 5 Minutes' option ([f786117](https://github.com/whoswhip/Sharpbin/commit/f786117cad468d0c0cacae10bbfe82c8d647353b))
|
||||
* **docker-compose:** add back VITE_API_URL environment variable to frontend ([d4e2cf2](https://github.com/whoswhip/Sharpbin/commit/d4e2cf25d3c4eb4c414b59ce6b5655cd9a3ba8a7))
|
||||
* **docker-compose:** add env_file entries for backend and frontend services ([c986a73](https://github.com/whoswhip/Sharpbin/commit/c986a73ef44df90c2e47f3a2dc60900b2271d230))
|
||||
* **docker:** correct environment variable syntax for backend service ([e0c9f1b](https://github.com/whoswhip/Sharpbin/commit/e0c9f1bbc1fc150d139043bbfb84ff16a86b20be))
|
||||
* **dotenv:** skip empty lines and comments when loading environment variables ([2302ebd](https://github.com/whoswhip/Sharpbin/commit/2302ebdffc74dbd5023803919730ac5bb8243abf))
|
||||
* **email:** ensure all email settings are validated before sending; allow nullable From property ([b9cff6a](https://github.com/whoswhip/Sharpbin/commit/b9cff6a0bd5899e3aaa3775981ae0782d621fa97))
|
||||
* **email:** validate settings before sending; use hmac for tokens ([2b66cb2](https://github.com/whoswhip/Sharpbin/commit/2b66cb27629726480c00ffae4775810a35ee4fcf))
|
||||
* **encryption:** improve encryption security: adjust salt size and memory parameters for AES encryption ([b54c12b](https://github.com/whoswhip/Sharpbin/commit/b54c12ba10c3f6607a6345caaa4d528e90f1ce0a))
|
||||
* forward headers during requests where needed ([3b53cfb](https://github.com/whoswhip/Sharpbin/commit/3b53cfbddf0397c8b040641d784dce8b070c9753))
|
||||
* forward the request header when viewing on the /[id] server route ([62d8059](https://github.com/whoswhip/Sharpbin/commit/62d80597dc51428fc3be810fb268b4bfd4cd6098))
|
||||
* **frontend:paste:** increase paste views only if api returns 'Paste view recorded.' ([4c071fc](https://github.com/whoswhip/Sharpbin/commit/4c071fcc3965f1164d95d0c2dfd729059ee7cfad))
|
||||
* **frontend:user:** resolve lint error ([2c3f8c9](https://github.com/whoswhip/Sharpbin/commit/2c3f8c95ac55a891caeaebacadad808bfc7180d2))
|
||||
* **frontend:** use darker version of tooltip on generate random password ([eef9803](https://github.com/whoswhip/Sharpbin/commit/eef98030d6daf6c223d5e12e7ad024211e411d13))
|
||||
* improve header handling and error checking in paste loading ([6d99a06](https://github.com/whoswhip/Sharpbin/commit/6d99a06c17b7365c26d4dd48405f2963f5826f1f))
|
||||
* improve icon consistency ([e102c91](https://github.com/whoswhip/Sharpbin/commit/e102c91d79618b87b71653e23df7a6511a6c09ba))
|
||||
* make syntax extension comparison case insensitive and remove '.' ([801426f](https://github.com/whoswhip/Sharpbin/commit/801426f93e08fdce0d548f8c539c5f7dc06fea93))
|
||||
* remove rate limiting on {id}/raw and {id} ([094c8e5](https://github.com/whoswhip/Sharpbin/commit/094c8e5e08dcbef33d4f0e4d965ac467d8d4d6d4))
|
||||
* **routes:** /raw/{pasteId} no longer returns a body on error ([38c8af1](https://github.com/whoswhip/Sharpbin/commit/38c8af1c5713defe06077842bacbf69ef47eff00))
|
||||
* set default value for AuthSettings__First_User_Admin and pass GIT_COMMIT_HASH as build argument ([f645846](https://github.com/whoswhip/Sharpbin/commit/f64584602eb7b29a7854923420c25811a2a64946))
|
||||
* switch to better sqlite-3 instead of experimental node api ([5296efa](https://github.com/whoswhip/Sharpbin/commit/5296efa9dbf4bfd6f6613cdee4806d170de9ba6d))
|
||||
* **types:** add missing createdAt field to Paste interface ([6047d48](https://github.com/whoswhip/Sharpbin/commit/6047d48da2d5920e9e79b4e12b48a142ec9e2646))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* /user/{uuid} redirects to /user/{username} based off uuid ([059d32e](https://github.com/whoswhip/Sharpbin/commit/059d32e42c93fa0113e0bf253ab8bb432b3fa0b2))
|
||||
* add GIT_COMMIT_HASH support for versioning in Dockerfile and footer ([5eebea3](https://github.com/whoswhip/Sharpbin/commit/5eebea314e6c475e012d0378aa4d6147485210f4))
|
||||
* add HatGlasses icon for anonymous users in Paste component ([b7ce54d](https://github.com/whoswhip/Sharpbin/commit/b7ce54d5a0e00ee27e53e492b71a973d63e94bef))
|
||||
* **auth:** add JWT user parsing from token ([d78baae](https://github.com/whoswhip/Sharpbin/commit/d78baae19e2508cac2205fcc9b3b09ee600d95fe))
|
||||
* **auth:** improve token refreshing ([75ecfbe](https://github.com/whoswhip/Sharpbin/commit/75ecfbe7e7724addf71f2a9d1de41f28132602a1))
|
||||
* **backend:** add DotEnv class for loading environment variables from .env file ([0023328](https://github.com/whoswhip/Sharpbin/commit/00233280d45a2fa87c4c01b9086620606be210e1))
|
||||
* email verification via smtp ([95da3f9](https://github.com/whoswhip/Sharpbin/commit/95da3f95435709692de347272fae01dff13ddf7c))
|
||||
* **email:** add email verification html templates ([0564d55](https://github.com/whoswhip/Sharpbin/commit/0564d55396da1f811aa7fa624a8f42392aeb49b9))
|
||||
* **email:** implement email queue management ([5420d94](https://github.com/whoswhip/Sharpbin/commit/5420d94595bba2731409677631551b7bc265ad3c))
|
||||
* guest param in user page ([8eede40](https://github.com/whoswhip/Sharpbin/commit/8eede40000f6a541188c95370073e76113d152d8))
|
||||
* **markdown:** add dont warn again feature ([e7cd372](https://github.com/whoswhip/Sharpbin/commit/e7cd3723a7c60e3f058de990e1b7ac2efb414683))
|
||||
* open graph embed image generation ([9486840](https://github.com/whoswhip/Sharpbin/commit/9486840f05fadac604f1ccd3a838f3f0d1a71f51))
|
||||
* **roles, visibility:** refactor user roles to use flags and introduce visibility enum ([44d7ae8](https://github.com/whoswhip/Sharpbin/commit/44d7ae8cd3ead498f7975a20b5269ee311553d23))
|
||||
|
||||
|
||||
|
||||
## [3.0.4](https://github.com/whoswhip/Sharpbin/compare/v3.0.3...v3.0.4) (2026-02-14)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **backend:** use GenerateSecureRandomString for api-keys, paste ids, and refresh tokens ([5017e73](https://github.com/whoswhip/Sharpbin/commit/5017e73bb54e626d4dc060fd553c972663eec45f))
|
||||
* **frontend:api-keys:** add flag to track successful API key fetch ([78f4ae1](https://github.com/whoswhip/Sharpbin/commit/78f4ae181eb18a98ed9964d8e651d84319fa8d2c))
|
||||
* **frontend:user:** resolve lint errors ([7d09870](https://github.com/whoswhip/Sharpbin/commit/7d09870ad25472ff17a1acc22d5724e199f2c931))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add dotnet-ef tool configuration to dotnet-tools.json ([db363f0](https://github.com/whoswhip/Sharpbin/commit/db363f0211972a06b622770ca522d3ef0bba12c8))
|
||||
* **backend:authentication:** implement API key authentication scheme and update authorization policies ([3374ead](https://github.com/whoswhip/Sharpbin/commit/3374eadb5654fa349a636c4a41a53df1ddf2edfe))
|
||||
* **backend:utilities:** implement GenerateSecureRandomString function that uses RandomNumberGenerator ([809b513](https://github.com/whoswhip/Sharpbin/commit/809b513e7a3f5a4f7faf64b02d9ed83e81c540b8))
|
||||
* **backend:** implement api keys; rename token -> verificationToken in paste creation api ([53d0f33](https://github.com/whoswhip/Sharpbin/commit/53d0f33ff026d6e5a188d80585e6a3bb633d9fa8))
|
||||
* **frontend:api-keys:** display the count of API keys in the header and adjust empty state condition ([3dc8070](https://github.com/whoswhip/Sharpbin/commit/3dc8070efeb19538c4ff120d2a681c4167c716f3))
|
||||
* **frontend:api-keys:** implement API key management features including creation, deletion, and fetching ([ee45deb](https://github.com/whoswhip/Sharpbin/commit/ee45deb43937cbf3996c3c379461110a484bd086))
|
||||
* **frontend:modal:** decrease modal background opacity and blur ([3b2801a](https://github.com/whoswhip/Sharpbin/commit/3b2801a65509d3a894c701f03028b2cd4599b456))
|
||||
* **frontend:stats:** enhance tooltip for total storage used to show uncompressed size ([cac3442](https://github.com/whoswhip/Sharpbin/commit/cac34423d99d1228f426be903da53bafca5f50e7))
|
||||
* **frontend:user:** improve UX; move user settings to settings tab ([5052bbd](https://github.com/whoswhip/Sharpbin/commit/5052bbdb135dc2df08db94874de5bf2bf738364c))
|
||||
* **frontend:** improve user page UX ([ff706d8](https://github.com/whoswhip/Sharpbin/commit/ff706d877742317cb8f4ccf72ba5f0791a6d2b88))
|
||||
|
||||
|
||||
|
||||
## [3.0.3](https://github.com/whoswhip/Sharpbin/compare/v3.0.2...v3.0.3) (2026-02-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* correct spelling of 'Verification' in PasteSettings and PasteController ([697ec38](https://github.com/whoswhip/Sharpbin/commit/697ec384f8a0d3d86eb7e523595ddda3cda256b4))
|
||||
* do not generate open api documents on build ([e901849](https://github.com/whoswhip/Sharpbin/commit/e90184992a1dd585bfb3728dc866193ab870fb86))
|
||||
* ensure length > 0 and that arrays have value before validating ([f95b347](https://github.com/whoswhip/Sharpbin/commit/f95b347191854e8057c8086e52165a83e2fa8a7d))
|
||||
* initialize multiselect state in modal component ([908441d](https://github.com/whoswhip/Sharpbin/commit/908441de4b7e857d8cbcc520da86cf1abaab0fa2))
|
||||
* prevent internal server endpoint leakage in openapi ([4917180](https://github.com/whoswhip/Sharpbin/commit/4917180624d1ec2f7af784c50c5cd2810beba1b3))
|
||||
* resolve lint issues ([b56a848](https://github.com/whoswhip/Sharpbin/commit/b56a848d21da5d8bb57c22bdc03bd84449813338))
|
||||
* simplify height adjustment logic for text area and markdown container ([f37e647](https://github.com/whoswhip/Sharpbin/commit/f37e647a1c0264a3b6229c270e75b8176ec93628))
|
||||
* update display name validation to allow spaces and improve error message ([755b356](https://github.com/whoswhip/Sharpbin/commit/755b356d616a339273c7e45207304e901617c367))
|
||||
* update stats tooltip to display correct pluralization for paste counts ([54ca2ee](https://github.com/whoswhip/Sharpbin/commit/54ca2ee6417e0a6cfcc14ccb0be6e79d9dc4cacd))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add statistics link to footer component ([cbbed2d](https://github.com/whoswhip/Sharpbin/commit/cbbed2d341670ba7b034af161ccdb3ddb3101dc0))
|
||||
* add statistics page ([22317a2](https://github.com/whoswhip/Sharpbin/commit/22317a2fae8f8a8ed45f313a46bb2489b8042f92))
|
||||
* allow spaces in display names ([abcf79c](https://github.com/whoswhip/Sharpbin/commit/abcf79c6458b97d1f75b6c31020fdc7ab957d4f2))
|
||||
* **backend:** allow spaces in display name during registration ([71363fa](https://github.com/whoswhip/Sharpbin/commit/71363fa1a467c660297301d4f35513bdfe39ccd5))
|
||||
* cache for 6 hours instead of 24 hours ([d04e296](https://github.com/whoswhip/Sharpbin/commit/d04e2962b51796393f77b66fd37f6efad924b413))
|
||||
* enhance API stats endpoint to include daily paste counts for the past week ([23e7973](https://github.com/whoswhip/Sharpbin/commit/23e7973e972f197954568fb292f1c8f6e5272c50))
|
||||
* implement web worker for syntax highlighting using highlight.js ([1cd6d16](https://github.com/whoswhip/Sharpbin/commit/1cd6d16d8538bf3b990f523703eb9abc19da5f36))
|
||||
* proxy openapi url ([698db0a](https://github.com/whoswhip/Sharpbin/commit/698db0a85e000e8b1ab76d82827b8f404ffd0f67))
|
||||
* true total paste size; always map the openapi route ([6b32994](https://github.com/whoswhip/Sharpbin/commit/6b32994d16b201a5a99037fcb23af30bd35876bc))
|
||||
* update tooltip function to accept parameters for styling ([c9591a4](https://github.com/whoswhip/Sharpbin/commit/c9591a43c78b7c8a09b3e7afa0e8b401b70efae0))
|
||||
|
||||
|
||||
|
||||
## [3.0.2](https://github.com/whoswhip/Sharpbin/compare/v3.0.1...v3.0.2) (2026-01-31)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add IValidateableObject interface to required DTO's ensuring model validation ([270360a](https://github.com/whoswhip/Sharpbin/commit/270360a32f9b9217a1be1057058a61c57f578e95))
|
||||
* adjust input margin for title field in paste creation ([d2486b9](https://github.com/whoswhip/Sharpbin/commit/d2486b9f6e1b87e2d4e13fcc2550292ad77170c3))
|
||||
* enable AllowMissingPrunePackageData in project configuration ([c52ad8b](https://github.com/whoswhip/Sharpbin/commit/c52ad8ba9b12e62324fc6bac445a3e1c5b275e95))
|
||||
* improve error handling and update user display name modal ([a6ffa98](https://github.com/whoswhip/Sharpbin/commit/a6ffa982a4225ef4512b925af39ed4836be40fbb))
|
||||
* update version to 3.0.1 in package-lock.json ([15f0be5](https://github.com/whoswhip/Sharpbin/commit/15f0be5a2f902429906c1acdfe7923b25c16be12))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add conventional-changelog and conventional-changelog-angular dependencies ([e4cf98a](https://github.com/whoswhip/Sharpbin/commit/e4cf98af096b4909e97898eaa452447a09307d31))
|
||||
* add inputMaxLength property to Modal component for better input control ([005cb5d](https://github.com/whoswhip/Sharpbin/commit/005cb5de23e244a4b07ea1173b7805f7cd2b2561))
|
||||
* add output caching and stats endpoint to track pastes and users ([ca210c5](https://github.com/whoswhip/Sharpbin/commit/ca210c5ea3e97d7a4e93f51794d1da7a6da40ebf))
|
||||
* createdAt paste property ([9d0cc54](https://github.com/whoswhip/Sharpbin/commit/9d0cc54db46a24d16f752b5db66baf1565891d26))
|
||||
* enhance PasteService with caching and cache invalidation methods ([5375e1c](https://github.com/whoswhip/Sharpbin/commit/5375e1caa64ce51bd0cd3613f8df68d6ea2d7aa4))
|
||||
* include createdAt in user responses ([854e50f](https://github.com/whoswhip/Sharpbin/commit/854e50fe78265a58af6004c3db12ca551c4372f9))
|
||||
* include paste createdAt in responses ([8aa1543](https://github.com/whoswhip/Sharpbin/commit/8aa1543296817745f66a724e349897d8496bb193))
|
||||
* user createdAt property ([500f457](https://github.com/whoswhip/Sharpbin/commit/500f457f976bc4742e8e3395f01eef84a0c16558))
|
||||
|
||||
|
||||
|
||||
## [3.0.1](https://github.com/whoswhip/Sharpbin/compare/v3.0.0...v3.0.1) (2026-01-27)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* adjust dropdown max height dynamically and improve search input positioning ([2d01e72](https://github.com/whoswhip/Sharpbin/commit/2d01e726a97b99a35017df9f477fa1304213bc9e))
|
||||
* adjust height properties for paste creation info ([01efa39](https://github.com/whoswhip/Sharpbin/commit/01efa399cf7d7aa1d38af1bc29017a8873f97dca))
|
||||
* adjust tooltip formatting for decrypted size display ([a7481b5](https://github.com/whoswhip/Sharpbin/commit/a7481b5852532d42697e723f8f49cfa126ce8212))
|
||||
* allow flexible display on cf turnstile ([3681f58](https://github.com/whoswhip/Sharpbin/commit/3681f586dc0a01fcfd197db3961386d4ac7fe371))
|
||||
* disable pointer events on menu icons ([590f0c3](https://github.com/whoswhip/Sharpbin/commit/590f0c3da9c4bd6f9db43a5866dddfb9a2859326))
|
||||
* enhance password validation and add show/hide functionality ([ec62e3b](https://github.com/whoswhip/Sharpbin/commit/ec62e3be7556f083ef8380dd4eece4f5e5b4f148))
|
||||
* enhance Paste component layout and user information display ([4db9867](https://github.com/whoswhip/Sharpbin/commit/4db986715cfd36d300677b7e527ff8e2de827791))
|
||||
* include author data in recent paste data ([c9aa0d9](https://github.com/whoswhip/Sharpbin/commit/c9aa0d9a16f9135be7be4b100c6c0966f3285e6a))
|
||||
* render all turnstiles as flexible and interaction-only ([75010d3](https://github.com/whoswhip/Sharpbin/commit/75010d303424a45d9435571b45e4d0d29ade23a9))
|
||||
* resize markdown preview as well ([51449ab](https://github.com/whoswhip/Sharpbin/commit/51449abe6e894d289374ec7ffcef21ff3d1e71c9))
|
||||
* resolve lint issue svelte/no-at-html-tags ([71fb5b1](https://github.com/whoswhip/Sharpbin/commit/71fb5b16160aa986ca577c25373dcc382ff96ba3))
|
||||
* update Open Graph description to use syntax name from consts ([a06021f](https://github.com/whoswhip/Sharpbin/commit/a06021f0cd67162446d9393a854ddc4f7f3a74b0))
|
||||
* update resize function call to use `previewMode` ensuring resize when switched to code ([16f5bff](https://github.com/whoswhip/Sharpbin/commit/16f5bff317a6620e3a7e5a0fd99ac6b56599dd8e))
|
||||
* update Turnstile configuration and improve layout for verification ([9c49c21](https://github.com/whoswhip/Sharpbin/commit/9c49c21e62118d277670677e51a685150194a2b6))
|
||||
* update visibility icons in Paste component ([6c8cdcc](https://github.com/whoswhip/Sharpbin/commit/6c8cdccbbfd3becdd5fae4674909c788f00edab7))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add CSV rendering functionality with PapaParse ([bfad18b](https://github.com/whoswhip/Sharpbin/commit/bfad18bb0551ddc2eb03f934ecedd2b7b89ddbf2))
|
||||
* add CSV to syntax lists ([147e43c](https://github.com/whoswhip/Sharpbin/commit/147e43cd8ab32da538e6ff76a68cdb7441e469e2))
|
||||
* add papaparse and its type definitions ([95316f5](https://github.com/whoswhip/Sharpbin/commit/95316f5a846c03a5e2b014717c26bea9005f933d))
|
||||
* add tailwind-scrollbar npm package ([43f9a25](https://github.com/whoswhip/Sharpbin/commit/43f9a25915ac32076636ab86781aa7efb5240b41))
|
||||
* close hamburger menu when clicked outside ([1937307](https://github.com/whoswhip/Sharpbin/commit/1937307ae728f0d77c9ee572adf1ba688648e0aa))
|
||||
* enhance CSV rendering with header support and improved styling ([c940fc5](https://github.com/whoswhip/Sharpbin/commit/c940fc5207a80563a620b37c9aeebce395c659e9))
|
||||
* include decrypted size in paste size tooltip ([7082fc4](https://github.com/whoswhip/Sharpbin/commit/7082fc45346824f14d6f8fe85743f73eca6a35c1))
|
||||
* style dropdown scrollbar ([091c6d8](https://github.com/whoswhip/Sharpbin/commit/091c6d895e638fc13b68207e3ae765664dfc80b6))
|
||||
|
||||
|
||||
|
||||
# [3.0.0](https://github.com/whoswhip/Sharpbin/compare/050f0bc935937b8b80500a59bc6ac5513fd7af93...v3.0.0) (2026-01-24)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add ASPNETCORE_URLS environment variable for backend service in docker-compose.yml ([c4f606e](https://github.com/whoswhip/Sharpbin/commit/c4f606ecf265678495b616a11c0fab1aa4ca9331))
|
||||
* add cursor pointer to the submit button for better UX ([f5de211](https://github.com/whoswhip/Sharpbin/commit/f5de211611c8142c0825286c0f514b1edc161d51))
|
||||
* add validation for display name length in user creation and update requests ([9bb620a](https://github.com/whoswhip/Sharpbin/commit/9bb620a4a31473385af6ffd32d2b7d7c5affd415))
|
||||
* adjust password hint display logic in registration form ([361cf76](https://github.com/whoswhip/Sharpbin/commit/361cf76f46598c1d797c745e44f2de5d960682bc))
|
||||
* center-align text in login and registration links in navbar ([4dafde7](https://github.com/whoswhip/Sharpbin/commit/4dafde739aaf04d4a7b0e08ee15415518bcf2e7b))
|
||||
* change to non-reactive statements ([55bee20](https://github.com/whoswhip/Sharpbin/commit/55bee20e5de3d4c155f2eaa0f7999110a86aa535))
|
||||
* correct conditional logic for user role checks in component rendering ([7298982](https://github.com/whoswhip/Sharpbin/commit/729898296b4e09fa8cada5feb524f1d3774a2d7c))
|
||||
* correct environment variable key for Turnstile Site Key in docker-compose ([2773813](https://github.com/whoswhip/Sharpbin/commit/2773813c263d59a20ceabd02ebabd763a3832ebc))
|
||||
* correct property name for TOTP enabled flag in parseTotpEnabled function ([9e56c4e](https://github.com/whoswhip/Sharpbin/commit/9e56c4eee1d97227b821d643640d2d1db593aba7))
|
||||
* correct syntax selection logic for file drag and drop handling ([62b5dce](https://github.com/whoswhip/Sharpbin/commit/62b5dcef00e6230ec8674d3de65617216e760e51))
|
||||
* display 2FA status only for the account owner ([4de6a6a](https://github.com/whoswhip/Sharpbin/commit/4de6a6a1186e97a7063d5e55008f9acc5043b912))
|
||||
* dont disabled login button when registrations are disabled ([bbfa9ff](https://github.com/whoswhip/Sharpbin/commit/bbfa9ffc560a87bcc8441fddc6d78496819a9144))
|
||||
* enhance paste size validation logic ([f467a2a](https://github.com/whoswhip/Sharpbin/commit/f467a2a89966e6025d7ac0a60eb89c99956e4d28))
|
||||
* enhance textarea styling and display content metrics ([fabef95](https://github.com/whoswhip/Sharpbin/commit/fabef95159e469abcf6316362f18de25aab0a0c6))
|
||||
* enhance tooltip functionality and update last login display ([d3c2efd](https://github.com/whoswhip/Sharpbin/commit/d3c2efd2108026b5e49f1a199c6f2afdeb0a06a0))
|
||||
* ensure JSDOM is only loaded in server-side environments ([7789ab6](https://github.com/whoswhip/Sharpbin/commit/7789ab6cb2822ca338186573c010047a3c5b0f48))
|
||||
* improve error handling and display for login failures ([ce66fe1](https://github.com/whoswhip/Sharpbin/commit/ce66fe13e8718b8abbf67adca9fa1775c932401f))
|
||||
* improve error handling and response messages in EditPaste method ([284c5e9](https://github.com/whoswhip/Sharpbin/commit/284c5e927e1ef796026ca1b1a078adadc1986721))
|
||||
* improve error handling for registration response ([d514e45](https://github.com/whoswhip/Sharpbin/commit/d514e456bf364b1dbdbd7e67938ca609c2362468))
|
||||
* improve error handling in paste fetching and add error page ([5e4afaf](https://github.com/whoswhip/Sharpbin/commit/5e4afafac0e57a24316761c555892fee5dc8394a))
|
||||
* improve error logging for view count increment failure ([8b84a2d](https://github.com/whoswhip/Sharpbin/commit/8b84a2d8a3dbcfa0909a9ba7ac79531244c268f2))
|
||||
* improve formatBytes function and display byte size in textarea ([2a9a4b9](https://github.com/whoswhip/Sharpbin/commit/2a9a4b9eefaef513df5437a9d548e1941583fc1e))
|
||||
* include url queries in resolve ([7857c32](https://github.com/whoswhip/Sharpbin/commit/7857c327eac1a2371552bedc1571650bffb29c0d))
|
||||
* increase max height ([7650fd7](https://github.com/whoswhip/Sharpbin/commit/7650fd786dbcffb9cba6aba9c073d9ec5e19c737))
|
||||
* inline is expired calculation ([2b60ee8](https://github.com/whoswhip/Sharpbin/commit/2b60ee86369731ebc98deaf007c725a544382b2a))
|
||||
* lint issues resolved ([21b6f95](https://github.com/whoswhip/Sharpbin/commit/21b6f95edc1ff34a3ee66f32083b4f99d9bbf2ac))
|
||||
* load turnstile script in layout and explicitly render ([2c24af5](https://github.com/whoswhip/Sharpbin/commit/2c24af5ac98dd4959e353571d3186fb98b459bf4))
|
||||
* null user/paste fk in reports on delete ([f8a1490](https://github.com/whoswhip/Sharpbin/commit/f8a149058295ebc56fc43cecf03b76792fc62529))
|
||||
* prevent moderators from modifiying higher roles(admin) ([3711885](https://github.com/whoswhip/Sharpbin/commit/3711885a38e18ddf6e478e17c671c4c7774c0d3e))
|
||||
* properly set limiter ([6f99036](https://github.com/whoswhip/Sharpbin/commit/6f990364a59b0a9801a6dbd715c70c2f29e63e9c))
|
||||
* refresh token ([19f439a](https://github.com/whoswhip/Sharpbin/commit/19f439a4052d16a3bddba36dc15822906ca92e11))
|
||||
* remove dependency condition for backend service health check in docker-compose.yml ([095df2f](https://github.com/whoswhip/Sharpbin/commit/095df2f3f3aff1eccf4f023ca1a77bc11d66bbea))
|
||||
* remove quotes from DATA_PROTECTION_KEY_PATH in docker-compose ([f96396b](https://github.com/whoswhip/Sharpbin/commit/f96396b586f5f0b5da66227c08767be348f5cbab))
|
||||
* remove quotes from default connection string in docker-compose ([d5565f9](https://github.com/whoswhip/Sharpbin/commit/d5565f9a68bf38035d994002812c3411427f563e))
|
||||
* remove unused nuget package ([4bd6a18](https://github.com/whoswhip/Sharpbin/commit/4bd6a18e31970f4568f0d405454c30b56e06c895))
|
||||
* reset Turnstile on login and registration error handling ([5a630d2](https://github.com/whoswhip/Sharpbin/commit/5a630d2a715acc851add8f82b19dba111d98c2bd))
|
||||
* reset turnstile on login error handling ([1da88db](https://github.com/whoswhip/Sharpbin/commit/1da88dba4ed500baf6dc57b6eeb02b115c0fd000))
|
||||
* resolve lint issues ([1f4fda1](https://github.com/whoswhip/Sharpbin/commit/1f4fda1a16f92cebae716642482d959ad300c5a7))
|
||||
* ssr request to user; navbar positioning ([bffc4e2](https://github.com/whoswhip/Sharpbin/commit/bffc4e2bf41fe1a3dd93f3042be0e796b6f986d2))
|
||||
* **style:** update Navbar styling for improved layout and consistency ([6c3caaf](https://github.com/whoswhip/Sharpbin/commit/6c3caaf2ecaa6dc9e616d7f5a7f65ee1a15c091c))
|
||||
* **styling:** add table styling for markdown elements ([825d384](https://github.com/whoswhip/Sharpbin/commit/825d384db4c906f373ea92ae3e4b46efd741e862))
|
||||
* **styling:** adjust margin and padding for first child in markdown elements ([8f5499a](https://github.com/whoswhip/Sharpbin/commit/8f5499ae05f69c131447fef6188680d448ed895e))
|
||||
* **styling:** enforce max width on recent pastes titles ([8accfa2](https://github.com/whoswhip/Sharpbin/commit/8accfa2dc525f528337e2cbd79ab6a6a2c2b748f))
|
||||
* token refreshing using wrong object path ([e45785e](https://github.com/whoswhip/Sharpbin/commit/e45785e1b8bb64a0834cf420db4866307146132d))
|
||||
* update API fetch calls to use dynamic apiUrl ([6072f7f](https://github.com/whoswhip/Sharpbin/commit/6072f7f674bc3def903815de35536ed933cff7fd))
|
||||
* update API routes for fetching raw paste content and deleting pastes ([48543c7](https://github.com/whoswhip/Sharpbin/commit/48543c7ff03b1ff4b3efa96de56097fb9ada2f02))
|
||||
* update database connection string configuration in Program.cs and docker-compose.yml ([011b523](https://github.com/whoswhip/Sharpbin/commit/011b523fd321e0834c73790b2553adee37a022f6))
|
||||
* update docker-compose to reflect correct backend directory structure ([113ad49](https://github.com/whoswhip/Sharpbin/commit/113ad499d9806a7a237f6afdb9a6bf02ebc238aa))
|
||||
* update environment variables in docker-compose for backend and frontend services ([5e8d7be](https://github.com/whoswhip/Sharpbin/commit/5e8d7be86423247e63a350d440bc52cf3428d312))
|
||||
* update Navbar and layout server to improve structure and data handling ([a912d04](https://github.com/whoswhip/Sharpbin/commit/a912d0463b1e8517f055f596c2cb033b88db6b9b))
|
||||
* update paste view count display in metadata ([f9b63ed](https://github.com/whoswhip/Sharpbin/commit/f9b63edf776e2715b09de2d408aab4ba85ccd50f))
|
||||
* update profile link to direct to user page instead of dashboard ([ff52498](https://github.com/whoswhip/Sharpbin/commit/ff52498cf99a74936d47d73369c7fdd7b771f0df))
|
||||
* update SQLite connection string retrieval in Program.cs ([6178888](https://github.com/whoswhip/Sharpbin/commit/6178888246871f38ab8373bacbb2a61fba6d4046))
|
||||
* update TOTP API request payload to use 'code' instead of 'totpcode' ([6bcc62a](https://github.com/whoswhip/Sharpbin/commit/6bcc62a7e7b77c1129c16d9a8c979e003b6481e5))
|
||||
* update version number to 3.0.0 and remove beta check from footer ([8252d58](https://github.com/whoswhip/Sharpbin/commit/8252d58f47d503a0c40f95bde9ee277341e801b9))
|
||||
* use $app/state ([b44f0bc](https://github.com/whoswhip/Sharpbin/commit/b44f0bce0ab5f7fcedf9c206362a31947215eef9))
|
||||
* use margin-bottom instead of margin-top for elements ([bd7d115](https://github.com/whoswhip/Sharpbin/commit/bd7d1154eaf57e310a82cb43c09baf15c499a489))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* /raw/{id} endpoint ([ca87b1a](https://github.com/whoswhip/Sharpbin/commit/ca87b1a5f220a6f3b8857cf00602abf867c9a7d9))
|
||||
* account deletion; auto incremental uids; display name renaming UI + account deletion UI; enhanced username validation ([fe54ff1](https://github.com/whoswhip/Sharpbin/commit/fe54ff15ce7122373643eece9981eb05a1d7c7d0))
|
||||
* add application version definition to Vite config ([eca6867](https://github.com/whoswhip/Sharpbin/commit/eca6867fcab5c1ba4d1d327c76f18fd21290abd6))
|
||||
* add delete functionality for pastes with authorization check ([3015f97](https://github.com/whoswhip/Sharpbin/commit/3015f97ff977fbfd9b23a11aad016ac7408be752))
|
||||
* add Dockerfile and docker-compose for backend and frontend services ([31142e0](https://github.com/whoswhip/Sharpbin/commit/31142e0cf96d2ff868fadf1ecac192a07ebc5c2d))
|
||||
* add editedAt field to Paste interface and enhance paste editing functionality ([86b74a1](https://github.com/whoswhip/Sharpbin/commit/86b74a140a546651d301079b71531468d0b1d52d))
|
||||
* add Footer component to layout for improved user navigation ([e093550](https://github.com/whoswhip/Sharpbin/commit/e0935505ea01c286cb802337461b1ebbb4eb6f2d))
|
||||
* add health check endpoint returning status ok ([dfdce51](https://github.com/whoswhip/Sharpbin/commit/dfdce51c6e648b601880a16644d7790b41550129))
|
||||
* add health checks for backend and frontend services in docker-compose.yml ([08c4be4](https://github.com/whoswhip/Sharpbin/commit/08c4be4f7eb8e985114d1f87a8bd69a7bad0a9ee))
|
||||
* add health checks for backend and frontend services in docker-compose.yml ([57dad56](https://github.com/whoswhip/Sharpbin/commit/57dad564a6df35ea488fab40fa9798511036d4ac))
|
||||
* add health checks for database connectivity ([cab1b17](https://github.com/whoswhip/Sharpbin/commit/cab1b170c1218c47c5c4f366425731c3fdb5d67a))
|
||||
* add isBinaryData utility function and integrate it into paste handling; add drag and drop functionality when creating a paste ([bf0eac9](https://github.com/whoswhip/Sharpbin/commit/bf0eac9ed8aa00cf4d82236cf8257f87bc6b8588))
|
||||
* add markdown parsing and rendering support ([406381f](https://github.com/whoswhip/Sharpbin/commit/406381fbfe724249b41477f64ef42116882a671d))
|
||||
* add Pagination interface and integrate it into User type ([a9e1e82](https://github.com/whoswhip/Sharpbin/commit/a9e1e823591c01be4dc960bf5427131480dfa413))
|
||||
* add pagination to user retrieval endpoints; enhance BuildUserResponse to include pagination details ([93df14e](https://github.com/whoswhip/Sharpbin/commit/93df14e59ce876c877d34d28a9f0a0cf3d53eb28))
|
||||
* add PasteCleanUpService as a hosted service ([f578b58](https://github.com/whoswhip/Sharpbin/commit/f578b58780930d253837d4e1c795f46c6b27b9df))
|
||||
* add PasteSettings environment variables for internal API key and HMAC secret ([a6fa65c](https://github.com/whoswhip/Sharpbin/commit/a6fa65c3bd67fbb1133737d738626c345304f503))
|
||||
* add recent pastes page with data fetching and display logic ([8a6ab29](https://github.com/whoswhip/Sharpbin/commit/8a6ab29f52ddd6e05c211569323d0d4d48b4938b))
|
||||
* add registration status check and disable form elements when registration is disabled ([b1d2d3f](https://github.com/whoswhip/Sharpbin/commit/b1d2d3f5bba5e7f0bab38448fc25baa8a4551317))
|
||||
* add variant support for dropdown component styling ([1950dc4](https://github.com/whoswhip/Sharpbin/commit/1950dc47ae8c5ca721851999afb2ce32b7c5c4cb))
|
||||
* admins can change user's roles ([99feb27](https://github.com/whoswhip/Sharpbin/commit/99feb2795a17b43724985cbf1722088fde0ac281))
|
||||
* auth, compression, jwt, paste wip, roles, ratelimiting ([6ec1a7f](https://github.com/whoswhip/Sharpbin/commit/6ec1a7fa7b3254e6ab09aaed8943534b79dac9cd))
|
||||
* auto detect syntax from file extension on drag and drop; syntax from extension function ([9e05600](https://github.com/whoswhip/Sharpbin/commit/9e056009e3858d9a56bd71638cd32db3ce122a60))
|
||||
* bypass user confirmation when loading external assets in markdown for trusted domains ([35d891b](https://github.com/whoswhip/Sharpbin/commit/35d891bed7bd7fb2415a14e74f45eb5b7d4e3453))
|
||||
* create Paste component for displaying paste details ([753d28f](https://github.com/whoswhip/Sharpbin/commit/753d28f720c9f7f6a3b7d787ca19a8149d592ee7))
|
||||
* declare application version constant in app.d.ts ([72206e9](https://github.com/whoswhip/Sharpbin/commit/72206e9ba214b602cafd2836d880ac06debb69de))
|
||||
* enable registration toggle and update Navbar to reflect registration status ([159fcc2](https://github.com/whoswhip/Sharpbin/commit/159fcc2a890480cfad0cc19dd153c84aa1af88d0))
|
||||
* enhance AuthService to support admin role assignment for the first user ([c934c85](https://github.com/whoswhip/Sharpbin/commit/c934c85b130d2c0086146110f3211f612387b8d3))
|
||||
* enhance code highlighting for plaintext in syntax highlighter ([5cb30a9](https://github.com/whoswhip/Sharpbin/commit/5cb30a90a760874d54cc18e0adc63cfe6812d1c7))
|
||||
* enhance decryption process with status updates and improved user feedback ([7b3af77](https://github.com/whoswhip/Sharpbin/commit/7b3af774494c31f8fcd829d20f9bb5f46242320a))
|
||||
* enhance paste creation with dynamic textarea resizing and improved password handling; generate random password button in paste creation; show password in paste creation; ([5410a89](https://github.com/whoswhip/Sharpbin/commit/5410a8973a81dc6a854f1c685e3a3546de985486))
|
||||
* enhance tooltip functionality and improve date formatting ([8ab66f5](https://github.com/whoswhip/Sharpbin/commit/8ab66f5f159c1c34d29c456fef9a4c626548c6aa))
|
||||
* enhance tooltip functionality; prevent empty tooltips for paste titles ([7eb0204](https://github.com/whoswhip/Sharpbin/commit/7eb0204e6751df148b6520c6ccd665289e31341b))
|
||||
* enhance user experience with tooltips; implement return URL handling on login and registration; add user roles; improve paste visibility checks ([5fca207](https://github.com/whoswhip/Sharpbin/commit/5fca207ad61acf0dca4c9fd13ab5a598d89ba890))
|
||||
* implement decryptAes function; moved to encryption.ts ([f61f31d](https://github.com/whoswhip/Sharpbin/commit/f61f31de0e9a3c97a347d38783cddb4c0d7f83fe))
|
||||
* implement mobile support for navbar ([63f55d2](https://github.com/whoswhip/Sharpbin/commit/63f55d2bdac475bd7d981d87475fa4e8cddb6b72))
|
||||
* implement modal component for password input and confirmation actions ([b6e020f](https://github.com/whoswhip/Sharpbin/commit/b6e020fa6987b5ecad5ca78d24ce87e41799c177))
|
||||
* implement pagination for user pastes; enhance fetchPage function and update display logic ([49b9673](https://github.com/whoswhip/Sharpbin/commit/49b9673d48d50a5ca2adea9b4c2055ae2c88f001))
|
||||
* implement paste decryption ([3a54951](https://github.com/whoswhip/Sharpbin/commit/3a549511f93d7001d246c318545e6edb307e2f99))
|
||||
* implement rate limiting policy for site info endpoints in Auth and Paste controllers ([3895bd9](https://github.com/whoswhip/Sharpbin/commit/3895bd968136071cc09bba686107f693f7e47dc3))
|
||||
* implement registration page with Turnstile verification and loading state ([24b25c2](https://github.com/whoswhip/Sharpbin/commit/24b25c2291eea16fab16c250b5856b91f7385b74))
|
||||
* implement server-side user data fetching; enhance user controller for detailed responses; update token handling to use cookies ([4151c62](https://github.com/whoswhip/Sharpbin/commit/4151c62b8cd10cdbf6a757f6e82935e8d5426a5a))
|
||||
* implement Turnstile verification for enhanced security during login and registration ([848b859](https://github.com/whoswhip/Sharpbin/commit/848b8598e5fb407f284027875c1f09c396b4aa6f))
|
||||
* implement user update functionality by UUID and add validation to UpdateUserRequest ([f40d4ab](https://github.com/whoswhip/Sharpbin/commit/f40d4ab68c3aabf95b8775601b1534bda9665b4b))
|
||||
* improve file download naming by using syntax extension conditionally ([fed0663](https://github.com/whoswhip/Sharpbin/commit/fed06630b7383eb185b2afbdfd30d2776416bcc5))
|
||||
* improve paste creation validation; add content size check and remove unnecessary logging ([dd6ce5c](https://github.com/whoswhip/Sharpbin/commit/dd6ce5c39506e9e22aeefa4db34ac8caa48a5cdd))
|
||||
* improve recent page; improve SEO for pages ([3a5738b](https://github.com/whoswhip/Sharpbin/commit/3a5738b53173ddae500098ffcbf1769dada11584))
|
||||
* initial commit ([050f0bc](https://github.com/whoswhip/Sharpbin/commit/050f0bc935937b8b80500a59bc6ac5513fd7af93))
|
||||
* integrate hash-wasm for enhanced AES encryption and decryption ([7e1fb3a](https://github.com/whoswhip/Sharpbin/commit/7e1fb3add4f438a206638ea0c90b0a27fd108c53))
|
||||
* login & registration; enhanced paste view; custom dropdown + search; navbar; global user access via store; auto token refresh; paste creation as user; /api/user/me, returns info on yourself including pastes; ([db1d870](https://github.com/whoswhip/Sharpbin/commit/db1d8704a1d0f183812fbd41ad077274c6626801))
|
||||
* paste cleanup service; sveltekit frontend; paste editing; paste metadata modifying ([adad139](https://github.com/whoswhip/Sharpbin/commit/adad139081fb4d9b2ed644e8fe4cdd89ac2ef38d))
|
||||
* paste compression & verification enforcement settings; enforce 2fa on admins setting; increase paste validation; anonymous uploads ([9f55aa1](https://github.com/whoswhip/Sharpbin/commit/9f55aa1b2273ee0298892dba380c71630c743289))
|
||||
* paste creation, utilities, revert to gzip, grammar fixes etc ([93daa2e](https://github.com/whoswhip/Sharpbin/commit/93daa2e1a2b75cc2e93cbc7149b837e79eb9ece4))
|
||||
* paste creation; paste viewing; more langs supported; jwt settings class; paste settings class; data validation on paste metadata modification ([b9b14a3](https://github.com/whoswhip/Sharpbin/commit/b9b14a3d5a553fd1e7e7294c8ba29cd8cb8218dd))
|
||||
* paste views; configuration validation; hmacsha256 method; enhance paste clean up serivce; paste view clean up service; ([3048af3](https://github.com/whoswhip/Sharpbin/commit/3048af3a6dece0338e278bf6d6b2358c0f4952fc))
|
||||
* preview markdown in paste creation; prevent external option in parseMarkdown ([3f27a3a](https://github.com/whoswhip/Sharpbin/commit/3f27a3a3e726e941ad6e996db53f9366506a7012))
|
||||
* refactor drag and drop file handling to update syntax selection conditionally ([ca9fa81](https://github.com/whoswhip/Sharpbin/commit/ca9fa81771af49b20628c148a1ac61ad6a168bf9))
|
||||
* refactor refresh token handling; update schema and logic for improved security and functionality ([ae91108](https://github.com/whoswhip/Sharpbin/commit/ae91108484ff73a6cdee16e0454acc330a221a33))
|
||||
* reporting apis; better rate limiting ([14bbd9c](https://github.com/whoswhip/Sharpbin/commit/14bbd9c762f641ac738714822d19845d86bb6582))
|
||||
* reports; improved+simplifed modals; extractError funcction; ([67447d5](https://github.com/whoswhip/Sharpbin/commit/67447d51aec59af200524e7f33bcee5678adc2bc))
|
||||
* seo optimizations + opengraph embeds ([3bbd646](https://github.com/whoswhip/Sharpbin/commit/3bbd64631a46d510e720db3a3d5cf7ad4298702d))
|
||||
* totp 2fa; httpcontext extension for jwtuser; asp.net data protection; prevent banned users from certain actions; account deletion requires 2fa if enabled; making users admins requires 2fa if enabled; httpcontext extension to get ip; enhance user store ([20ceb91](https://github.com/whoswhip/Sharpbin/commit/20ceb91db8405172d5beb9df646d3d912cea40a5))
|
||||
* update API routes for paste options and recent pastes ([1f2761f](https://github.com/whoswhip/Sharpbin/commit/1f2761f463e160a0d4d865a4d6a5763fc408712b))
|
||||
* update button styles for active state in paste creation ([6981836](https://github.com/whoswhip/Sharpbin/commit/698183690c1b48b6e6ebf83f62025242d746c607))
|
||||
* update favicon and improve tooltip for paste size display ([1ed2178](https://github.com/whoswhip/Sharpbin/commit/1ed21789e656dfdc7a65119f4c5ec010a1669593))
|
||||
* update minimum height for main sections across multiple pages for consistent layout ([c565c57](https://github.com/whoswhip/Sharpbin/commit/c565c57e20cb0eb7d6e57e17182382e2ee931190))
|
||||
* view raw button; paste header follows when scrolling; scroll to top button appears after scrolling far enough ([28a0ccb](https://github.com/whoswhip/Sharpbin/commit/28a0ccbfab4461fd6fe75d25b3f7cffce063041f))
|
||||
|
||||
|
||||
### Reverts
|
||||
|
||||
* Revert "chore: format via csharpier" ([6bea6c4](https://github.com/whoswhip/Sharpbin/commit/6bea6c49bef1eea4dfd72d962b4e06e20b64594f))
|
||||
|
||||
|
||||
|
||||
@@ -1,111 +1,21 @@
|
||||
# SharpbinV3
|
||||
# SharpbinV2
|
||||
SharpbinV2 is a re-write to the original messy code base.
|
||||
|
||||
Sharpbin is a [pastebin](https://en.wikipedia.org/wiki/Pastebin)-style website built with ASP.NET Core and SvelteKit.
|
||||
Instead of using html files and replacing variables(Simple SSR) it is now done with just apis and static html pages served from `wwwroot`.
|
||||
## Current Features
|
||||
- Account Systrem
|
||||
- Syntax Highlighting
|
||||
- Private Pastes with Client Side Encryption
|
||||
- Raw Text Serving
|
||||
- Paste Compression at Rest and on Response Transit (Files are only compressed when there is a considerable file size decrease)
|
||||
- Cleaner Code Base
|
||||
- Paste Analytics (Views etc.)
|
||||
|
||||
A live instance is available at [sharpbin.cc](https://sharpbin.cc).
|
||||
|
||||
## Features
|
||||
|
||||
- User authentication and account management.
|
||||
- Syntax highlighting for various programming languages.
|
||||
- Private pastes with client-side encryption.
|
||||
- Raw text serving for easy sharing and scripting.
|
||||
- Paste editing including content, syntax, title, and expiration.
|
||||
- Configurable paste expiration.
|
||||
- Server-side paste compression to save storage.
|
||||
- Captcha support via Cloudflare Turnstile.
|
||||
|
||||
## Getting Started
|
||||
|
||||
The easiest way to run SharpbinV3 is using Docker Compose.
|
||||
|
||||
1. Ensure Docker and Docker Compose are installed.
|
||||
2. Clone the repository.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/whoswhip/Sharpbin.git
|
||||
```
|
||||
|
||||
3. In the repository root, copy `.env.example` to `.env`.
|
||||
4. Replace the secret placeholders and configure your domain and Turnstile keys. Set `ORIGIN` to the public frontend URL, including the scheme. For local Docker testing, use `ORIGIN=http://localhost:5173`, `Domain=localhost:5173`, `Https=false`, and `AllowedCorsOrigins__0=http://localhost:5173`.
|
||||
5. Run the following command in the root directory:
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
### Configuration
|
||||
|
||||
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:
|
||||
|
||||
```json
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Data Source=sharpbin.db"
|
||||
},
|
||||
```
|
||||
|
||||
#### Backend (SharpbinV3.Server)
|
||||
|
||||
- `Domain`: The domain your instance of Sharpbin will be hosted at (e.g., example.com)
|
||||
- `Https`: Whether the public instance uses HTTPS. Used when generating email links; this does not enable TLS on the server.
|
||||
- `AllowedCorsOrigins__0`: An allowed browser origin for the backend API (e.g., `https://example.com`). Use numbered entries for additional origins.
|
||||
- `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=/app/data/sharpbin.db`).
|
||||
- `JwtSettings__Secret`: A random secret of 32-128 characters used for signing JWT tokens.
|
||||
- `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key.
|
||||
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
|
||||
- `AuthSettings__Registration_Enabled`:**true**: Enables/disables registration.
|
||||
- `AuthSettings__First_User_Admin`: Gives the first user the admin role, it is recommended to disable this after use.
|
||||
- `AuthSettings__Admins_Require_2FA`: Enforces Admins to have 2FA when trying to do certain actions.
|
||||
- `AuthSettings__API_Key_HMAC_Secret`: Recommended to securely hash API keys, but is not required.
|
||||
- `PasteSettings__MaxTitleLength`: Max title length in characters.
|
||||
- `PasteSettings__MaxPasteSizeInBytes`:**1_048_576** (1MB): Max Paste Size set in bytes.
|
||||
- `PasteSettings__EnablePasteCompression`:**true**: Enables/Disables server-side paste compression.
|
||||
- `PasteSettings__RequiresVerification`:**true**: Enables/Disables CAPTCHA verification when creating pastes.
|
||||
- `PasteSettings__View_HMAC_Secret`: A required random secret of 32–128 characters used to hash viewer identifiers.
|
||||
- `PasteSettings__View_Internal_API_Key`: A shared key of 32–128 characters used to authorize view recording. Compose passes it to both services.
|
||||
|
||||
#### Frontend (SharpbinV3.Client)
|
||||
|
||||
- `VITE_API_URL`: The backend URL reachable from the frontend server. Defaults to `http://localhost:5050` when running directly and `http://backend:8080` in Compose. Browser requests use the frontend's `/api` proxy.
|
||||
- `ORIGIN`: The public frontend URL, including its scheme (e.g., `https://example.com`). Used by the production Node server; see [SvelteKit's Node adapter documentation](https://svelte.dev/docs/kit/adapter-node#ORIGIN-PROTOCOL_HEADER-HOST_HEADER-and-PORT_HEADER).
|
||||
- `VITE_ALLOWED_HOSTS`: A comma-separated list used only by Vite dev/preview (e.g., `localhost,sharpbin.cc`). Export it in the shell before starting Vite; the config reads `process.env` directly. It does not configure production host restrictions.
|
||||
- `VIEW_INTERNAL_API_KEY`: The production frontend's shared view-recording key. Compose sets it from `PasteSettings__View_Internal_API_Key`; do not duplicate it in the root `.env`. When running the frontend directly, set it yourself or use the existing `View_HMAC_Internal_API_Key` fallback.
|
||||
|
||||
When `NODE_ENV=development`, the frontend uses a fixed development-only internal key matching the backend's checked-in development configuration and ignores both environment key names. See the [client README](SharpbinV3.Client/README.md) for development and standalone production setup.
|
||||
|
||||
The frontend will be accessible at http://localhost:5173.
|
||||
|
||||
## Project Structure
|
||||
|
||||
- **[SharpbinV3.Server](SharpbinV3.Server/README.md)**: Backend API built with C# and ASP.NET Core. Refer to its README for server-side development and configuration.
|
||||
- **[SharpbinV3.Client](SharpbinV3.Client/README.md)**: Frontend application built with SvelteKit and TypeScript. Refer to its README for client-side development and setup.
|
||||
## TODO
|
||||
- [ ] Password Resets
|
||||
- [x] Switch to Controllers
|
||||
- [ ] Admin Panel
|
||||
- [ ] Paste Editing
|
||||
- [ ] Paste Searching (maybe)
|
||||
- [x] Paste Deletion
|
||||
- [ ] Switch to Razor Pages?
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SharpbinV2.Server.Services;
|
||||
using SharpbinV2.Server.Models;
|
||||
using Bcrypt = BCrypt.Net.BCrypt;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
|
||||
namespace SharpbinV2.Server.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/auth")]
|
||||
public class AuthController : Controller
|
||||
{
|
||||
private readonly DatabaseService _databaseService;
|
||||
private readonly ILogger<AuthController> _logger;
|
||||
|
||||
public AuthController(DatabaseService databaseService, ILogger<AuthController> logger)
|
||||
{
|
||||
_databaseService = databaseService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
[EnableRateLimiting("auth")]
|
||||
public async Task<IActionResult> Login([FromBody] AuthRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(request.Username) && string.IsNullOrWhiteSpace(request.Email))
|
||||
return BadRequest(new { success = false, message = "Username or Email is required" });
|
||||
if (request.Password.Length is < 8 or > 128)
|
||||
return BadRequest(new { success = false, message = "Password must be between 8 and 128 characters" });
|
||||
if (!string.IsNullOrWhiteSpace(request.Username) && request.Username.Length > 32)
|
||||
return BadRequest(new { success = false, message = "Username must be 32 characters or less" });
|
||||
if (!string.IsNullOrWhiteSpace(request.Email) && request.Email.Length > 128)
|
||||
return BadRequest(new { success = false, message = "Email must be 128 characters or less" });
|
||||
if (!string.IsNullOrWhiteSpace(request.Username) && !string.IsNullOrWhiteSpace(request.Email))
|
||||
return BadRequest(new { success = false, message = "Please provide either a username or an email, not both" });
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(requestDetails.Token))
|
||||
{
|
||||
var _session = await _databaseService.UserFromToken(requestDetails.Token);
|
||||
if (_session != null)
|
||||
{
|
||||
return BadRequest(new { success = false, message = "You are already logged in" });
|
||||
}
|
||||
}
|
||||
|
||||
User? user = null;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Username))
|
||||
user = await _databaseService.UserFromUsername(request.Username);
|
||||
else if (!string.IsNullOrWhiteSpace(request.Email))
|
||||
user = await _databaseService.UserFromEmail(request.Email);
|
||||
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid username or password" });
|
||||
|
||||
if (!Bcrypt.Verify(request.Password, user.Password))
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Invalid username or password" });
|
||||
}
|
||||
|
||||
string token = HelperService.GenerateToken();
|
||||
|
||||
var session = await _databaseService.CreateSession(user, requestDetails, token) ?? new Session();
|
||||
if (session.UUID == "0" || session == null)
|
||||
return StatusCode(500, new { success = false, message = "Failed to create session" });
|
||||
|
||||
var cookieOptions = new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
#if DEBUG
|
||||
Secure = false,
|
||||
#else
|
||||
Secure = true,
|
||||
#endif
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(14)
|
||||
};
|
||||
Response.Cookies.Append("Authorization", token, cookieOptions);
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
message = "Login successful",
|
||||
token
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"Error during login attempt for user {request.Username ?? request.Email}");
|
||||
return StatusCode(500, "Internal server error");
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("register")]
|
||||
[EnableRateLimiting("auth")]
|
||||
public async Task<IActionResult> Register([FromBody] AuthRequest request)
|
||||
{
|
||||
try
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(request.Username) && string.IsNullOrWhiteSpace(request.Email))
|
||||
return BadRequest(new { success = false, message = "Username or Email is required" });
|
||||
if (request.Password.Length is < 8 or > 128)
|
||||
return BadRequest(new { success = false, message = "Password must be between 8 and 128 characters" });
|
||||
if (request.Username.Length is < 3 or > 32)
|
||||
return BadRequest(new { success = false, message = "Username must be between 3 and 32 characters" });
|
||||
if (request.Email.Length > 128)
|
||||
return BadRequest(new { success = false, message = "Email must be 128 characters or less" });
|
||||
if (!string.IsNullOrWhiteSpace(request.Email) && !HelperService.IsValidEmail(request.Email))
|
||||
return BadRequest(new { success = false, message = "Invalid email" });
|
||||
if (!string.IsNullOrWhiteSpace(request.Username) && !string.IsNullOrWhiteSpace(request.Email))
|
||||
return BadRequest(new { success = false, message = "Please provide either a username or an email, not both" });
|
||||
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(requestDetails.Token))
|
||||
{
|
||||
var _session = await _databaseService.UserFromToken(requestDetails.Token);
|
||||
if (_session != null)
|
||||
{
|
||||
return BadRequest(new { success = false, message = "You are already logged in" });
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.Username))
|
||||
{
|
||||
var existingUser = await _databaseService.UserFromUsername(request.Username);
|
||||
if (existingUser != null)
|
||||
return BadRequest(new { success = false, message = "Username already exists" });
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(request.Email))
|
||||
{
|
||||
var existingUser = await _databaseService.UserFromEmail(request.Email);
|
||||
if (existingUser != null)
|
||||
return BadRequest(new { success = false, message = "Email already exists" });
|
||||
}
|
||||
|
||||
string hashedPassword = Bcrypt.HashPassword(request.Password, Bcrypt.GenerateSalt(12));
|
||||
string token = HelperService.GenerateToken();
|
||||
string uuid = Guid.NewGuid().ToString();
|
||||
|
||||
User? user = await _databaseService.CreateUser(request.Username, request.Email, hashedPassword, uuid);
|
||||
if (user == null)
|
||||
return StatusCode(500, new { success = false, message = "Failed to create user" });
|
||||
|
||||
var session = await _databaseService.CreateSession(user, requestDetails, token) ?? new Session();
|
||||
|
||||
if (session.UUID == "0" || session == null)
|
||||
return StatusCode(500, new { success = false, message = "Failed to create session" });
|
||||
|
||||
var cookieOptions = new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
#if DEBUG
|
||||
Secure = false,
|
||||
#else
|
||||
Secure = true,
|
||||
#endif
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(14)
|
||||
};
|
||||
|
||||
Response.Cookies.Append("Authorization", token, cookieOptions);
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
message = "Registration successful",
|
||||
user = new
|
||||
{
|
||||
user.UID,
|
||||
user.UUID,
|
||||
user.Username,
|
||||
user.Email,
|
||||
user.DisplayName,
|
||||
user.Created
|
||||
},
|
||||
token
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"Error during registration attempt for user {request.Username ?? request.Email}");
|
||||
return StatusCode(500, "Internal server error");
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("authenticated")]
|
||||
public async Task<IActionResult> IsAuthenticated()
|
||||
{
|
||||
try
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(requestDetails.Token))
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Not authenticated, no token found" });
|
||||
}
|
||||
var user = await _databaseService.UserFromToken(requestDetails.Token);
|
||||
if (user == null)
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Not authenticated, invalid token" });
|
||||
}
|
||||
var session = await _databaseService.GetSession(requestDetails.Token);
|
||||
long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
if (session == null || session.Expirary < currentTime)
|
||||
{
|
||||
Response.Cookies.Delete("Authorization");
|
||||
return Unauthorized(new { success = false, message = "Session expired" });
|
||||
}
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
message = "Authenticated",
|
||||
expires = session.Expirary,
|
||||
user = new
|
||||
{
|
||||
user.UID,
|
||||
user.UUID,
|
||||
user.Username,
|
||||
user.Email,
|
||||
user.DisplayName,
|
||||
user.Created,
|
||||
user.LastLogin,
|
||||
user.Type
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error checking authentication status");
|
||||
return StatusCode(500, "Internal server error");
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("logout")]
|
||||
public async Task<IActionResult> Logout()
|
||||
{
|
||||
try
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(requestDetails.Token))
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Not authenticated" });
|
||||
}
|
||||
var user = await _databaseService.UserFromToken(requestDetails.Token);
|
||||
if (user == null)
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Not authenticated" });
|
||||
}
|
||||
await _databaseService.DeleteSession(requestDetails.Token);
|
||||
Response.Cookies.Delete("Authorization");
|
||||
return Ok(new { success = true, message = "Logged out successfully" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during logout attempt");
|
||||
return StatusCode(500, "Internal server error");
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("delete")]
|
||||
public async Task<IActionResult> DeleteAccount()
|
||||
{
|
||||
try
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(requestDetails.Token))
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Not authenticated" });
|
||||
}
|
||||
var user = await _databaseService.UserFromToken(requestDetails.Token);
|
||||
if (user == null)
|
||||
{
|
||||
return Unauthorized(new { success = false, message = "Not authenticated" });
|
||||
}
|
||||
await _databaseService.DeleteUser(user);
|
||||
await _databaseService.DeleteSession(requestDetails.Token);
|
||||
Response.Cookies.Delete("Authorization");
|
||||
return Ok(new { success = true, message = "Account deleted successfully" });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error during account deletion attempt");
|
||||
return StatusCode(500, "Internal server error");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
public class AuthRequest
|
||||
{
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using SharpbinV2.Server.Services;
|
||||
using SharpbinV2.Server.Models;
|
||||
using System.Text;
|
||||
using IOFile = System.IO.File;
|
||||
using UAParser;
|
||||
|
||||
namespace SharpbinV2.Server.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/pastes")]
|
||||
public class PasteController : Controller
|
||||
{
|
||||
private readonly DatabaseService _databaseService;
|
||||
private readonly ILogger<PasteController> _logger;
|
||||
|
||||
public PasteController(DatabaseService databaseService, ILogger<PasteController> logger)
|
||||
{
|
||||
_databaseService = databaseService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpPost("create")]
|
||||
[EnableRateLimiting("uploads")]
|
||||
[Consumes("text/plain")]
|
||||
public async Task<IActionResult> CreatePaste(string title, string syntax, int visibility)
|
||||
{
|
||||
try
|
||||
{
|
||||
string content = await new StreamReader(HttpContext.Request.Body, Encoding.UTF8).ReadToEndAsync();
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
var queries = HttpContext.Request.Query;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(content))
|
||||
return BadRequest(new { success = false, message = "Content cannot be empty." });
|
||||
|
||||
if (content.Length > Program.MaxFileSize)
|
||||
return BadRequest(new { success = false, message = $"Content exceeds maximum size of {Program.MaxFileSize} bytes." });
|
||||
|
||||
title = !string.IsNullOrWhiteSpace(title) ? title : $"Untitled {await _databaseService.EnumeratePastes()}";
|
||||
syntax = syntax?.ToLower() ?? "none";
|
||||
visibility = visibility < 0 || visibility > 2 ? 0 : visibility;
|
||||
|
||||
if (title.Length > 500)
|
||||
return BadRequest(new { success = false, message = "Title cannot exceed 500 characters." });
|
||||
if (visibility < 0 || visibility > 2)
|
||||
return BadRequest(new { success = false, message = "Invalid visibility option. Must be 0 (public), 1 (unlisted), or 2 (private)." });
|
||||
if (!Program.ValidSyntaxLanguages.Contains(syntax.ToLower()))
|
||||
return BadRequest(new { success = false, message = "Invalid syntax language specified." });
|
||||
if (string.IsNullOrWhiteSpace(title))
|
||||
title = $"Untitled {await _databaseService.EnumeratePastes()}";
|
||||
|
||||
bool shouldCompress = await CompressionService.ShouldCompress(content);
|
||||
byte[] compressedContent = shouldCompress
|
||||
? await CompressionService.CompressString(content)
|
||||
: Encoding.UTF8.GetBytes(content);
|
||||
User? user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
|
||||
string pasteId = HelperService.GenerateRandomString(8);
|
||||
|
||||
Paste paste = new Paste
|
||||
{
|
||||
Created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||
Size = compressedContent.Length,
|
||||
TrueSize = content.Length,
|
||||
UUID = Guid.NewGuid().ToString(),
|
||||
ID = pasteId,
|
||||
AuthorUUID = user?.UUID ?? "0", // 0 means the user is anonymous
|
||||
FilePath = shouldCompress ? $"pastes/{pasteId}.txt.gz" : $"pastes/{pasteId}.txt",
|
||||
Visibility = visibility,
|
||||
Title = title,
|
||||
Edited = 0,
|
||||
Views = 0,
|
||||
Syntax = syntax.ToLower()
|
||||
};
|
||||
|
||||
await IOFile.WriteAllBytesAsync(paste.FilePath, compressedContent);
|
||||
bool success = await _databaseService.CreatePaste(paste, _logger);
|
||||
|
||||
if (!success)
|
||||
return StatusCode(500, new { success, message = "An error occurred while creating the paste." });
|
||||
|
||||
_logger.LogInformation($"Paste created successfully: {pasteId}");
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
paste = new
|
||||
{
|
||||
paste.ID,
|
||||
paste.UUID,
|
||||
paste.Title,
|
||||
paste.Syntax,
|
||||
paste.Visibility,
|
||||
paste.Created,
|
||||
paste.Size,
|
||||
paste.TrueSize,
|
||||
paste.AuthorUUID
|
||||
},
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error creating paste");
|
||||
return StatusCode(500, new { error = "An error occurred while creating the paste." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetPaste(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
return BadRequest(new { success = false, message = "Invalid paste ID." });
|
||||
Paste? paste = await _databaseService.GetPasteFromID(id);
|
||||
|
||||
if (paste == null || paste.FilePath == null || !IOFile.Exists(paste.FilePath))
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
|
||||
if (paste.FilePath.EndsWith(".gz"))
|
||||
Response.Headers.Append("Content-Encoding", "gzip");
|
||||
|
||||
Response.Headers.Append("Content-Type", "text/plain; charset=utf-8");
|
||||
Response.Headers.Append("Cache-Control", "public, max-age=3600");
|
||||
|
||||
return PhysicalFile(Path.GetFullPath(paste.FilePath), "text/plain");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving paste");
|
||||
return StatusCode(500, new { error = "An error occurred while retrieving the paste." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("{id}/info")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetPasteInfo(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
return BadRequest(new { success = false, message = "Invalid paste ID." });
|
||||
Paste? paste = await _databaseService.GetPasteFromID(id);
|
||||
if (paste == null || string.IsNullOrWhiteSpace(paste.UUID))
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
User? author = null;
|
||||
if (!string.IsNullOrWhiteSpace(paste.AuthorUUID))
|
||||
author = await _databaseService.UserFromUUID(paste.AuthorUUID ?? "");
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
paste = new
|
||||
{
|
||||
paste.ID,
|
||||
paste.UUID,
|
||||
paste.Title,
|
||||
paste.Syntax,
|
||||
paste.Views,
|
||||
paste.Visibility,
|
||||
paste.Created,
|
||||
paste.Size,
|
||||
paste.TrueSize,
|
||||
paste.AuthorUUID,
|
||||
username = author?.Username ?? "Anonymous",
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving paste info");
|
||||
return StatusCode(500, new { error = "An error occurred while retrieving the paste info." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("{id}/views")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetPasteViews(string id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(requestDetails.Token) || await _databaseService.GetSession(requestDetails.Token) == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid or missing authentication token." });
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
return BadRequest(new { success = false, message = "Invalid paste ID." });
|
||||
Paste? paste = await _databaseService.GetPasteFromID(id);
|
||||
User? user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
if (paste.AuthorUUID != user?.UUID)
|
||||
return Unauthorized(new { success = false, message = "You do not have permission to view this paste's views." });
|
||||
|
||||
List<View?>? views = await _databaseService.GetViewsFromPaste(paste.UUID ?? "", _logger);
|
||||
|
||||
if (views == null || views.Count == 0)
|
||||
return BadRequest(new { success = false, message = "No views found for this paste." });
|
||||
|
||||
var details = new List<object>();
|
||||
|
||||
foreach (var view in views)
|
||||
{
|
||||
if (view == null)
|
||||
continue;
|
||||
var uaParser = Parser.GetDefault();
|
||||
ClientInfo clientInfo = uaParser.Parse(view.UserAgent ?? "");
|
||||
details.Add(new
|
||||
{
|
||||
view.PasteUUID,
|
||||
view.Created,
|
||||
UserAgent = new
|
||||
{
|
||||
Browser = clientInfo.UA.Family,
|
||||
Platform = clientInfo.OS.Family,
|
||||
Device = clientInfo.Device.Family
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
pasteID = paste.ID,
|
||||
pasteUUID = paste.UUID,
|
||||
views = details
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving paste views");
|
||||
return StatusCode(500, new { error = "An error occurred while retrieving the paste views." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("archive")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetPastes(int page, int limit)
|
||||
{
|
||||
if (page < 1 || limit < 1 || limit > 25)
|
||||
return BadRequest(new { success = false, message = "Invalid page or limit parameters." });
|
||||
if (page == 1)
|
||||
page = 0;
|
||||
|
||||
try
|
||||
{
|
||||
int pages = await _databaseService.EnumeratePastes() / limit;
|
||||
if (page > pages)
|
||||
return BadRequest(new { success = false, message = "Page number exceeds available pages." });
|
||||
|
||||
List<Paste?>? pastes = await _databaseService.GetPastes(limit, page, _logger);
|
||||
|
||||
if (pastes == null || pastes.Count == 0)
|
||||
return NotFound(new { success = false, message = "No pastes found." });
|
||||
|
||||
var pasteList = new List<object>();
|
||||
foreach (var paste in pastes)
|
||||
{
|
||||
if (paste == null)
|
||||
continue;
|
||||
pasteList.Add(new
|
||||
{
|
||||
paste.ID,
|
||||
paste.UUID,
|
||||
paste.Title,
|
||||
paste.Syntax,
|
||||
paste.Visibility,
|
||||
paste.Created,
|
||||
paste.Size,
|
||||
paste.TrueSize,
|
||||
paste.AuthorUUID
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
pages,
|
||||
pastes = pasteList
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving pastes archive");
|
||||
return StatusCode(500, new { error = "An error occurred while retrieving the pastes archive." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("my")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetMyPastes(int page, int limit)
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(requestDetails.Token) || await _databaseService.GetSession(requestDetails.Token) == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid or missing authentication token." });
|
||||
User? user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
|
||||
if (user == null)
|
||||
return Unauthorized(new { success = false, message = "User not found." });
|
||||
if (page < 1 || limit < 1 || limit > 25)
|
||||
return BadRequest(new { success = false, message = "Invalid page or limit parameters." });
|
||||
if (page == 1)
|
||||
page = 0;
|
||||
|
||||
try
|
||||
{
|
||||
int pages = await _databaseService.EnumerateUserPastes(user) / limit;
|
||||
if (page > pages)
|
||||
return BadRequest(new { success = false, message = "Page number exceeds available pages." });
|
||||
List<Paste?>? pastes = await _databaseService.GetPastesFromUser(user, limit, page, _logger, true);
|
||||
if (pastes == null || pastes.Count == 0)
|
||||
return NotFound(new { success = false, message = "No pastes found." });
|
||||
var pasteList = new List<object>();
|
||||
foreach (var paste in pastes)
|
||||
{
|
||||
if (paste == null)
|
||||
continue;
|
||||
pasteList.Add(new
|
||||
{
|
||||
paste.ID,
|
||||
paste.UUID,
|
||||
paste.Title,
|
||||
paste.Syntax,
|
||||
paste.Visibility,
|
||||
paste.Created,
|
||||
paste.Size,
|
||||
paste.TrueSize,
|
||||
paste.AuthorUUID
|
||||
});
|
||||
}
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
pages,
|
||||
pastes = pasteList
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving user's pastes");
|
||||
return StatusCode(500, new { error = "An error occurred while retrieving the user's pastes." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> DeletePaste(string id)
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(requestDetails.Token) || await _databaseService.GetSession(requestDetails.Token) == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid or missing authentication token." });
|
||||
|
||||
User? user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
|
||||
if (user == null || user.UUID == "0")
|
||||
return Unauthorized(new { success = false, message = "User not found." });
|
||||
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
return BadRequest(new { success = false, message = "Invalid paste ID." });
|
||||
try
|
||||
{
|
||||
Paste? paste = await _databaseService.GetPasteFromID(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
|
||||
if (paste.AuthorUUID != user.UUID && user.Type != 255)
|
||||
return Unauthorized(new { success = false, message = "You do not have permission to delete this paste." });
|
||||
|
||||
bool success = await _databaseService.DeletePaste(paste, _logger);
|
||||
if (!success)
|
||||
return StatusCode(500, new { success, message = "An error occurred while deleting the paste." });
|
||||
|
||||
if (IOFile.Exists(paste.FilePath))
|
||||
IOFile.Delete(paste.FilePath);
|
||||
|
||||
_logger.LogInformation($"Paste deleted successfully: {id}");
|
||||
return Ok(new { success = true, message = "Paste deleted successfully." });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error deleting paste");
|
||||
return StatusCode(500, new { error = "An error occurred while deleting the paste." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("{id}/change-id")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> ChangePasteID(string id, string newId)
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(requestDetails.Token) || await _databaseService.GetSession(requestDetails.Token) == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid or missing authentication token." });
|
||||
User? user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
|
||||
if (user == null || user.UUID == "0")
|
||||
return Unauthorized(new { success = false, message = "User not found." });
|
||||
if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(newId))
|
||||
return BadRequest(new { success = false, message = "Invalid paste ID." });
|
||||
if (user.Type != 255)
|
||||
return Unauthorized(new { success = false, message = "You do not have permission to change paste ID." });
|
||||
|
||||
try
|
||||
{
|
||||
var paste = await _databaseService.GetPasteFromID(id);
|
||||
if (paste == null)
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
|
||||
paste.ID = newId;
|
||||
|
||||
var newPaste = await _databaseService.UpdatePaste(paste, _logger);
|
||||
if (newPaste == null)
|
||||
return StatusCode(500, new { success = false, message = "An error occurred while changing the paste ID." });
|
||||
|
||||
if (IOFile.Exists(paste.FilePath) && paste.ID != null)
|
||||
{
|
||||
string newFilePath = paste.FilePath.Replace(paste.ID, newId);
|
||||
IOFile.Move(paste.FilePath, newFilePath);
|
||||
paste.FilePath = newFilePath;
|
||||
}
|
||||
else
|
||||
{
|
||||
return StatusCode(500, new { success = false, message = "Paste file not found or invalid." });
|
||||
}
|
||||
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
message = "Paste ID changed successfully.",
|
||||
paste = new
|
||||
{
|
||||
newPaste.ID,
|
||||
newPaste.UUID,
|
||||
newPaste.Title,
|
||||
newPaste.Syntax,
|
||||
newPaste.Visibility,
|
||||
newPaste.Created,
|
||||
newPaste.Size,
|
||||
newPaste.TrueSize,
|
||||
newPaste.AuthorUUID
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error changing paste ID");
|
||||
return StatusCode(500, new { error = "An error occurred while changing the paste ID." });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPatch("{id}")]
|
||||
[EnableRateLimiting("general")]
|
||||
[Consumes("text/plain")]
|
||||
public async Task<IActionResult> EditPaste(string id, string title)
|
||||
{
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
if (string.IsNullOrWhiteSpace(requestDetails.Token) || await _databaseService.GetSession(requestDetails.Token) == null)
|
||||
return Unauthorized(new { success = false, message = "Invalid or missing authentication token." });
|
||||
|
||||
User? user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
|
||||
if (user == null || user.UUID == "0")
|
||||
return Unauthorized(new { success = false, message = "User not found." });
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
return BadRequest(new { success = false, message = "Invalid paste ID." });
|
||||
|
||||
var paste = await _databaseService.GetPasteFromID(id);
|
||||
if (paste == null || string.IsNullOrWhiteSpace(paste.FilePath))
|
||||
return NotFound(new { success = false, message = "Paste not found." });
|
||||
|
||||
if (paste.AuthorUUID != user.UUID && user.Type != 255)
|
||||
return Unauthorized(new { success = false, message = "You do not have permission to edit this paste." });
|
||||
|
||||
if (title.Length > 500)
|
||||
return BadRequest(new { success = false, message = "Title cannot exceed 500 characters." });
|
||||
|
||||
try
|
||||
{
|
||||
string content = await new StreamReader(HttpContext.Request.Body, Encoding.UTF8).ReadToEndAsync();
|
||||
if (string.IsNullOrWhiteSpace(content))
|
||||
return BadRequest(new { success = false, message = "Content cannot be empty." });
|
||||
|
||||
if (content.Length > Program.MaxFileSize)
|
||||
return BadRequest(new { success = false, message = $"Content exceeds maximum size of {Program.MaxFileSize} bytes." });
|
||||
|
||||
bool shouldCompress = await CompressionService.ShouldCompress(content);
|
||||
byte[] compressedContent = shouldCompress
|
||||
? await CompressionService.CompressString(content)
|
||||
: Encoding.UTF8.GetBytes(content);
|
||||
|
||||
paste.Edited = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
paste.TrueSize = content.Length;
|
||||
paste.Size = compressedContent.Length;
|
||||
paste.FilePath = shouldCompress ? paste.FilePath.Split('.').First() + ".txt.gz" : paste.FilePath.Split('.').First() + ".txt";
|
||||
paste.Title = !string.IsNullOrWhiteSpace(title) ? title : paste.Title;
|
||||
|
||||
await IOFile.WriteAllBytesAsync(paste.FilePath, compressedContent);
|
||||
|
||||
Console.WriteLine($"Wrote {content} to {paste.FilePath}");
|
||||
|
||||
var updatedPaste = await _databaseService.UpdatePaste(paste, _logger);
|
||||
if (updatedPaste == null)
|
||||
return StatusCode(500, new { success = false, message = "An error occurred while editing the paste." });
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
paste = new
|
||||
{
|
||||
updatedPaste.ID,
|
||||
updatedPaste.UUID,
|
||||
updatedPaste.Title,
|
||||
updatedPaste.Syntax,
|
||||
updatedPaste.Visibility,
|
||||
updatedPaste.Created,
|
||||
updatedPaste.Size,
|
||||
updatedPaste.TrueSize,
|
||||
updatedPaste.AuthorUUID,
|
||||
updatedPaste.Edited
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error editing paste");
|
||||
return StatusCode(500, new { error = "An error occurred while editing the paste." });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using SharpbinV2.Server.Services;
|
||||
|
||||
namespace SharpbinV2.Server.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/site")]
|
||||
public class SiteController : Controller
|
||||
{
|
||||
private readonly ILogger<SiteController> _logger;
|
||||
private readonly DatabaseService _databaseService;
|
||||
public SiteController(ILogger<SiteController> logger, DatabaseService databaseService)
|
||||
{
|
||||
_logger = logger;
|
||||
_databaseService = databaseService;
|
||||
}
|
||||
|
||||
[HttpGet("info")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult GetInfo()
|
||||
{
|
||||
var info = new
|
||||
{
|
||||
Program.MaxFileSize,
|
||||
};
|
||||
return Ok(new { success = true, info });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using SharpbinV2.Server.Services;
|
||||
using SharpbinV2.Server.Models;
|
||||
|
||||
namespace SharpbinV2.Server.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("")]
|
||||
public class StaticController : Controller
|
||||
{
|
||||
private readonly ILogger<StaticController> _logger;
|
||||
private readonly DatabaseService _databaseService;
|
||||
private readonly IWebHostEnvironment _environment;
|
||||
|
||||
public StaticController(ILogger<StaticController> logger, DatabaseService databaseService, IWebHostEnvironment environment)
|
||||
{
|
||||
_logger = logger;
|
||||
_databaseService = databaseService;
|
||||
_environment = environment;
|
||||
}
|
||||
|
||||
[HttpGet("")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Index()
|
||||
{
|
||||
Response.StatusCode = 200;
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "index.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("{pasteid}")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetPaste(string pasteid)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(pasteid))
|
||||
{
|
||||
return Redirect("/error?error=400&message=Invalid paste id.");
|
||||
}
|
||||
|
||||
var filePath = Path.Combine(_environment.WebRootPath, pasteid);
|
||||
if (System.IO.File.Exists(filePath))
|
||||
{
|
||||
var contentType = GetContentType(Path.GetExtension(filePath));
|
||||
return PhysicalFile(filePath, contentType);
|
||||
}
|
||||
|
||||
var paste = await _databaseService.GetPasteFromID(pasteid);
|
||||
if (paste == null)
|
||||
{
|
||||
return Redirect("/error?error=400&message=Paste not found.");
|
||||
}
|
||||
|
||||
var requestDetails = HelperService.GetRequestDetails(HttpContext);
|
||||
var user = await _databaseService.UserFromToken(requestDetails.Token ?? "");
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
if (user.UUID != paste.AuthorUUID)
|
||||
{
|
||||
if (!await _databaseService.HasAlreadyViewedFromUserDetails(user))
|
||||
{
|
||||
await _databaseService.AddViewToPaste(user, paste, requestDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!await _databaseService.AlreadyViewed(requestDetails))
|
||||
{
|
||||
await _databaseService.AddViewToPaste(new User { UUID = "0" }, paste, requestDetails);
|
||||
}
|
||||
}
|
||||
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "paste.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("error")]
|
||||
public IActionResult Error()
|
||||
{
|
||||
Response.StatusCode = 400;
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "error.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("error.html")]
|
||||
public IActionResult ErrorHtml()
|
||||
{
|
||||
return Redirect("/error");
|
||||
}
|
||||
|
||||
[HttpGet("raw/{pasteid}")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> GetRawPaste(string pasteid)
|
||||
{
|
||||
if (string.IsNullOrEmpty(pasteid))
|
||||
{
|
||||
return Redirect("/error?error=400&message=Invalid paste id.");
|
||||
}
|
||||
|
||||
var paste = await _databaseService.GetPasteFromID(pasteid);
|
||||
if (paste == null || paste.FilePath == null)
|
||||
{
|
||||
return Redirect("/error?error=400&message=Paste not found.");
|
||||
}
|
||||
|
||||
Response.Headers.Append("Content-Type", "text/plain");
|
||||
if (paste.FilePath.EndsWith(".gz"))
|
||||
{
|
||||
Response.Headers.Append("Content-Encoding", "gzip");
|
||||
}
|
||||
|
||||
return PhysicalFile(paste.FilePath, "text/plain");
|
||||
}
|
||||
|
||||
[HttpGet("paste.html")]
|
||||
public IActionResult PasteHtml()
|
||||
{
|
||||
return Redirect("/");
|
||||
}
|
||||
|
||||
[HttpGet("archive")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Archive()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "archive.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("dash")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Dashboard()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "dash.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("dash.html")]
|
||||
public IActionResult DashboardHtml()
|
||||
{
|
||||
return Redirect("/dash");
|
||||
}
|
||||
|
||||
[HttpGet("login")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Login()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "login.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("register")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult Register()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "register.html"), "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("u/{username}")]
|
||||
[EnableRateLimiting("general")]
|
||||
public async Task<IActionResult> UserProfile(string username)
|
||||
{
|
||||
if (string.IsNullOrEmpty(username))
|
||||
{
|
||||
return Redirect("/error?error=400&message=Invalid username.");
|
||||
}
|
||||
|
||||
string html = await System.IO.File.ReadAllTextAsync(Path.Combine(_environment.WebRootPath, "user.html"));
|
||||
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
Response.Headers.Append("Pragma", "no-cache");
|
||||
Response.Headers.Append("Expires", "0");
|
||||
|
||||
return Content(html, "text/html");
|
||||
}
|
||||
|
||||
[HttpGet("reset-password")]
|
||||
[EnableRateLimiting("general")]
|
||||
public IActionResult ResetPassword()
|
||||
{
|
||||
Response.Headers.Append("Content-Type", "text/html");
|
||||
return PhysicalFile(Path.Combine(_environment.WebRootPath, "reset-password.html"), "text/html");
|
||||
}
|
||||
|
||||
private static string GetContentType(string extension)
|
||||
{
|
||||
return extension.ToLowerInvariant() switch
|
||||
{
|
||||
".html" => "text/html",
|
||||
".css" => "text/css",
|
||||
".js" => "text/javascript",
|
||||
".json" => "application/json",
|
||||
".png" => "image/png",
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".ico" => "image/x-icon",
|
||||
_ => "application/octet-stream"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SharpbinV2.Server.Services;
|
||||
|
||||
namespace SharpbinV2.Server.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/users")]
|
||||
public class UserController : Controller
|
||||
{
|
||||
private readonly ILogger<UserController> _logger;
|
||||
private readonly DatabaseService _databaseService;
|
||||
public UserController(ILogger<UserController> logger, DatabaseService databaseService)
|
||||
{
|
||||
_logger = logger;
|
||||
_databaseService = databaseService;
|
||||
}
|
||||
|
||||
[HttpGet("uuid/{uuid}")]
|
||||
public async Task<IActionResult> GetUserByUuid(string uuid)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(uuid))
|
||||
return BadRequest(new { success = false, message = "UUID cannot be null or empty" });
|
||||
|
||||
var user = await _databaseService.UserFromUUID(uuid);
|
||||
if (user == null)
|
||||
{
|
||||
_logger.LogWarning("User not found for UUID: {Uuid}", uuid);
|
||||
return NotFound(new { success = false, message = "User not found" });
|
||||
}
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
user = new
|
||||
{
|
||||
user.UID,
|
||||
user.UUID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
user.Created,
|
||||
user.LastLogin,
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving user by UUID: {Uuid}", uuid);
|
||||
return StatusCode(500, new { success= false, message = "Internal server error" });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("uid/{uid}")]
|
||||
public async Task<IActionResult> GetUserByUID(int uid)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (uid <= 0)
|
||||
return BadRequest(new { success = false, message = "UID must be a positive integer" });
|
||||
var user = await _databaseService.UserFromUID(uid);
|
||||
if (user == null)
|
||||
{
|
||||
_logger.LogWarning("User not found for UID: {Uid}", uid);
|
||||
return NotFound(new { success = false, message = "User not found" });
|
||||
}
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
user = new
|
||||
{
|
||||
user.UID,
|
||||
user.UUID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
user.Created,
|
||||
user.LastLogin,
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving user by UID: {Uid}", uid);
|
||||
return StatusCode(500, new { success= false, message = "Internal server error" });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("username/{username}")]
|
||||
public async Task<IActionResult> GetUserByUsername(string username)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(username))
|
||||
return BadRequest(new { success = false, message = "Username cannot be null or empty" });
|
||||
var user = await _databaseService.UserFromUsername(username);
|
||||
if (user == null)
|
||||
{
|
||||
_logger.LogWarning("User not found for username: {Username}", username);
|
||||
return NotFound(new { success = false, message = "User not found" });
|
||||
}
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
user = new
|
||||
{
|
||||
user.UID,
|
||||
user.UUID,
|
||||
user.Username,
|
||||
user.DisplayName,
|
||||
user.Created,
|
||||
user.LastLogin,
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving user by username: {Username}", username);
|
||||
return StatusCode(500, new { success= false, message = "Internal server error" });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("{uuid}/pastes")]
|
||||
public async Task<IActionResult> GetUserPastes(string uuid, int limit, int page)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(uuid))
|
||||
return BadRequest(new { success = false, message = "UUID cannot be null or empty" });
|
||||
if (limit <= 0 || page < 0)
|
||||
return BadRequest(new { success = false, message = "Invalid pagination parameters" });
|
||||
if (page == 1) page = 0;
|
||||
|
||||
var user = await _databaseService.UserFromUUID(uuid);
|
||||
if (user == null)
|
||||
{
|
||||
_logger.LogWarning("User not found for UUID: {Uuid}", uuid);
|
||||
return NotFound(new { success = false, message = "User not found" });
|
||||
}
|
||||
|
||||
int pages = await _databaseService.EnumerateUserPastes(user) / limit;
|
||||
if (page > pages)
|
||||
return BadRequest(new { success = false, message = "Page number exceeds available pages" });
|
||||
|
||||
var pastes = await _databaseService.GetPastesFromUser(user, limit, page, _logger);
|
||||
if (pastes == null || pastes.Count == 0)
|
||||
return Ok(new { success = false, message = "No pastes found for this user."});
|
||||
|
||||
var pasteList = new List<object>();
|
||||
foreach (var paste in pastes)
|
||||
{
|
||||
if (paste == null)
|
||||
continue;
|
||||
pasteList.Add(new
|
||||
{
|
||||
paste.ID,
|
||||
paste.UUID,
|
||||
paste.Title,
|
||||
paste.Syntax,
|
||||
paste.Visibility,
|
||||
paste.Created,
|
||||
paste.Size,
|
||||
paste.TrueSize,
|
||||
paste.AuthorUUID
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
success = true,
|
||||
pastes = pasteList,
|
||||
pages
|
||||
});
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error retrieving pastes for user UUID: {Uuid}", uuid);
|
||||
return StatusCode(500, new { success= false, message = "Internal server error" });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
|
||||
USER app
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
EXPOSE 8081
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
COPY ["SharpbinV2.Server/SharpbinV2.Server.csproj", "SharpbinV2.Server/"]
|
||||
RUN dotnet restore "./SharpbinV2.Server/SharpbinV2.Server.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/SharpbinV2.Server"
|
||||
RUN dotnet build "./SharpbinV2.Server.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./SharpbinV2.Server.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "SharpbinV2.Server.dll"]
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace SharpbinV2.Server.Models
|
||||
{
|
||||
public class PasswordReset
|
||||
{
|
||||
public string? UID { get; set; }
|
||||
public string? UUID { get; set; }
|
||||
public string? USERUUID { get; set; }
|
||||
public string? URL { get; set; }
|
||||
public string? Token { get; set; }
|
||||
public long? Created { get; set; }
|
||||
public long? Expirary { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace SharpbinV2.Server.Models
|
||||
{
|
||||
public class Paste
|
||||
{
|
||||
public int UID { get; set; }
|
||||
public string? UUID { get; set; }
|
||||
public string? ID { get; set; }
|
||||
public int? Visibility { get; set; }
|
||||
public string? Title { get; set; }
|
||||
public string? AuthorUUID { get; set; }
|
||||
public string? FilePath { get; set; }
|
||||
public long? Created { get; set; }
|
||||
public long? Edited { get; set; }
|
||||
public int? Size { get; set; }
|
||||
public int? TrueSize { get; set; }
|
||||
public int? Views { get; set; }
|
||||
public string? Syntax { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace SharpbinV2.Server.Models
|
||||
{
|
||||
public class RequestDetails
|
||||
{
|
||||
public string? Ip { get; set; }
|
||||
public string? UserAgent { get; set; }
|
||||
public string? Token { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace SharpbinV2.Server.Models
|
||||
{
|
||||
public class Session
|
||||
{
|
||||
public string? UUID { get; set; }
|
||||
public string? UserUUID { get; set; }
|
||||
public string? Token { get; set; }
|
||||
public long? Created { get; set; }
|
||||
public long? Expirary { get; set; }
|
||||
public string? Ip { get; set; }
|
||||
public string? UserAgent { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace SharpbinV2.Server.Models
|
||||
{
|
||||
public class User
|
||||
{
|
||||
public int? UID { get; set; }
|
||||
public string? UUID { get; set; }
|
||||
public int? Type { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string? Username { get; set; }
|
||||
public string? DisplayName { get; set; }
|
||||
public string? Password { get; set; }
|
||||
public long? Created { get; set; }
|
||||
public long? LastLogin { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace SharpbinV2.Server.Models
|
||||
{
|
||||
public class View
|
||||
{
|
||||
public string? UUID { get; set; }
|
||||
public string? PasteUUID { get; set; }
|
||||
public string? UserUUID { get; set; }
|
||||
public string? Fingerprint { get; set; }
|
||||
public string? UserAgent { get; set; }
|
||||
public long? Created { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using SharpbinV2.Server.Services;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace SharpbinV2.Server
|
||||
{
|
||||
class Program
|
||||
{
|
||||
public static string MainDatabaseConnection = "Data Source=data.db";
|
||||
public static long MaxFileSize = 1_048_576; // 1MB
|
||||
public static string[] ValidSyntaxLanguages =
|
||||
[
|
||||
"none",
|
||||
"autoHotkey",
|
||||
"autoIt",
|
||||
"bash",
|
||||
"c",
|
||||
"cpp",
|
||||
"csharp",
|
||||
"css",
|
||||
"dart",
|
||||
"html",
|
||||
"java",
|
||||
"javascript",
|
||||
"json",
|
||||
"lua",
|
||||
"markdown",
|
||||
"php",
|
||||
"python",
|
||||
"ruby",
|
||||
"rust",
|
||||
"sql",
|
||||
"swift",
|
||||
"typescript",
|
||||
"toml",
|
||||
"xml"
|
||||
];
|
||||
public static string SHA256Salt = RandomNumberGenerator.GetHexString(32);
|
||||
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
await Initialize();
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
builder.Configuration.AddEnvironmentVariables();
|
||||
|
||||
if (Environment.GetEnvironmentVariable("HTTPS") == "true")
|
||||
{
|
||||
builder.WebHost.UseUrls($"https://*:{Environment.GetEnvironmentVariable("ASPNETCORE_HTTPS_PORTS") ?? "5820"}");
|
||||
}
|
||||
else
|
||||
{
|
||||
builder.WebHost.UseUrls($"http://*:{Environment.GetEnvironmentVariable("ASPNETCORE_HTTP_PORTS") ?? "5810"}");
|
||||
}
|
||||
|
||||
MaxFileSize = Environment.GetEnvironmentVariable("MAX_FILE_SIZE") != null ? Convert.ToInt64(Environment.GetEnvironmentVariable("MAX_FILE_SIZE")) : MaxFileSize;
|
||||
|
||||
if (Environment.GetEnvironmentVariable("SHA256_SALT") != null)
|
||||
{
|
||||
SHA256Salt = Environment.GetEnvironmentVariable("SHA256_SALT") ?? SHA256Salt;
|
||||
}
|
||||
else
|
||||
{
|
||||
SHA256Salt = RandomNumberGenerator.GetHexString(32);
|
||||
Environment.SetEnvironmentVariable("SHA256_SALT", SHA256Salt);
|
||||
|
||||
var dotenv = Path.Combine(Directory.GetCurrentDirectory(), ".env");
|
||||
if (File.Exists(dotenv))
|
||||
{
|
||||
var lines = File.ReadAllLines(dotenv).ToList();
|
||||
var saltLine = $"SHA256_SALT={SHA256Salt}";
|
||||
if (lines.Any(line => line.StartsWith("SHA256_SALT=")))
|
||||
{
|
||||
lines[lines.FindIndex(line => line.StartsWith("SHA256_SALT="))] = saltLine;
|
||||
}
|
||||
else
|
||||
{
|
||||
lines.Add(saltLine);
|
||||
}
|
||||
File.WriteAllLines(dotenv, lines);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
builder.WebHost.ConfigureKestrel(options =>
|
||||
{
|
||||
options.Limits.MaxRequestBodySize = MaxFileSize;
|
||||
});
|
||||
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
options.AddTokenBucketLimiter("uploads", opt =>
|
||||
{
|
||||
opt.TokenLimit = 10;
|
||||
opt.ReplenishmentPeriod = TimeSpan.FromMinutes(1);
|
||||
opt.TokensPerPeriod = 2;
|
||||
opt.AutoReplenishment = true;
|
||||
});
|
||||
|
||||
options.AddTokenBucketLimiter("auth", opt =>
|
||||
{
|
||||
opt.TokenLimit = 15;
|
||||
opt.ReplenishmentPeriod = TimeSpan.FromMinutes(5);
|
||||
opt.TokensPerPeriod = 10;
|
||||
opt.AutoReplenishment = true;
|
||||
});
|
||||
|
||||
options.AddFixedWindowLimiter("general", opt =>
|
||||
{
|
||||
opt.PermitLimit = 200;
|
||||
opt.Window = TimeSpan.FromMinutes(1);
|
||||
});
|
||||
|
||||
options.OnRejected = async (context, token) =>
|
||||
{
|
||||
context.HttpContext.Response.StatusCode = 429;
|
||||
await context.HttpContext.Response.WriteAsJsonAsync(new
|
||||
{
|
||||
success = false,
|
||||
message = "Rate limit exceeded. Please try again later."
|
||||
});
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
// Add services to the container.
|
||||
builder.Services.AddCors();
|
||||
builder.Services.AddResponseCaching();
|
||||
builder.Services.AddResponseCompression();
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddScoped<DatabaseService>();
|
||||
//builder.Services.AddEndpointsApiExplorer();
|
||||
//builder.Services.AddSwaggerGen();
|
||||
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseExceptionHandler("/Error");
|
||||
app.UseHsts();
|
||||
|
||||
}
|
||||
|
||||
//if (app.Environment.IsDevelopment())
|
||||
//{
|
||||
// app.UseSwagger();
|
||||
// app.UseSwaggerUI();
|
||||
//}
|
||||
|
||||
|
||||
//app.UseHttpsRedirection();
|
||||
app.UseRouting();
|
||||
app.UseStaticFiles();
|
||||
app.UseRateLimiter();
|
||||
|
||||
app.UseCors(builder =>
|
||||
{
|
||||
builder.AllowAnyOrigin();
|
||||
builder.AllowAnyMethod();
|
||||
builder.AllowAnyHeader();
|
||||
});
|
||||
app.UseResponseCaching();
|
||||
app.UseResponseCompression();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
await app.RunAsync();
|
||||
|
||||
}
|
||||
|
||||
static async Task Initialize()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var connection = new SqliteConnection(MainDatabaseConnection))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = @"CREATE TABLE IF NOT EXISTS users (
|
||||
UID INTEGER UNIQUE,
|
||||
UUID TEXT NOT NULL UNIQUE,
|
||||
Type INTEGER NOT NULL DEFAULT 0,
|
||||
Email TEXT UNIQUE,
|
||||
Username TEXT NOT NULL UNIQUE,
|
||||
DisplayName TEXT,
|
||||
Password TEXT NOT NULL,
|
||||
Created INTEGER NOT NULL,
|
||||
LastLogin INTEGER,
|
||||
PRIMARY KEY(UID AUTOINCREMENT)
|
||||
);";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = @"CREATE TABLE IF NOT EXISTS pastes (
|
||||
UID INTEGER NOT NULL UNIQUE,
|
||||
UUID TEXT NOT NULL UNIQUE,
|
||||
ID TEXT NOT NULL UNIQUE,
|
||||
Visibility INTEGER,
|
||||
Title TEXT,
|
||||
AuthorUUID TEXT NOT NULL,
|
||||
FilePath TEXT NOT NULL UNIQUE,
|
||||
Created INTEGER NOT NULL,
|
||||
Edited INTEGER,
|
||||
Size INTEGER NOT NULL,
|
||||
TrueSize INTEGER NOT NULL,
|
||||
Views INTEGER NOT NULL DEFAULT 0,
|
||||
Syntax TEXT,
|
||||
PRIMARY KEY(UID AUTOINCREMENT)
|
||||
);";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = @"CREATE TABLE IF NOT EXISTS sessions (
|
||||
UUID TEXT NOT NULL UNIQUE,
|
||||
UserUUID INTEGER NOT NULL,
|
||||
Token INTEGER NOT NULL UNIQUE,
|
||||
Created INTEGER NOT NULL,
|
||||
Expirary INTEGER NOT NULL,
|
||||
Ip TEXT NOT NULL,
|
||||
UserAgent TEXT NOT NULL
|
||||
);";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = @"CREATE TABLE IF NOT EXISTS views (
|
||||
UserUUID TEXT NOT NULL,
|
||||
PasteUUID INTEGER NOT NULL,
|
||||
Fingerprint TEXT NOT NULL,
|
||||
UserAgent TEXT,
|
||||
Created INTEGER NOT NULL
|
||||
);";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = @"CREATE TABLE IF NOT EXISTS punishments (
|
||||
UID INTEGER NOT NULL UNIQUE,
|
||||
UUID TEXT NOT NULL UNIQUE,
|
||||
Type INTEGER NOT NULL DEFAULT 0,
|
||||
Reason TEXT,
|
||||
Created INTEGER NOT NULL,
|
||||
Expirary INTEGER NOT NULL,
|
||||
PRIMARY KEY(UID AUTOINCREMENT)
|
||||
);";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = @"CREATE TABLE IF NOT EXISTS passwordresets (
|
||||
UID INTEGER NOT NULL UNIQUE,
|
||||
UUID TEXT NOT NULL UNIQUE,
|
||||
USERUUID TEXT NOT NULL UNIQUE,
|
||||
URL TEXT NOT NULL UNIQUE,
|
||||
Token TEXT NOT NULL UNIQUE,
|
||||
Created INTEGER NOT NULL,
|
||||
Expirary INTEGER NOT NULL,
|
||||
PRIMARY KEY(UID AUTOINCREMENT)
|
||||
);";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
await connection.CloseAsync();
|
||||
}
|
||||
}
|
||||
if (!Directory.Exists("pastes"))
|
||||
Directory.CreateDirectory("pastes");
|
||||
if (!Directory.Exists("logs"))
|
||||
Directory.CreateDirectory("logs");
|
||||
var root = Directory.GetCurrentDirectory();
|
||||
var dotenv = Path.Combine(root, ".env");
|
||||
DotEnv.Load(dotenv);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine(ex.Message);
|
||||
Environment.Exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// https://dusted.codes/dotenv-in-dotnet
|
||||
/// </summary>
|
||||
public static class DotEnv
|
||||
{
|
||||
public static void Load(string filePath)
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
return;
|
||||
|
||||
foreach (var line in File.ReadAllLines(filePath))
|
||||
{
|
||||
var parts = line.Split(
|
||||
'=',
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
if (parts.Length != 2)
|
||||
continue;
|
||||
|
||||
Environment.SetEnvironmentVariable(parts[0], parts[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-3
@@ -2,22 +2,32 @@
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "http://localhost:5050"
|
||||
"applicationUrl": "http://localhost:5810"
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "https://localhost:7149;http://localhost:5050"
|
||||
"applicationUrl": "https://localhost:5820;http://localhost:5810"
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_HTTPS_PORTS": "8081",
|
||||
@@ -27,5 +37,13 @@
|
||||
"useSSL": true
|
||||
}
|
||||
},
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json"
|
||||
"$schema": "http://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:1241",
|
||||
"sslPort": 44317
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
|
||||
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
|
||||
namespace SharpbinV2.Server.Services
|
||||
{
|
||||
public class CompressionService
|
||||
{
|
||||
public static async Task<byte[]> CompressString(string text)
|
||||
{
|
||||
byte[] compressedBytes;
|
||||
using (var ms = new MemoryStream())
|
||||
{
|
||||
using (var cs = new GZipStream(ms, CompressionMode.Compress))
|
||||
{
|
||||
byte[] inputBytes = Encoding.UTF8.GetBytes(text);
|
||||
await cs.WriteAsync(inputBytes, 0, inputBytes.Length);
|
||||
}
|
||||
compressedBytes = ms.ToArray();
|
||||
}
|
||||
return compressedBytes;
|
||||
}
|
||||
public static async Task<string> DecompressByteArrayToString(byte[] compressedBytes)
|
||||
{
|
||||
string decompressedText;
|
||||
using (var ms = new MemoryStream(compressedBytes))
|
||||
{
|
||||
using (var cs = new GZipStream(ms, CompressionMode.Decompress))
|
||||
{
|
||||
using (var sr = new StreamReader(cs))
|
||||
{
|
||||
decompressedText = await sr.ReadToEndAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
return decompressedText;
|
||||
}
|
||||
public static async Task<byte[]> DecompressByteArray(byte[] compressedBytes)
|
||||
{
|
||||
byte[] decompressedBytes;
|
||||
using (var ms = new MemoryStream(compressedBytes))
|
||||
{
|
||||
using (var cs = new GZipStream(ms, CompressionMode.Decompress))
|
||||
{
|
||||
using (var msDecompressed = new MemoryStream())
|
||||
{
|
||||
await cs.CopyToAsync(msDecompressed);
|
||||
decompressedBytes = msDecompressed.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
return decompressedBytes;
|
||||
}
|
||||
public static async Task<bool> ShouldCompress(string text, int sizeThreshold = 512, double ratioThreshold = 0.8)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
return false;
|
||||
|
||||
byte[] inputBytes = Encoding.UTF8.GetBytes(text);
|
||||
if (inputBytes.Length < sizeThreshold)
|
||||
return false;
|
||||
|
||||
byte[] compressedBytes = await CompressString(text).ConfigureAwait(false);
|
||||
double compressionRatio = (double)compressedBytes.Length / inputBytes.Length;
|
||||
|
||||
return compressionRatio < ratioThreshold;
|
||||
}
|
||||
public static bool IsCompressed(byte[] data)
|
||||
{
|
||||
return data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,775 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using SharpbinV2.Server.Models;
|
||||
using Bcrypt = BCrypt.Net.BCrypt;
|
||||
|
||||
namespace SharpbinV2.Server.Services
|
||||
{
|
||||
public class DatabaseService
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
public DatabaseService(IConfiguration configuration)
|
||||
{
|
||||
_connectionString = configuration.GetConnectionString("DefaultConnection") ?? "Data Source=data.db";
|
||||
}
|
||||
|
||||
public async Task<User?> UserFromUsername(string username)
|
||||
{
|
||||
if (string.IsNullOrEmpty(username))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM users WHERE Username = @Username;";
|
||||
command.Parameters.AddWithValue("@Username", username);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return new User
|
||||
{
|
||||
UID = reader.GetInt32(0),
|
||||
UUID = reader.GetString(1),
|
||||
Type = reader.GetInt32(2),
|
||||
Email = reader.IsDBNull(3) ? null : reader.GetString(3),
|
||||
Username = reader.GetString(4),
|
||||
DisplayName = reader.IsDBNull(5) ? null : reader.GetString(5),
|
||||
Password = reader.GetString(6),
|
||||
Created = reader.GetInt64(7),
|
||||
LastLogin = reader.GetInt64(8)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<User?> UserFromUUID(string uuid)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uuid))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM users WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@UUID", uuid);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return new User
|
||||
{
|
||||
UID = reader.GetInt32(0),
|
||||
UUID = reader.GetString(1),
|
||||
Type = reader.GetInt32(2),
|
||||
Email = reader.IsDBNull(3) ? null : reader.GetString(3),
|
||||
Username = reader.GetString(4),
|
||||
DisplayName = reader.IsDBNull(5) ? null : reader.GetString(5),
|
||||
Password = reader.GetString(6),
|
||||
Created = reader.GetInt64(7),
|
||||
LastLogin = reader.GetInt64(8)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<User?> UserFromEmail(string email)
|
||||
{
|
||||
if (string.IsNullOrEmpty(email))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM users WHERE Email = @Email;";
|
||||
command.Parameters.AddWithValue("@Email", email);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return new User
|
||||
{
|
||||
UID = reader.GetInt32(0),
|
||||
UUID = reader.GetString(1),
|
||||
Type = reader.GetInt32(2),
|
||||
Email = reader.IsDBNull(3) ? null : reader.GetString(3),
|
||||
Username = reader.GetString(4),
|
||||
DisplayName = reader.IsDBNull(5) ? null : reader.GetString(5),
|
||||
Password = reader.GetString(6),
|
||||
Created = reader.GetInt64(7),
|
||||
LastLogin = reader.GetInt64(8)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<User?> UserFromToken(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM sessions WHERE Token = @Token;";
|
||||
command.Parameters.AddWithValue("@Token", token);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return await UserFromUUID(reader.GetString(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<User?> UserFromUID(int uid)
|
||||
{
|
||||
if (uid <= 0)
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM users WHERE UID = @UID;";
|
||||
command.Parameters.AddWithValue("@UID", uid);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return new User
|
||||
{
|
||||
UID = reader.GetInt32(0),
|
||||
UUID = reader.GetString(1),
|
||||
Type = reader.GetInt32(2),
|
||||
Email = reader.IsDBNull(3) ? null : reader.GetString(3),
|
||||
Username = reader.GetString(4),
|
||||
DisplayName = reader.IsDBNull(5) ? null : reader.GetString(5),
|
||||
Password = reader.GetString(6),
|
||||
Created = reader.GetInt64(7),
|
||||
LastLogin = reader.GetInt64(8)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<int> EnumeratePastes()
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT COUNT(*) FROM pastes;";
|
||||
return Convert.ToInt32(await command.ExecuteScalarAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<int> EnumerateUserPastes(User user)
|
||||
{
|
||||
if (user == null)
|
||||
return 0;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT COUNT(*) FROM pastes WHERE AuthorUUID = @AuthorUUID;";
|
||||
command.Parameters.AddWithValue("@AuthorUUID", user.UUID);
|
||||
return Convert.ToInt32(await command.ExecuteScalarAsync());
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<Paste?> GetPasteFromID(string id)
|
||||
{
|
||||
if (string.IsNullOrEmpty(id))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM pastes WHERE ID = @ID;";
|
||||
command.Parameters.AddWithValue("@ID", id);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return new Paste
|
||||
{
|
||||
UUID = reader.GetString(1),
|
||||
ID = reader.GetString(2),
|
||||
Visibility = reader.GetInt32(3),
|
||||
Title = reader.IsDBNull(4) ? null : reader.GetString(4),
|
||||
AuthorUUID = reader.GetString(5),
|
||||
FilePath = reader.GetString(6),
|
||||
Created = reader.GetInt64(7),
|
||||
Edited = reader.GetInt64(8),
|
||||
Size = reader.GetInt32(9),
|
||||
TrueSize = reader.GetInt32(10),
|
||||
Views = reader.GetInt32(11),
|
||||
Syntax = reader.IsDBNull(12) ? null : reader.GetString(12)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<bool> AlreadyViewed(RequestDetails details)
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM views WHERE Fingerprint = @Fingerprint";
|
||||
command.Parameters.AddWithValue("@Fingerprint", HelperService.SHA256Hash(details.Ip + details.UserAgent, Program.SHA256Salt));
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
return reader.HasRows;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<bool> HasAlreadyViewedFromUserDetails(User user)
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM views WHERE UserUUID = @UserUUID;";
|
||||
command.Parameters.AddWithValue("@UserUUID", user.UUID);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
return reader.HasRows;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task AddViewToPaste(User user, Paste paste, RequestDetails details)
|
||||
{
|
||||
if (paste == null || details == null)
|
||||
return;
|
||||
var _user = user ?? new User { UUID = "0" };
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "INSERT INTO views (UserUUID, PasteUUID, Fingerprint, UserAgent, Created) VALUES (@UserUUID, @PasteUUID, @Fingerprint, @UserAgent, @Created);";
|
||||
command.Parameters.AddWithValue("@UserUUID", _user.UUID);
|
||||
command.Parameters.AddWithValue("@PasteUUID", paste.UUID);
|
||||
command.Parameters.AddWithValue("@Fingerprint", HelperService.SHA256Hash(details.Ip + details.UserAgent, Program.SHA256Salt));
|
||||
command.Parameters.AddWithValue("@UserAgent", details.UserAgent ?? (object)DBNull.Value);
|
||||
command.Parameters.AddWithValue("@Created", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = "UPDATE pastes SET Views = Views + 1 WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@UUID", paste.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
await connection.CloseAsync();
|
||||
}
|
||||
}
|
||||
public async Task<List<Paste?>?> PastesFromUser(User user)
|
||||
{
|
||||
if (user == null)
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID;";
|
||||
command.Parameters.AddWithValue("@AuthorUUID", user.UUID);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
var pastes = new List<Paste?>();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
pastes.Add(new Paste
|
||||
{
|
||||
UUID = reader.GetString(1),
|
||||
ID = reader.GetString(2),
|
||||
Visibility = reader.GetInt32(3),
|
||||
Title = reader.IsDBNull(4) ? null : reader.GetString(4),
|
||||
AuthorUUID = reader.GetString(5),
|
||||
FilePath = reader.GetString(6),
|
||||
Created = reader.GetInt64(7),
|
||||
Edited = reader.GetInt64(8),
|
||||
Size = reader.GetInt32(9),
|
||||
TrueSize = reader.GetInt32(10),
|
||||
Views = reader.GetInt32(11),
|
||||
Syntax = reader.IsDBNull(12) ? null : reader.GetString(12)
|
||||
});
|
||||
}
|
||||
return pastes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<PasswordReset?> GetPasswordReset(string url, string uuid, string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(token))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM passwordresets WHERE URL = @URL AND UUID = @UUID AND Token = @Token;";
|
||||
command.Parameters.AddWithValue("@URL", url);
|
||||
command.Parameters.AddWithValue("@UUID", uuid);
|
||||
command.Parameters.AddWithValue("@Token", token);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return new PasswordReset
|
||||
{
|
||||
UID = reader.GetString(0),
|
||||
UUID = reader.GetString(1),
|
||||
USERUUID = reader.GetString(2),
|
||||
URL = reader.GetString(3),
|
||||
Token = reader.GetString(4),
|
||||
Created = reader.GetInt64(5),
|
||||
Expirary = reader.GetInt64(6)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
public async Task<bool> ResetPassword(string uuid, string password_hash)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uuid) || string.IsNullOrEmpty(password_hash))
|
||||
return false;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "UPDATE users SET Password = @Password WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@Password", password_hash);
|
||||
command.Parameters.AddWithValue("@UUID", uuid);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<Session?> CreateSession(User user, RequestDetails details, string token)
|
||||
{
|
||||
if (user == null || details == null)
|
||||
return new Session { UUID = "0" };
|
||||
var session = new Session
|
||||
{
|
||||
UUID = Guid.NewGuid().ToString(),
|
||||
UserUUID = user.UUID,
|
||||
Token = token,
|
||||
Created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||
Expirary = DateTimeOffset.UtcNow.AddDays(14).ToUnixTimeSeconds(),
|
||||
Ip = Bcrypt.HashPassword(details.Ip, Bcrypt.GenerateSalt(8)),
|
||||
UserAgent = details.UserAgent
|
||||
};
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "INSERT INTO sessions (UUID, UserUUID, Token, Created, Expirary, Ip, UserAgent) VALUES (@UUID, @UserUUID, @Token, @Created, @Expirary, @Ip, @UserAgent);";
|
||||
command.Parameters.AddWithValue("@UUID", session.UUID);
|
||||
command.Parameters.AddWithValue("@UserUUID", session.UserUUID);
|
||||
command.Parameters.AddWithValue("@Token", session.Token);
|
||||
command.Parameters.AddWithValue("@Created", session.Created);
|
||||
command.Parameters.AddWithValue("@Expirary", session.Expirary);
|
||||
command.Parameters.AddWithValue("@Ip", session.Ip);
|
||||
command.Parameters.AddWithValue("@UserAgent", session.UserAgent);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "UPDATE users SET LastLogin = @LastLogin WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@LastLogin", session.Created);
|
||||
command.Parameters.AddWithValue("@UUID", user.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
return session;
|
||||
}
|
||||
public async Task<Session?> GetSession(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return null;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM sessions WHERE Token = @Token;";
|
||||
command.Parameters.AddWithValue("@Token", token);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
await reader.ReadAsync();
|
||||
return new Session
|
||||
{
|
||||
UUID = reader.GetString(0),
|
||||
UserUUID = reader.GetString(1),
|
||||
Token = reader.GetString(2),
|
||||
Created = reader.GetInt64(3),
|
||||
Expirary = reader.GetInt64(4),
|
||||
Ip = reader.GetString(5),
|
||||
UserAgent = reader.GetString(6)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public async Task<bool> DeleteSession(string token)
|
||||
{
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return false;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "DELETE FROM sessions WHERE Token = @Token;";
|
||||
command.Parameters.AddWithValue("@Token", token);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public async Task<User?> CreateUser(string username, string email, string password_hash, string uuid)
|
||||
{
|
||||
if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password_hash))
|
||||
return null;
|
||||
var user = new User
|
||||
{
|
||||
UUID = uuid,
|
||||
Type = 0,
|
||||
Email = email,
|
||||
Username = username,
|
||||
DisplayName = username,
|
||||
Password = password_hash,
|
||||
Created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||
LastLogin = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
|
||||
};
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "INSERT INTO users (UUID, Type, Email, Username, DisplayName, Password, Created, LastLogin) VALUES (@UUID, @Type, @Email, @Username, @DisplayName, @Password, @Created, @LastLogin);";
|
||||
command.Parameters.AddWithValue("@UUID", user.UUID);
|
||||
command.Parameters.AddWithValue("@Type", user.Type);
|
||||
command.Parameters.AddWithValue("@Email", string.IsNullOrWhiteSpace(user.Email) ? DBNull.Value : user.Email);
|
||||
command.Parameters.AddWithValue("@Username", user.Username);
|
||||
command.Parameters.AddWithValue("@DisplayName", user.DisplayName ?? (object)DBNull.Value);
|
||||
command.Parameters.AddWithValue("@Password", user.Password);
|
||||
command.Parameters.AddWithValue("@Created", user.Created);
|
||||
command.Parameters.AddWithValue("@LastLogin", user.LastLogin);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
return user;
|
||||
}
|
||||
public async Task<bool> DeleteUser(User user)
|
||||
{
|
||||
if (user == null)
|
||||
return false;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "DELETE FROM users WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@UUID", user.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "DELETE FROM pastes WHERE AuthorUUID = @AuthorUUID;";
|
||||
command.Parameters.AddWithValue("@AuthorUUID", user.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "DELETE FROM sessions WHERE UserUUID = @UserUUID;";
|
||||
command.Parameters.AddWithValue("@UserUUID", user.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
// anonymize all views by user
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "UPDATE views SET UserUUID = @UserUUID WHERE UserUUID = @OldUserUUID;";
|
||||
command.Parameters.AddWithValue("@UserUUID", "0");
|
||||
command.Parameters.AddWithValue("@OldUserUUID", user.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public async Task<bool> CreatePaste(Paste paste, ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (paste == null || string.IsNullOrEmpty(paste.UUID) || string.IsNullOrEmpty(paste.ID) || paste.AuthorUUID == null)
|
||||
return false;
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "INSERT INTO pastes (UUID, ID, Visibility, Title, AuthorUUID, FilePath, Created, Edited, Size, TrueSize, Views, Syntax) VALUES (@UUID, @ID, @Visibility, @Title, @AuthorUUID, @FilePath, @Created, @Edited, @Size, @TrueSize, @Views, @Syntax);";
|
||||
command.Parameters.AddWithValue("@UUID", paste.UUID);
|
||||
command.Parameters.AddWithValue("@ID", paste.ID);
|
||||
command.Parameters.AddWithValue("@Visibility", paste.Visibility ?? 0);
|
||||
command.Parameters.AddWithValue("@Title", paste.Title ?? (object)DBNull.Value);
|
||||
command.Parameters.AddWithValue("@AuthorUUID", paste.AuthorUUID);
|
||||
command.Parameters.AddWithValue("@FilePath", paste.FilePath ?? (object)DBNull.Value);
|
||||
command.Parameters.AddWithValue("@Created", paste.Created ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds());
|
||||
command.Parameters.AddWithValue("@Edited", paste.Edited ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds());
|
||||
command.Parameters.AddWithValue("@Size", paste.Size ?? 0);
|
||||
command.Parameters.AddWithValue("@TrueSize", paste.TrueSize ?? 0);
|
||||
command.Parameters.AddWithValue("@Views", paste.Views ?? 0);
|
||||
command.Parameters.AddWithValue("@Syntax", paste.Syntax ?? (object)DBNull.Value);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to create paste in database.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public async Task<List<View?>?> GetViewsFromPaste(string uuid, ILogger logger)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uuid))
|
||||
return null;
|
||||
try
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM views WHERE PasteUUID = @PasteUUID;";
|
||||
command.Parameters.AddWithValue("@PasteUUID", uuid);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
var views = new List<View?>();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
views.Add(new View
|
||||
{
|
||||
UserUUID = reader.GetString(0),
|
||||
PasteUUID = reader.GetString(1),
|
||||
Fingerprint = reader.GetString(2),
|
||||
UserAgent = reader.GetString(3),
|
||||
Created = reader.GetInt64(4)
|
||||
});
|
||||
}
|
||||
return views;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to get views from paste in database.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public async Task<List<Paste?>?> GetPastes(int limit, int page, ILogger logger)
|
||||
{
|
||||
if (limit <= 0 || page < 0)
|
||||
return null;
|
||||
try
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "SELECT * FROM pastes WHERE Visibility NOT IN (1,2) ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;";
|
||||
command.Parameters.AddWithValue("@Limit", limit);
|
||||
command.Parameters.AddWithValue("@Offset", limit * page);
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
var pastes = new List<Paste?>();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
pastes.Add(new Paste
|
||||
{
|
||||
UID = reader.GetInt32(0),
|
||||
UUID = reader.GetString(1),
|
||||
ID = reader.GetString(2),
|
||||
Visibility = reader.GetInt32(3),
|
||||
Title = reader.IsDBNull(4) ? null : reader.GetString(4),
|
||||
AuthorUUID = reader.GetString(5),
|
||||
FilePath = reader.GetString(6),
|
||||
Created = reader.GetInt64(7),
|
||||
Edited = reader.GetInt64(8),
|
||||
Size = reader.GetInt32(9),
|
||||
TrueSize = reader.GetInt32(10),
|
||||
Views = reader.GetInt32(11),
|
||||
Syntax = reader.IsDBNull(12) ? null : reader.GetString(12)
|
||||
});
|
||||
}
|
||||
return pastes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to get pastes from database.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public async Task<List<Paste?>?> GetPastesFromUser(User user, int limit, int page, ILogger logger, bool _private = false)
|
||||
{
|
||||
if (user == null || limit <= 0 || page < 0)
|
||||
return null;
|
||||
try
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
if (_private)
|
||||
command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;";
|
||||
else
|
||||
command.CommandText = "SELECT * FROM pastes WHERE AuthorUUID = @AuthorUUID AND Visibility NOT IN (1,2) ORDER BY Created DESC LIMIT @Limit OFFSET @Offset;";
|
||||
|
||||
command.Parameters.AddWithValue("@AuthorUUID", user.UUID);
|
||||
command.Parameters.AddWithValue("@Limit", limit);
|
||||
command.Parameters.AddWithValue("@Offset", limit * page);
|
||||
|
||||
using (var reader = await command.ExecuteReaderAsync())
|
||||
{
|
||||
if (!reader.HasRows)
|
||||
return null;
|
||||
var pastes = new List<Paste?>();
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
pastes.Add(new Paste
|
||||
{
|
||||
UID = reader.GetInt32(0),
|
||||
UUID = reader.GetString(1),
|
||||
ID = reader.GetString(2),
|
||||
Visibility = reader.GetInt32(3),
|
||||
Title = reader.IsDBNull(4) ? null : reader.GetString(4),
|
||||
AuthorUUID = reader.GetString(5),
|
||||
FilePath = reader.GetString(6),
|
||||
Created = reader.GetInt64(7),
|
||||
Edited = reader.GetInt64(8),
|
||||
Size = reader.GetInt32(9),
|
||||
TrueSize = reader.GetInt32(10),
|
||||
Views = reader.GetInt32(11),
|
||||
Syntax = reader.IsDBNull(12) ? null : reader.GetString(12)
|
||||
});
|
||||
}
|
||||
return pastes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to get user pastes from database.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public async Task<bool> DeletePaste(Paste paste, ILogger logger)
|
||||
{
|
||||
if (paste == null || string.IsNullOrEmpty(paste.UUID))
|
||||
return false;
|
||||
try
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "DELETE FROM pastes WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@UUID", paste.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "DELETE FROM views WHERE PasteUUID = @PasteUUID;";
|
||||
command.Parameters.AddWithValue("@PasteUUID", paste.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(paste.FilePath) && File.Exists(paste.FilePath))
|
||||
{
|
||||
File.Delete(paste.FilePath);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to delete paste from database.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public async Task<Paste?> UpdatePaste(Paste paste, ILogger logger)
|
||||
{
|
||||
if (paste == null || string.IsNullOrEmpty(paste.UUID))
|
||||
return null;
|
||||
try
|
||||
{
|
||||
using (var connection = new SqliteConnection(_connectionString))
|
||||
{
|
||||
await connection.OpenAsync();
|
||||
using (var command = connection.CreateCommand())
|
||||
{
|
||||
command.CommandText = "UPDATE pastes SET Visibility = @Visibility, Title = @Title, Edited = @Edited, Size = @Size, TrueSize = @TrueSize, Syntax = @Syntax, FilePath = @FilePath WHERE UUID = @UUID;";
|
||||
command.Parameters.AddWithValue("@Visibility", paste.Visibility ?? 0);
|
||||
command.Parameters.AddWithValue("@Title", paste.Title ?? (object)DBNull.Value);
|
||||
command.Parameters.AddWithValue("@Edited", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
|
||||
command.Parameters.AddWithValue("@Size", paste.Size ?? 0);
|
||||
command.Parameters.AddWithValue("@TrueSize", paste.TrueSize ?? 0);
|
||||
command.Parameters.AddWithValue("@Syntax", paste.Syntax ?? (object)DBNull.Value);
|
||||
command.Parameters.AddWithValue("@FilePath", paste.FilePath);
|
||||
command.Parameters.AddWithValue("@UUID", paste.UUID);
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
return paste;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to update paste in database.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using SharpbinV2.Server.Models;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Bcrypt = BCrypt.Net.BCrypt;
|
||||
|
||||
namespace SharpbinV2.Server.Services
|
||||
{
|
||||
public class HelperService
|
||||
{
|
||||
public static string[] ipHeaders =
|
||||
{
|
||||
"X-Forwarded-For",
|
||||
"X-Real-IP",
|
||||
"CF-Connecting-IP",
|
||||
"True-Client-IP",
|
||||
"X-Cluster-Client-IP",
|
||||
"X-ProxyUser-IP"
|
||||
};
|
||||
|
||||
public static JObject? TryParse(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JObject.Parse(json);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public static JArray? TryParseArray(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JArray.Parse(json);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public static string GenerateToken()
|
||||
{
|
||||
string randomstring = GenerateRandomString(32);
|
||||
string randomguid = Guid.NewGuid().ToString();
|
||||
return Convert.ToBase64String(Encoding.UTF8.GetBytes(Bcrypt.HashPassword(randomstring + randomguid, Bcrypt.GenerateSalt(10))));
|
||||
}
|
||||
public static string GenerateRandomString(int length)
|
||||
{
|
||||
var random = new Random();
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
|
||||
}
|
||||
public static RequestDetails GetRequestDetails(HttpContext context)
|
||||
{
|
||||
var requestdetails = new RequestDetails();
|
||||
var headers = context.Request.Headers;
|
||||
if (headers.ContainsKey("User-Agent"))
|
||||
requestdetails.UserAgent = headers["User-Agent"];
|
||||
|
||||
requestdetails.Ip = ipHeaders
|
||||
.FirstOrDefault(header => headers.TryGetValue(header, out var ip) && !string.IsNullOrWhiteSpace(ip))
|
||||
is string matchedHeader ? headers[matchedHeader] : context.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
if (headers.ContainsKey("Authorization"))
|
||||
requestdetails.Token = headers["Authorization"];
|
||||
else if (context.Request.Cookies.ContainsKey("Authorization"))
|
||||
requestdetails.Token = context.Request.Cookies["Authorization"];
|
||||
|
||||
return requestdetails;
|
||||
}
|
||||
public static string FormatBytes(long bytes)
|
||||
{
|
||||
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
|
||||
double len = bytes;
|
||||
int order = 0;
|
||||
while (len >= 1024 && order < sizes.Length - 1)
|
||||
{
|
||||
order++;
|
||||
len = len / 1024;
|
||||
}
|
||||
return $"{len:0.##} {sizes[order]}";
|
||||
}
|
||||
public static bool IsValidEmail(string email)
|
||||
{
|
||||
return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
|
||||
}
|
||||
public static string SHA256Hash(string input, string salt = "")
|
||||
{
|
||||
using (SHA256 sha256Hash = SHA256.Create())
|
||||
{
|
||||
string combinedInput = input + salt;
|
||||
byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(combinedInput));
|
||||
|
||||
StringBuilder builder = new StringBuilder();
|
||||
foreach (byte b in bytes)
|
||||
{
|
||||
builder.Append(b.ToString("x2"));
|
||||
}
|
||||
return builder.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>37bd710f-bebc-4da3-b1f2-d9b2885ff0a8</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<SignAssembly>False</SignAssembly>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="logs\**" />
|
||||
<Compile Remove="pastes\**" />
|
||||
<Content Remove="logs\**" />
|
||||
<Content Remove="pastes\**" />
|
||||
<EmbeddedResource Remove="logs\**" />
|
||||
<EmbeddedResource Remove="pastes\**" />
|
||||
<None Remove="logs\**" />
|
||||
<None Remove="pastes\**" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="Classes.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="9.0.5" />
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
|
||||
<PackageReference Include="UAParser" Version="3.1.47" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="wwwroot\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.5.2.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpbinV3.Server", "SharpbinV3.Server.csproj", "{79A5E17C-498C-F55E-C79E-1F32E48383EF}"
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpbinV2.Server", "SharpbinV2.Server.csproj", "{68738FF4-A603-C797-2A44-D510EF342839}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@@ -10,15 +10,15 @@ Global
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{68738FF4-A603-C797-2A44-D510EF342839}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{68738FF4-A603-C797-2A44-D510EF342839}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{68738FF4-A603-C797-2A44-D510EF342839}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{68738FF4-A603-C797-2A44-D510EF342839}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {98CE5484-B4BF-4C6B-9EEC-07F6E621F094}
|
||||
SolutionGuid = {4E1CB94E-6A3B-4EDF-95C2-479B8817C596}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Paste Archives - Sharpbin</title>
|
||||
<link rel="preload" href="css/style.css" as="style">
|
||||
<link rel="preload" href="css/archive.css" as="style">
|
||||
<link rel="preload" href="js/archive.js" as="script">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<link rel="stylesheet" href="css/archive.css">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
|
||||
rel="stylesheet">
|
||||
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="main-container">
|
||||
<h1 id="archive-header">Paste Archives</h1>
|
||||
<div class="archive-information">
|
||||
<p id="archive-title">Title</p>
|
||||
<p id="archive-date">Date</p>
|
||||
<p id="archive-syntax">Syntax</p>
|
||||
</div>
|
||||
<ol class="archive-list" id="archives">
|
||||
</ol>
|
||||
<div class="paste-actions">
|
||||
<button id="previous-button"><span id="previous-button-svg"></span></button>
|
||||
<p id="paste-pages">0/0</p>
|
||||
<button id="next-button"><span id="next-button-svg"></span></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="js/archive.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,229 @@
|
||||
.main-container {
|
||||
max-width: 80%;
|
||||
max-height: 80vh;
|
||||
margin: 2rem auto;
|
||||
margin-top: calc(2rem + 55px);
|
||||
padding: 1.5rem;
|
||||
background-color: var(--neutral-900);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
#archive-header {
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
margin-bottom: 1.5rem;
|
||||
color: var(--neutral-50);
|
||||
text-align: center;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.archive-information {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr 1fr;
|
||||
gap: 1rem;
|
||||
padding: 0.75rem 1rem;
|
||||
margin-bottom: 1rem;
|
||||
background-color: var(--neutral-800);
|
||||
border-radius: 6px;
|
||||
font-weight: 600;
|
||||
color: var(--neutral-200);
|
||||
border-bottom: 2px solid var(--neutral-700);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.archive-information p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.archive-list {
|
||||
list-style-type: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
border-radius: 6px;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--neutral-700) var(--neutral-900);
|
||||
}
|
||||
|
||||
.archive-list::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.archive-list::-webkit-scrollbar-track {
|
||||
background: var(--neutral-900);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.archive-list::-webkit-scrollbar-thumb {
|
||||
background-color: var(--neutral-700);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.archive-list li {
|
||||
margin: 0.75rem 0;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.archive-list li:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.archive-list li a {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr 1fr;
|
||||
gap: 1rem;
|
||||
padding: 1rem 1.25rem;
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
text-decoration: none;
|
||||
transition: all 0.3s ease;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.archive-list li a:hover {
|
||||
background-color: var(--neutral-750);
|
||||
border-color: var(--neutral-600);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.archive-list li a p {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#archive-title {
|
||||
font-weight: 500;
|
||||
color: var(--neutral-100);
|
||||
}
|
||||
|
||||
#archive-date {
|
||||
color: var(--neutral-300);
|
||||
font-size: 0.9rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#archive-syntax {
|
||||
color: var(--neutral-300);
|
||||
font-size: 0.9rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.paste-actions {
|
||||
width: 100%;
|
||||
margin-top: 1.5rem;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.paste-actions button {
|
||||
padding: 0.4rem 0.8rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
font-size: 1rem;
|
||||
min-width: 75px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.paste-actions button:hover:not(:disabled) {
|
||||
background-color: var(--neutral-700);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.paste-actions button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
#paste-pages {
|
||||
font-weight: 500;
|
||||
color: var(--neutral-300);
|
||||
font-size: 1.1rem;
|
||||
margin: 0;
|
||||
padding: 0.5rem 1rem;
|
||||
background-color: var(--neutral-800);
|
||||
border-radius: 6px;
|
||||
min-width: 80px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.archive-information,
|
||||
.archive-list li a {
|
||||
grid-template-columns: 3fr 2fr;
|
||||
}
|
||||
|
||||
#archive-syntax {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.archive-information p:last-child {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.paste-actions button {
|
||||
padding: 0.5rem 1rem;
|
||||
min-width: 80px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.main-container {
|
||||
padding: 1rem;
|
||||
max-width: 95%;
|
||||
}
|
||||
|
||||
#archive-header {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.archive-list {
|
||||
max-height: 60vh;
|
||||
}
|
||||
|
||||
.paste-actions {
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
#paste-pages {
|
||||
min-width: 60px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
}
|
||||
|
||||
#next-button-svg {
|
||||
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M310.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-192 192c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L242.7 256 73.4 86.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l192 192z"/></svg>');
|
||||
color: white;
|
||||
width: 1.5em;
|
||||
height: 1.5em;
|
||||
background-size: contain;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
filter: invert(100%);
|
||||
}
|
||||
|
||||
#previous-button-svg {
|
||||
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l192 192c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L77.3 256l169.3-169.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-192 192z"/></svg>');
|
||||
color: white;
|
||||
width: 1.5em;
|
||||
height: 1.5em;
|
||||
background-size: contain;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
filter: invert(100%);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
.auth-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
min-height: 100vh;
|
||||
min-width: 100%;
|
||||
padding: 20px;
|
||||
background-color: var(--neutral-950);
|
||||
}
|
||||
|
||||
.auth-form-container {
|
||||
background-color: var(--neutral-900);
|
||||
border-radius: 8px;
|
||||
padding: 30px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
|
||||
width: 100%;
|
||||
max-width: 650px;
|
||||
border: 1px solid var(--neutral-800);
|
||||
}
|
||||
|
||||
.auth-title {
|
||||
text-align: center;
|
||||
font-size: 1.8rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 24px;
|
||||
color: var(--neutral-100);
|
||||
}
|
||||
|
||||
.auth-description {
|
||||
text-align: center;
|
||||
color: var(--neutral-400);
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 20px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.auth-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
color: var(--neutral-300);
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
padding: 12px 16px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-100);
|
||||
font-size: 1rem;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.form-group input:focus {
|
||||
outline: none;
|
||||
border-color: var(--neutral-500);
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.auth-button {
|
||||
margin-top: 10px;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
background-color: var(--neutral-700);
|
||||
color: var(--neutral-50);
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.auth-button:hover {
|
||||
background-color: var(--neutral-600);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.auth-links {
|
||||
margin-top: 24px;
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.auth-links p {
|
||||
color: var(--neutral-400);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.auth-links a {
|
||||
color: var(--neutral-300);
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
|
||||
.auth-links a:hover {
|
||||
color: var(--neutral-100);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
background-color: rgba(220, 38, 38, 0.1);
|
||||
color: #ef4444;
|
||||
padding: 10px 16px;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 16px;
|
||||
font-size: 0.9rem;
|
||||
display: none;
|
||||
border: 1px solid rgba(220, 38, 38, 0.2);
|
||||
}
|
||||
|
||||
.error-message.visible {
|
||||
display: block;
|
||||
animation: fadeIn 0.3s ease;
|
||||
}
|
||||
|
||||
.success-message {
|
||||
background-color: rgba(34, 197, 94, 0.1);
|
||||
color: #22c55e;
|
||||
padding: 10px 16px;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 16px;
|
||||
font-size: 0.9rem;
|
||||
border: 1px solid rgba(34, 197, 94, 0.2);
|
||||
animation: fadeIn 0.3s ease;
|
||||
}
|
||||
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
|
||||
.auth-container {
|
||||
padding: 0px;
|
||||
}
|
||||
|
||||
.auth-form-container {
|
||||
padding: 20px;
|
||||
max-width: 100%;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
|
||||
.auth-title {
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.auth-button {
|
||||
padding: 10px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
::selection {
|
||||
background-color: var(--neutral-600);
|
||||
color: var(--neutral-100);
|
||||
}
|
||||
|
||||
::-moz-selection {
|
||||
background-color: var(--neutral-600);
|
||||
color: var(--neutral-100);
|
||||
}
|
||||
|
||||
input::selection,
|
||||
textarea::selection {
|
||||
background-color: #3b82f6;
|
||||
color: white;
|
||||
}
|
||||
|
||||
input::-moz-selection,
|
||||
textarea::-moz-selection {
|
||||
background-color: #3b82f6;
|
||||
color: white;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--neutral-950);
|
||||
color: var(--neutral-100);
|
||||
}
|
||||
|
||||
.main-container {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
align-items: stretch;
|
||||
margin-top: 2rem;
|
||||
min-height: 400px;
|
||||
padding: 20px;
|
||||
gap: 25px;
|
||||
}
|
||||
|
||||
.account-info,
|
||||
.paste-list {
|
||||
width: 48%;
|
||||
border-radius: 8px;
|
||||
padding: 25px;
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
|
||||
background-color: var(--neutral-900);
|
||||
border: 1px solid var(--neutral-700);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.paste-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.account-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.account-info:hover,
|
||||
.paste-list:hover {
|
||||
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.25);
|
||||
border-color: var(--neutral-700);
|
||||
}
|
||||
|
||||
.account-info h1,
|
||||
.paste-list h1 {
|
||||
margin-bottom: 25px;
|
||||
color: var(--neutral-100);
|
||||
text-align: center;
|
||||
font-size: 1.8rem;
|
||||
border-bottom: 2px solid var(--neutral-700);
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
.account-info p {
|
||||
margin: 12px 0;
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid var(--neutral-800);
|
||||
font-size: 1.05rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
color: var(--neutral-300);
|
||||
}
|
||||
|
||||
.paste-information {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
padding: 10px 0;
|
||||
border-bottom: 2px solid var(--neutral-700);
|
||||
font-weight: bold;
|
||||
margin-bottom: 15px;
|
||||
color: var(--neutral-300);
|
||||
}
|
||||
|
||||
#pastes {
|
||||
list-style-type: none;
|
||||
width: 100%;
|
||||
max-height: 90%;
|
||||
overflow-y: auto;
|
||||
padding: 0;
|
||||
border-radius: 4px;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--neutral-700) var(--neutral-900);
|
||||
border: none;
|
||||
}
|
||||
|
||||
#pastes li {
|
||||
margin: 0.75rem 0;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
#pastes li:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
#pastes li a {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr 1fr;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
text-decoration: none;
|
||||
transition: all 0.3s ease;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
#pastes li a:hover {
|
||||
background-color: var(--neutral-750);
|
||||
border-color: var(--neutral-600);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
#pastes li a p {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
#paste-title {
|
||||
font-weight: 500;
|
||||
color: var(--neutral-100);
|
||||
}
|
||||
|
||||
#paste-date {
|
||||
color: var(--neutral-300);
|
||||
font-size: 0.9rem;
|
||||
text-align: center;
|
||||
overflow: hidden !important;
|
||||
text-overflow: clip !important;
|
||||
white-space: nowrap !important;
|
||||
text-align: left;
|
||||
margin-right: -70px !important;
|
||||
}
|
||||
|
||||
#paste-syntax {
|
||||
color: var(--neutral-300);
|
||||
font-size: 0.9rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
|
||||
|
||||
.paste-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
margin-top: auto;
|
||||
padding-top: 15px;
|
||||
border-top: 1px solid var(--neutral-800);
|
||||
}
|
||||
|
||||
.paste-actions button {
|
||||
background-color: var(--neutral-700);
|
||||
color: var(--neutral-50);
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 8px 15px;
|
||||
margin: 0 10px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.paste-actions button:hover {
|
||||
background-color: var(--neutral-600);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.paste-actions button:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.paste-actions button:disabled {
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-500);
|
||||
cursor: not-allowed;
|
||||
opacity: 0.7;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
#paste-pages {
|
||||
margin: 0 15px;
|
||||
font-weight: bold;
|
||||
min-width: 40px;
|
||||
text-align: center;
|
||||
color: var(--neutral-300);
|
||||
}
|
||||
|
||||
#pastes::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
#pastes::-webkit-scrollbar-track {
|
||||
background: var(--neutral-900);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
#pastes::-webkit-scrollbar-thumb {
|
||||
background-color: var(--neutral-700);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
#pastes::-webkit-scrollbar-thumb:hover {
|
||||
background-color: var(--neutral-600);
|
||||
}
|
||||
|
||||
@media (max-width: 992px) {
|
||||
.main-container {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.account-info,
|
||||
.paste-list {
|
||||
padding: 20px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.main-container {
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.account-info,
|
||||
.paste-list {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 576px) {
|
||||
.main-container {
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.account-info,
|
||||
.paste-list {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
.account-info h1,
|
||||
.paste-list h1 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
#pastes li {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
#pastes li span {
|
||||
margin-top: 5px;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
.logout-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 2000;
|
||||
}
|
||||
|
||||
.logout-modal-box {
|
||||
background: var(--neutral-900);
|
||||
color: var(--neutral-100);
|
||||
padding: 2rem 2.5rem;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);
|
||||
text-align: center;
|
||||
min-width: 300px;
|
||||
max-width: 90vw;
|
||||
}
|
||||
|
||||
.logout-modal-box h2 {
|
||||
margin-bottom: 1rem;
|
||||
font-size: 1.4rem;
|
||||
color: var(--neutral-50);
|
||||
}
|
||||
|
||||
.logout-modal-box p {
|
||||
margin-bottom: 2rem;
|
||||
color: var(--neutral-300);
|
||||
}
|
||||
|
||||
.logout-modal-box button {
|
||||
margin: 0 0.5rem;
|
||||
padding: 0.7rem 1.5rem;
|
||||
border-radius: 6px;
|
||||
font-weight: 600;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
transition: background 0.2s, color 0.2s;
|
||||
}
|
||||
|
||||
#confirm-logout {
|
||||
background: #e74c3c;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#confirm-logout:hover {
|
||||
background: #c0392b;
|
||||
}
|
||||
|
||||
#cancel-logout {
|
||||
background: var(--neutral-700);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#cancel-logout:hover {
|
||||
background: var(--neutral-600);
|
||||
}
|
||||
|
||||
#logout-button {
|
||||
background-color: var(--neutral-700);
|
||||
color: var(--neutral-50);
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 10px 24px;
|
||||
margin-top: auto;
|
||||
font-size: 1.08rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.2s;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
#logout-button:hover {
|
||||
background-color: var(--neutral-600);
|
||||
color: var(--neutral-10);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.13);
|
||||
}
|
||||
|
||||
#logout-button:active {
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-200);
|
||||
transform: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
#delete-account-button {
|
||||
background-color: #e74c3c;
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 10px 24px;
|
||||
font-size: 1.08rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s, color 0.2s, box-shadow 0.2s, transform 0.2s;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
|
||||
letter-spacing: 0.5px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
#delete-account-button:hover {
|
||||
background-color: #c0392b;
|
||||
color: #fff;
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.13);
|
||||
}
|
||||
|
||||
#delete-account-button:active {
|
||||
background-color: #a93226;
|
||||
color: #fff;
|
||||
transform: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.delete-modal-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 2100;
|
||||
}
|
||||
|
||||
.delete-modal-box {
|
||||
background: var(--neutral-900);
|
||||
color: var(--neutral-100);
|
||||
padding: 2rem 2.5rem;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);
|
||||
text-align: center;
|
||||
min-width: 320px;
|
||||
max-width: 95vw;
|
||||
}
|
||||
|
||||
.delete-modal-box h2 {
|
||||
margin-bottom: 1rem;
|
||||
font-size: 1.4rem;
|
||||
color: #e74c3c;
|
||||
}
|
||||
|
||||
.delete-modal-box p {
|
||||
margin-bottom: 1.2rem;
|
||||
color: var(--neutral-300);
|
||||
}
|
||||
|
||||
.delete-modal-box input {
|
||||
margin-bottom: 0.7rem;
|
||||
width: 90%;
|
||||
padding: 8px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
background: var(--neutral-800);
|
||||
color: var(--neutral-100);
|
||||
font-size: 1rem;
|
||||
outline: none;
|
||||
transition: border 0.2s;
|
||||
}
|
||||
|
||||
.delete-modal-box input:focus {
|
||||
border: 1.5px solid #e74c3c;
|
||||
}
|
||||
|
||||
.delete-modal-box button {
|
||||
margin: 0 0.5rem;
|
||||
padding: 0.7rem 1.5rem;
|
||||
border-radius: 6px;
|
||||
font-weight: 600;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
transition: background 0.2s, color 0.2s;
|
||||
}
|
||||
|
||||
#confirm-delete-account {
|
||||
background: #e74c3c;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#confirm-delete-account:hover {
|
||||
background: #c0392b;
|
||||
}
|
||||
|
||||
#confirm-delete-account:disabled {
|
||||
background: var(--neutral-800);
|
||||
color: var(--neutral-500);
|
||||
cursor: not-allowed;
|
||||
opacity: 0.7;
|
||||
box-shadow: none;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
#cancel-delete-account {
|
||||
background: var(--neutral-700);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#cancel-delete-account:hover {
|
||||
background: var(--neutral-600);
|
||||
}
|
||||
|
||||
#delete-error {
|
||||
color: #e74c3c;
|
||||
font-size: 1rem;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
.nav-bar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.75rem 2rem;
|
||||
background-color: var(--neutral-900);
|
||||
color: #fff;
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
top: 0;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.nav-brand {
|
||||
flex: 0 0 auto;
|
||||
z-index: 15;
|
||||
}
|
||||
|
||||
.brand-link {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
letter-spacing: 0.5px;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.brand-link:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.nav-center {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
text-decoration: none;
|
||||
font-size: 1.1rem;
|
||||
padding: 0.6rem 1.2rem;
|
||||
border-radius: 6px;
|
||||
transition: all 0.3s ease;
|
||||
font-weight: 500;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
color: #fff;
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
#nav-bar-selected {
|
||||
color: #fff;
|
||||
background-color: rgba(255, 255, 255, 0.15);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.hamburger {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
width: 30px;
|
||||
height: 21px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
z-index: 15;
|
||||
}
|
||||
|
||||
.hamburger-line {
|
||||
display: block;
|
||||
height: 3px;
|
||||
width: 100%;
|
||||
border-radius: 10px;
|
||||
background: #fff;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.nav-center {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
position: fixed;
|
||||
top: 60px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background-color: var(--neutral-900);
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 0;
|
||||
max-height: 0;
|
||||
overflow: hidden;
|
||||
transition: max-height 0.3s ease-out, padding 0.3s ease;
|
||||
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.nav-links.show {
|
||||
max-height: 300px;
|
||||
padding: 1rem 0;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
width: 90%;
|
||||
text-align: center;
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid var(--neutral-800);
|
||||
}
|
||||
|
||||
.home-link {
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--neutral-800);
|
||||
order: -1;
|
||||
}
|
||||
|
||||
.nav-link:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.hamburger {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.hamburger.active .hamburger-line:nth-child(1) {
|
||||
transform: translateY(9px) rotate(45deg);
|
||||
}
|
||||
|
||||
.hamburger.active .hamburger-line:nth-child(2) {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.hamburger.active .hamburger-line:nth-child(3) {
|
||||
transform: translateY(-9px) rotate(-45deg);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
#blur[data-decrypted="false"] {
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
backdrop-filter: blur(10px);
|
||||
}
|
||||
|
||||
#blur[data-decrypted="true"] {
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
#blur {
|
||||
z-index: 50;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
#notification-container {
|
||||
position: fixed;
|
||||
z-index: 10001;
|
||||
top: 24px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
margin: 0 auto;
|
||||
width: fit-content;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.paste-information {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid var(--neutral-700);
|
||||
}
|
||||
|
||||
.paste-information p {
|
||||
margin-left: 2.5px;
|
||||
margin-right: 2.5px;
|
||||
}
|
||||
|
||||
.paste-header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.main-container {
|
||||
max-height: 80% !important;
|
||||
}
|
||||
|
||||
.paste-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
max-height: 80%;
|
||||
margin-top: 15px;
|
||||
background-color: var(--neutral-800);
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
}
|
||||
|
||||
#paste-content {
|
||||
padding: 10px;
|
||||
max-width: 100%;
|
||||
max-height: 50vh;
|
||||
overflow-y: scroll;
|
||||
overflow-wrap: break-word;
|
||||
word-wrap: break-word;
|
||||
white-space: pre-wrap;
|
||||
border-radius: 0px;
|
||||
border-bottom-right-radius: 5px;
|
||||
border-bottom-left-radius: 5px;
|
||||
display: block !important;
|
||||
}
|
||||
|
||||
.paste-actions {
|
||||
padding: 10px;
|
||||
width: 100%;
|
||||
border-bottom: 1px solid var(--neutral-700);
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 5px;
|
||||
margin: 5px 0;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: var(--neutral-700);
|
||||
border-color: var(--neutral-600);
|
||||
}
|
||||
|
||||
button:active {
|
||||
background-color: var(--neutral-600);
|
||||
border-color: var(--neutral-500);
|
||||
}
|
||||
|
||||
.hljs {
|
||||
padding: 1rem;
|
||||
border-radius: 6px;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.hljs-ln-numbers {
|
||||
border-right: 1px solid var(--neutral-700);
|
||||
padding-right: 8px !important;
|
||||
padding-left: 8px !important;
|
||||
text-align: center;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.hljs-ln-code {
|
||||
padding-left: 16px !important;
|
||||
text-align: left;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
pre code.hljs {
|
||||
display: block !important;
|
||||
overflow-x: auto;
|
||||
padding: 1em
|
||||
}
|
||||
|
||||
code.hljs {
|
||||
padding: 3px 5px
|
||||
}
|
||||
|
||||
.hljs {
|
||||
color: #c9d1d9;
|
||||
background: #1e1e1e;
|
||||
}
|
||||
|
||||
.hljs-doctag,
|
||||
.hljs-keyword,
|
||||
.hljs-meta .hljs-keyword,
|
||||
.hljs-template-tag,
|
||||
.hljs-template-variable,
|
||||
.hljs-type,
|
||||
.hljs-variable.language_ {
|
||||
color: #ff7b72
|
||||
}
|
||||
|
||||
.hljs-title,
|
||||
.hljs-title.class_,
|
||||
.hljs-title.class_.inherited__,
|
||||
.hljs-title.function_ {
|
||||
color: #d2a8ff
|
||||
}
|
||||
|
||||
.hljs-attr,
|
||||
.hljs-attribute,
|
||||
.hljs-literal,
|
||||
.hljs-meta,
|
||||
.hljs-number,
|
||||
.hljs-operator,
|
||||
.hljs-selector-attr,
|
||||
.hljs-selector-class,
|
||||
.hljs-selector-id,
|
||||
.hljs-variable {
|
||||
color: #79c0ff
|
||||
}
|
||||
|
||||
.hljs-meta .hljs-string,
|
||||
.hljs-regexp,
|
||||
.hljs-string {
|
||||
color: #a5d6ff
|
||||
}
|
||||
|
||||
.hljs-built_in,
|
||||
.hljs-symbol {
|
||||
color: #ffa657
|
||||
}
|
||||
|
||||
.hljs-code,
|
||||
.hljs-comment,
|
||||
.hljs-formula {
|
||||
color: #8b949e
|
||||
}
|
||||
|
||||
.hljs-name,
|
||||
.hljs-quote,
|
||||
.hljs-selector-pseudo,
|
||||
.hljs-selector-tag {
|
||||
color: #7ee787
|
||||
}
|
||||
|
||||
.hljs-subst {
|
||||
color: #c9d1d9
|
||||
}
|
||||
|
||||
.hljs-section {
|
||||
color: #1f6feb;
|
||||
font-weight: 700
|
||||
}
|
||||
|
||||
.hljs-bullet {
|
||||
color: #f2cc60
|
||||
}
|
||||
|
||||
.hljs-emphasis {
|
||||
color: #c9d1d9;
|
||||
font-style: italic
|
||||
}
|
||||
|
||||
.hljs-strong {
|
||||
color: #c9d1d9;
|
||||
font-weight: 700
|
||||
}
|
||||
|
||||
.hljs-addition {
|
||||
color: #aff5b4;
|
||||
background-color: #033a16
|
||||
}
|
||||
|
||||
.hljs-deletion {
|
||||
color: #ffdcd7;
|
||||
background-color: #67060c
|
||||
}
|
||||
|
||||
.throbber {
|
||||
border: 4px solid var(--neutral-700);
|
||||
border-top: 4px solid var(--neutral-50);
|
||||
border-radius: 50%;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
animation: spin 1s linear infinite;
|
||||
margin: auto;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.paste-information-card {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: none;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
padding: 0 0 8px 0;
|
||||
margin: 0 0 8px 0;
|
||||
border-bottom: 1px solid var(--neutral-700);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.paste-info-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 1rem;
|
||||
color: var(--neutral-100);
|
||||
font-weight: 400;
|
||||
background: none;
|
||||
border-radius: 0;
|
||||
padding: 0 6px;
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.info-icon {
|
||||
font-size: 1em;
|
||||
opacity: 0.7;
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
#author-link {
|
||||
color: var(--neutral-100);
|
||||
text-decoration: underline dotted;
|
||||
font-weight: 400;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
#author-link:hover {
|
||||
color: #4ea1f7;
|
||||
}
|
||||
|
||||
.paste-header h1#paste-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 6px;
|
||||
color: var(--neutral-50);
|
||||
letter-spacing: 0.2px;
|
||||
}
|
||||
|
||||
.info-icon {
|
||||
display: inline-block;
|
||||
width: 1.1em;
|
||||
height: 1.1em;
|
||||
margin-right: 4px;
|
||||
vertical-align: middle;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.syntax-icon {
|
||||
background: url('data:image/svg+xml;utf8,<svg fill="none" stroke="%23aaa" stroke-width="2" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M7 7l-4 3 4 3M13 7l4 3-4 3"/></svg>') no-repeat center/1em 1em;
|
||||
}
|
||||
|
||||
.date-icon {
|
||||
background: url('data:image/svg+xml;utf8,<svg fill="none" stroke="%23aaa" stroke-width="2" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><circle cx="10" cy="10" r="8"/><path d="M10 6v4l2 2"/></svg>') no-repeat center/1em 1em;
|
||||
}
|
||||
|
||||
.size-icon {
|
||||
background: url('data:image/svg+xml;utf8,<svg fill="none" stroke="%23aaa" stroke-width="2" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><rect x="4" y="3" width="12" height="14" rx="2"/><path d="M10 7v5m0 0l-2-2m2 2l2-2"/></svg>') no-repeat center/1em 1em;
|
||||
}
|
||||
|
||||
.views-icon {
|
||||
background: url('data:image/svg+xml;utf8,<svg fill="none" stroke="%23aaa" stroke-width="2" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><ellipse cx="10" cy="10" rx="8" ry="5"/><circle cx="10" cy="10" r="2.5"/></svg>') no-repeat center/1em 1em;
|
||||
}
|
||||
|
||||
.author-icon {
|
||||
background: url('data:image/svg+xml;utf8,<svg fill="none" stroke="%23aaa" stroke-width="2" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><circle cx="10" cy="7.5" r="3.5"/><path d="M3 17c0-3.3 3.1-6 7-6s7 2.7 7 6"/></svg>') no-repeat center/1em 1em;
|
||||
}
|
||||
|
||||
.edit-icon {
|
||||
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-edit"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 7h-1a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-1" /><path d="M20.385 6.585a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3l8.385 -8.415z" /><path d="M16 5l3 3" /></svg>') no-repeat center/1em 1em;
|
||||
}
|
||||
|
||||
#password-modal-bg {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 101;
|
||||
}
|
||||
|
||||
#password-modal {
|
||||
background: var(--neutral-900);
|
||||
padding: 2em 2.5em 1.5em 2.5em;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 32px #000a;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
min-width: 320px;
|
||||
border: 1px solid var(--neutral-800);
|
||||
font-family: inherit;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#password-modal .modal-title {
|
||||
font-weight: bold;
|
||||
font-size: 1.2em;
|
||||
margin-bottom: 0.5em;
|
||||
letter-spacing: 0.5px;
|
||||
color: white
|
||||
}
|
||||
|
||||
#password-modal label {
|
||||
margin-bottom: 1em;
|
||||
color: white;
|
||||
font-size: 1em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#password-modal input[type="password"] {
|
||||
margin-bottom: 1em;
|
||||
padding: 0.7em 1em;
|
||||
width: 100%;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--neutral-900);
|
||||
background: var(--neutral-800);
|
||||
color: white;
|
||||
font-size: 1em;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
#password-modal input[type="password"]:focus {
|
||||
border-color: var(--neutral-700);
|
||||
}
|
||||
|
||||
#password-modal .modal-btn-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
gap: 0.5em;
|
||||
}
|
||||
|
||||
#password-modal button {
|
||||
padding: 0.5em 1.5em;
|
||||
border-radius: 4px;
|
||||
border: none;
|
||||
font-weight: bold;
|
||||
font-size: 1em;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
#password-modal button:first-child {
|
||||
background: var(--neutral-700);
|
||||
border: 1px solid var(--neutral-600);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#password-modal button:first-child:hover {
|
||||
background: var(--neutral-600);
|
||||
border: 1px solid var(--neutral-500);
|
||||
}
|
||||
|
||||
#password-modal button:last-child {
|
||||
background: var(--neutral-700);
|
||||
border: 1px solid var(--neutral-600);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
#password-modal button:last-child:hover {
|
||||
background: var(--neutral-600);
|
||||
border: 1px solid var(--neutral-500);
|
||||
}
|
||||
|
||||
.has-true-size-tooltip {
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.true-size-tooltip {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 120%;
|
||||
transform: translateX(-50%);
|
||||
background: var(--neutral-900, #23272e);
|
||||
color: var(--neutral-50, #fff);
|
||||
padding: 6px 14px;
|
||||
border-radius: 6px;
|
||||
font-size: 0.95em;
|
||||
white-space: nowrap;
|
||||
box-shadow: 0 2px 8px #0007;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.2s;
|
||||
z-index: 200;
|
||||
border: 1px solid var(--neutral-700, #444);
|
||||
}
|
||||
|
||||
.has-true-size-tooltip:hover .true-size-tooltip {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
|
||||
.main-container {
|
||||
max-height: 100% !important;
|
||||
}
|
||||
|
||||
#password-modal-bg {
|
||||
padding: 1em;
|
||||
}
|
||||
|
||||
#password-modal {
|
||||
padding: 1.5em 2em 1em 2em;
|
||||
min-width: auto;
|
||||
}
|
||||
|
||||
#paste-content {
|
||||
word-break: break-all;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.paste-actions {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.paste-actions button {
|
||||
width: 30%;
|
||||
margin: 0;
|
||||
margin-right: 2.5px;
|
||||
margin-left: 2.5px;
|
||||
}
|
||||
|
||||
.paste-information-card {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
font-family: "Noto Sans Mono", "Consolas", "SF Mono", monospace;
|
||||
color: white;
|
||||
}
|
||||
|
||||
:root {
|
||||
--neutral-50: #fafafa;
|
||||
--neutral-100: #f5f5f5;
|
||||
--neutral-200: #e5e5e5;
|
||||
--neutral-300: #d4d4d4;
|
||||
--neutral-400: #a3a3a3;
|
||||
--neutral-500: #737373;
|
||||
--neutral-600: #525252;
|
||||
--neutral-700: #404040;
|
||||
--neutral-800: #262626;
|
||||
--neutral-900: #171717;
|
||||
--neutral-950: #0a0a0a;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Roboto', sans-serif;
|
||||
background-color: var(--neutral-950);
|
||||
height: 100vh;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.main-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background-color: var(--neutral-900);
|
||||
padding: 20px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--neutral-800);
|
||||
width: 80%;
|
||||
}
|
||||
|
||||
.create-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.create-form input {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
margin: 5px 0;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--neutral-800);
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
transition: border 0.3s;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.create-form input:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.create-form input:hover {
|
||||
border: 1px solid var(--neutral-600);
|
||||
}
|
||||
|
||||
.create-form textarea {
|
||||
width: 100%;
|
||||
min-width: 100%;
|
||||
max-width: 100%;
|
||||
height: 2.5rem;
|
||||
min-height: 2.5rem;
|
||||
font-size: 1rem;
|
||||
max-height: 40%;
|
||||
padding: 10px;
|
||||
margin: 5px 0;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--neutral-800);
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
transition: border 0.3s;
|
||||
}
|
||||
|
||||
.create-form textarea:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.create-form textarea:hover {
|
||||
border: 1px solid var(--neutral-600);
|
||||
}
|
||||
|
||||
.create-form button {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
margin: 5px 0;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--neutral-800);
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
cursor: pointer;
|
||||
transition: background-color 0.3s;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.create-form button:hover {
|
||||
background-color: var(--neutral-700);
|
||||
}
|
||||
|
||||
select {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
margin: 5px 0;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--neutral-800);
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
transition: border 0.3s;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
select:hover {
|
||||
outline: none;
|
||||
border: 1px solid var(--neutral-600);
|
||||
}
|
||||
|
||||
select:focus {
|
||||
outline: none;
|
||||
border: 1px solid var(--neutral-600);
|
||||
}
|
||||
|
||||
#syntax {
|
||||
padding-left: 14rem;
|
||||
}
|
||||
|
||||
#syntax-label {
|
||||
margin-bottom: -2.3rem;
|
||||
margin-top: 1.1rem;
|
||||
z-index: 2;
|
||||
align-self: flex-start;
|
||||
margin-left: 1rem;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media screen and (max-width: 800px) {
|
||||
.main-container {
|
||||
width: 90%;
|
||||
}
|
||||
|
||||
.create-form textarea {
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
#syntax-label {
|
||||
margin-bottom: 0.5rem;
|
||||
margin-top: 0.5rem;
|
||||
margin-left: 0;
|
||||
text-align: center;
|
||||
align-self: center;
|
||||
max-width: 12rem;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
/*
|
||||
|
||||
possible style, just not good for small screens on desktop for some reason
|
||||
|
||||
margin-left: 6.7rem;
|
||||
max-width: 12rem;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
margin-bottom: -1.9rem;
|
||||
|
||||
*/
|
||||
}
|
||||
|
||||
#syntax {
|
||||
padding-left: 0.7rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
body,
|
||||
html {
|
||||
height: 100%;
|
||||
min-height: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.main-container {
|
||||
max-width: 600px;
|
||||
margin: 2.5rem auto;
|
||||
padding: 1.5rem 1.5rem 2.5rem 1.5rem;
|
||||
background-color: var(--neutral-900);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.18);
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.user-header {
|
||||
text-align: center;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.user-header h1 {
|
||||
font-size: 2.1rem;
|
||||
font-weight: 700;
|
||||
color: var(--neutral-50);
|
||||
margin: 0 0 0.2rem 0;
|
||||
}
|
||||
|
||||
.user-header p {
|
||||
color: var(--neutral-400);
|
||||
font-size: 1rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.user-pastes-section {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.archive-information {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr 1fr;
|
||||
gap: 1rem;
|
||||
padding: 0.75rem 1rem;
|
||||
margin-bottom: 1rem;
|
||||
background-color: var(--neutral-800);
|
||||
border-radius: 6px;
|
||||
font-weight: 600;
|
||||
color: var(--neutral-200);
|
||||
border-bottom: 2px solid var(--neutral-700);
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.archive-information p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.archive-list {
|
||||
list-style-type: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
width: 100%;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
border-radius: 6px;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--neutral-700) var(--neutral-900);
|
||||
}
|
||||
|
||||
.archive-list::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
.archive-list::-webkit-scrollbar-track {
|
||||
background: var(--neutral-900);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.archive-list::-webkit-scrollbar-thumb {
|
||||
background-color: var(--neutral-700);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
.archive-list li {
|
||||
margin: 0.75rem 0;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.archive-list li:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.archive-list li a {
|
||||
display: grid;
|
||||
grid-template-columns: 2fr 1fr 1fr;
|
||||
gap: 1rem;
|
||||
padding: 1rem 1.25rem;
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
text-decoration: none;
|
||||
transition: all 0.3s ease;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.archive-list li a:hover {
|
||||
background-color: var(--neutral-750);
|
||||
border-color: var(--neutral-600);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.archive-list li a p {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.archive-list li a p:nth-child(2) {
|
||||
padding-left: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.archive-list li a p:nth-child(3) {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
#archive-title {
|
||||
font-weight: 500;
|
||||
color: var(--neutral-100);
|
||||
}
|
||||
|
||||
#archive-date {
|
||||
color: var(--neutral-300);
|
||||
font-size: 0.9rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#archive-syntax {
|
||||
color: var(--neutral-300);
|
||||
font-size: 0.9rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.user-pastes-throbber {
|
||||
margin: 1.5rem auto;
|
||||
}
|
||||
|
||||
.pastes-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 1.2rem;
|
||||
margin-top: 1.2rem;
|
||||
}
|
||||
|
||||
.pastes-actions button:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.pastes-actions span {
|
||||
color: var(--neutral-300);
|
||||
font-size: 1.1rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.main-container {
|
||||
max-width: 98vw;
|
||||
min-width: 0;
|
||||
padding: 0.5rem;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.archive-list li a p:last-child {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.archive-information,
|
||||
.archive-list li a {
|
||||
grid-template-columns: 3fr 2fr;
|
||||
}
|
||||
|
||||
#archive-syntax {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.archive-information p:last-child {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.main-container {
|
||||
padding: 1rem;
|
||||
margin: 1rem;
|
||||
}
|
||||
|
||||
.user-header h1 {
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.archive-list {
|
||||
max-height: 60vh;
|
||||
}
|
||||
}
|
||||
|
||||
#next-button-svg {
|
||||
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M310.6 233.4c12.5 12.5 12.5 32.8 0 45.3l-192 192c-12.5 12.5-32.8 12.5-45.3 0s-12.5-32.8 0-45.3L242.7 256 73.4 86.6c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l192 192z"/></svg>');
|
||||
color: white;
|
||||
width: 1.5em;
|
||||
height: 1.5em;
|
||||
background-size: contain;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
filter: invert(100%);
|
||||
}
|
||||
|
||||
#previous-button-svg {
|
||||
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--!Font Awesome Free 6.7.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.--><path d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l192 192c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L77.3 256l169.3-169.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-192 192z"/></svg>');
|
||||
color: white;
|
||||
width: 1.5em;
|
||||
height: 1.5em;
|
||||
background-size: contain;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center;
|
||||
filter: invert(100%);
|
||||
}
|
||||
|
||||
.pastes-actions button {
|
||||
padding: 0.4rem 0.8rem;
|
||||
border-radius: 6px;
|
||||
border: 1px solid var(--neutral-700);
|
||||
background-color: var(--neutral-800);
|
||||
color: var(--neutral-50);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
font-size: 1rem;
|
||||
min-width: 75px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Dashboard - Sharpbin</title>
|
||||
<link rel="preload" href="css/style.css" as="style">
|
||||
<link rel="preload" href="css/dash.css" as="style">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<link rel="stylesheet" href="css/dash.css">
|
||||
<link rel="preload" href="js/dash.js" as="script">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
|
||||
rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="main-container">
|
||||
<div class="account-info">
|
||||
<h1 id="account-header">Account Information</h1>
|
||||
<p id="account-username">Username: </p>
|
||||
<p id="account-email">Email: </p>
|
||||
<p id="account-joindate">Joined: </p>
|
||||
<p id="account-lastlogin">Last Login: </p>
|
||||
<p id="account-pastes">Pastes: </p>
|
||||
<button id="logout-button" onclick="logout()">Logout</button>
|
||||
<button id="delete-account-button" onclick="deleteAccount()">Delete Account</button>
|
||||
</div>
|
||||
<div class="paste-list">
|
||||
<h1 id="paste-header">Your Pastes</h1>
|
||||
<div class="paste-information">
|
||||
<p id="paste-title">Title</p>
|
||||
<p id="paste-date">Date</p>
|
||||
<p id="paste-syntax">Syntax</p>
|
||||
</div>
|
||||
<ol class="pastes" id="pastes">
|
||||
|
||||
</ol>
|
||||
<div class="paste-actions">
|
||||
<button id="previous-button" onclick="previousPage()"><</button>
|
||||
<p id="paste-pages">0/0</p>
|
||||
<button id="next-button" onclick="nextPage()">></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<script src="js/modal.js"></script>
|
||||
<script src="js/dash.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</html>
|
||||
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Error! - Sharpbin</title>
|
||||
<link rel="preload" href="css/style.css" as="style">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<link rel="preload" href="js/error.js" as="script">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
|
||||
rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div class="main-container">
|
||||
<h1 id="error-header">Oops! We've ran into an error.</h1>
|
||||
<h3 id="error-message"></p>
|
||||
</div>
|
||||
</body>
|
||||
<script src="js/error.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,63 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Sharpbin</title>
|
||||
<link rel="preload" href="css/style.css" as="style">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<link rel="preload" href="js/index.js" as="script">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
|
||||
rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="main-container">
|
||||
<form class="create-form" id="create-form">
|
||||
<input type="text" name="title" id="title" placeholder="Title" maxlength="500" autocomplete="off" spellcheck="false">
|
||||
<textarea name="content" id="content" placeholder="Content" autocomplete="off" spellcheck="false"></textarea>
|
||||
<label id="syntax-label">Syntax Highlighting -</label>
|
||||
<select name="syntax" id="syntax">
|
||||
<option value="none">None</option>
|
||||
<option value="AutoHotkey">AutoHotkey</option>
|
||||
<option value="AutoIt">AutoIt</option>
|
||||
<option value="bash">Bash</option>
|
||||
<option value="c">C</option>
|
||||
<option value="cpp">C++</option>
|
||||
<option value="csharp">C#</option>
|
||||
<option value="css">CSS</option>
|
||||
<option value="Dart">Dart</option>
|
||||
<option value="html">HTML</option>
|
||||
<option value="java">Java</option>
|
||||
<option value="javascript">JavaScript</option>
|
||||
<option value="json">JSON</option>
|
||||
<option value="lua">Lua</option>
|
||||
<option value="markdown">Markdown</option>
|
||||
<option value="php">PHP</option>
|
||||
<option value="python">Python</option>
|
||||
<option value="ruby">Ruby</option>
|
||||
<option value="rust">Rust</option>
|
||||
<option value="sql">SQL</option>
|
||||
<option value="swift">Swift</option>
|
||||
<option value="typescript">TypeScript</option>
|
||||
<option value="toml">TOML/Ini</option>
|
||||
<option value="xml">XML</option>
|
||||
</select>
|
||||
<select name="visibility" id="visibility" onchange="changeVisibility()">
|
||||
<option value="0">Public</option>
|
||||
<option value="1">Unlisted</option>
|
||||
<option value="2">Private</option>
|
||||
</select>
|
||||
<input type="password" name="password" id="password" placeholder="Password" style="display: none;" autocomplete="off" spellcheck="false">
|
||||
<button type="submit">Create Paste</button>
|
||||
</form>
|
||||
</div>
|
||||
</body>
|
||||
<script src="js/main.js"></script>
|
||||
<script src="js/index.js"></script>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,145 @@
|
||||
let pages = 1;
|
||||
let currentPage = 1;
|
||||
let limit = 25;
|
||||
|
||||
async function renderArchive(page, limit) {
|
||||
const archiveList = document.getElementById("archives");
|
||||
const pagesElement = document.getElementById("paste-pages");
|
||||
const previousButton = document.getElementById("previous-button");
|
||||
const nextButton = document.getElementById("next-button");
|
||||
|
||||
let loadingOverlay = document.getElementById("archive-loading-overlay");
|
||||
if (!loadingOverlay) {
|
||||
loadingOverlay = document.createElement("div");
|
||||
loadingOverlay.id = "archive-loading-overlay";
|
||||
loadingOverlay.innerHTML = '<div class="loading-spinner"><div></div><div></div><div></div></div>';
|
||||
loadingOverlay.style.position = "absolute";
|
||||
loadingOverlay.style.top = 0;
|
||||
loadingOverlay.style.left = 0;
|
||||
loadingOverlay.style.width = "100%";
|
||||
loadingOverlay.style.height = "100%";
|
||||
loadingOverlay.style.display = "flex";
|
||||
loadingOverlay.style.justifyContent = "center";
|
||||
loadingOverlay.style.alignItems = "center";
|
||||
loadingOverlay.style.background = "transparent";
|
||||
loadingOverlay.style.zIndex = 10;
|
||||
archiveList.parentElement.style.position = "relative";
|
||||
archiveList.parentElement.appendChild(loadingOverlay);
|
||||
} else {
|
||||
loadingOverlay.style.display = "flex";
|
||||
}
|
||||
|
||||
try {
|
||||
const archiveData = await getPastes(page, limit);
|
||||
const pastes = archiveData.pastes;
|
||||
pages = archiveData.pages;
|
||||
currentPage = page;
|
||||
|
||||
pagesElement.innerText = `${page}/${pages}`;
|
||||
previousButton.disabled = page <= 1;
|
||||
nextButton.disabled = page >= pages;
|
||||
|
||||
let archiveListHTML = "";
|
||||
if (pastes.length === 0) {
|
||||
archiveListHTML = '<div class="no-pastes">No pastes found</div>';
|
||||
} else {
|
||||
pastes.forEach(paste => {
|
||||
const title = paste.title.length > 30 ? paste.title.substring(0, 30) + '...' : paste.title;
|
||||
archiveListHTML += `
|
||||
<li>
|
||||
<a href="/${paste.id}">
|
||||
<p id="archive-title" title="${paste.title}">${title}</p>
|
||||
<p id="archive-date" title="${formatDate(paste.created)}">${formatDate(paste.created, true)}</p>
|
||||
<p id="archive-syntax">${paste.syntax || 'Plain Text'}</p>
|
||||
</a>
|
||||
</li>
|
||||
`;
|
||||
});
|
||||
}
|
||||
archiveList.innerHTML = archiveListHTML;
|
||||
} catch (error) {
|
||||
console.error('Error fetching pastes:', error);
|
||||
archiveList.innerHTML = '<div class="error-message">Failed to load pastes. Please try again later.</div>';
|
||||
} finally {
|
||||
if (loadingOverlay) loadingOverlay.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
const queries = new URLSearchParams(window.location.search);
|
||||
let page = parseInt(queries.get("page"));
|
||||
limit = parseInt(queries.get("limit"));
|
||||
|
||||
if (isNaN(page) || page < 1) page = 1;
|
||||
if (isNaN(limit) || limit < 1 || limit > 25) limit = 25;
|
||||
|
||||
await renderArchive(page, limit);
|
||||
|
||||
document.getElementById("previous-button").addEventListener("click", previousPage);
|
||||
document.getElementById("next-button").addEventListener("click", nextPage);
|
||||
});
|
||||
|
||||
async function getPastes(page, limit) {
|
||||
const response = await fetch(`/api/pastes/archive?page=${page}&limit=${limit}`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
return data;
|
||||
}
|
||||
|
||||
function getRelativeTime(date) {
|
||||
const now = new Date();
|
||||
const diff = now - date;
|
||||
const seconds = Math.floor(diff / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
if (isNaN(date.getTime())) return '';
|
||||
if (seconds < 60) return 'just now';
|
||||
if (minutes < 60) return `${minutes} min ago`;
|
||||
if (hours < 24) return `${hours} hr${hours > 1 ? 's' : ''} ago`;
|
||||
if (days < 7) return `${days} day${days > 1 ? 's' : ''} ago`;
|
||||
return date.toLocaleDateString();
|
||||
}
|
||||
|
||||
|
||||
function formatDate(unix, relative = false) {
|
||||
if (typeof unix !== 'number' || isNaN(unix)) {
|
||||
return 'Invalid date';
|
||||
}
|
||||
const date = new Date(unix * 1000);
|
||||
if (isNaN(date.getTime())) {
|
||||
return 'Invalid date';
|
||||
}
|
||||
if (relative) {
|
||||
return getRelativeTime(date);
|
||||
}
|
||||
return date.toLocaleDateString([], { year: 'numeric', month: '2-digit', day: '2-digit' });
|
||||
}
|
||||
|
||||
function nextPage() {
|
||||
if (currentPage >= pages) return;
|
||||
currentPage++;
|
||||
updateUrlAndRender();
|
||||
}
|
||||
|
||||
function previousPage() {
|
||||
if (currentPage <= 1) return;
|
||||
currentPage--;
|
||||
updateUrlAndRender();
|
||||
}
|
||||
|
||||
function updateUrlAndRender() {
|
||||
const url = `/archive?page=${currentPage}&limit=${limit}`;
|
||||
window.history.pushState({page: currentPage, limit: limit}, '', url);
|
||||
renderArchive(currentPage, limit);
|
||||
}
|
||||
|
||||
window.onpopstate = function(event) {
|
||||
if (event.state) {
|
||||
currentPage = event.state.page;
|
||||
limit = event.state.limit;
|
||||
renderArchive(currentPage, limit);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,268 @@
|
||||
let currentPage = 1;
|
||||
let totalPages = 1;
|
||||
let pastesPerPage = 10;
|
||||
let userPastes = [];
|
||||
|
||||
const userTypes = {
|
||||
"Admin": 255,
|
||||
"User": 0
|
||||
};
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
waitForAuthData().then(data => {
|
||||
if (data.success === false) {
|
||||
window.location.href = '/login';
|
||||
} else {
|
||||
updateAccountInfo(data.user);
|
||||
fetchUserPastes();
|
||||
}
|
||||
}).catch(error => {
|
||||
console.error('Error waiting for auth data:', error);
|
||||
window.location.href = '/login';
|
||||
});
|
||||
});
|
||||
|
||||
function waitForAuthData() {
|
||||
return new Promise(resolve => {
|
||||
const interval = setInterval(() => {
|
||||
if (authData) {
|
||||
clearInterval(interval);
|
||||
resolve(authData);
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
}
|
||||
|
||||
function updateAccountInfo(data) {
|
||||
document.getElementById('account-username').textContent = `Username: ${data.username}`;
|
||||
document.getElementById('account-email').textContent = `Email: ${data.email || 'Not provided'}`;
|
||||
|
||||
|
||||
if (data.displayname) {
|
||||
const usernameElement = document.getElementById('account-header');
|
||||
usernameElement.textContent = data.displayname;
|
||||
}
|
||||
|
||||
|
||||
const createdDate = new Date(data.created * 1000);
|
||||
const lastLoginDate = new Date(data.lastLogin * 1000);
|
||||
|
||||
document.getElementById('account-joindate').textContent = `Joined: ${formatDate(createdDate)}`;
|
||||
document.getElementById('account-lastlogin').textContent = `Last Login: ${formatDate(lastLoginDate)}`;
|
||||
}
|
||||
|
||||
|
||||
function formatDate(date, minutes = false) {
|
||||
if (isNaN(date.getTime())) {
|
||||
return 'Never';
|
||||
}
|
||||
|
||||
if (minutes)
|
||||
{
|
||||
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { minute: '2-digit', hour: '2-digit' });
|
||||
} else {
|
||||
return date.toLocaleDateString([], { year: 'numeric', month: '2-digit', day: '2-digit' });
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchUserPastes() {
|
||||
try {
|
||||
const response = await fetch('/api/pastes/my?page=1&limit=15');
|
||||
const pastesData = await response.json();
|
||||
|
||||
if (pastesData.message === 'No pastes found.' || pastesData.message === 'Page out of range.') {
|
||||
userPastes = [];
|
||||
document.getElementById('account-pastes').textContent = `Pastes: 0`;
|
||||
totalPages = 0;
|
||||
document.getElementById('paste-pages').textContent = `0/0`;
|
||||
displayPastes();
|
||||
return;
|
||||
}
|
||||
|
||||
userPastes = pastesData.pastes;
|
||||
document.getElementById('account-pastes').textContent = `Pastes: ${userPastes.length}`;
|
||||
totalPages = Math.ceil(userPastes.length / pastesPerPage);
|
||||
document.getElementById('paste-pages').textContent = `${currentPage}/${totalPages || 1}`;
|
||||
displayPastes();
|
||||
} catch (error) {
|
||||
console.error('Error fetching user pastes:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function displayPastes() {
|
||||
const pastesList = document.getElementById('pastes');
|
||||
pastesList.innerHTML = '';
|
||||
|
||||
|
||||
const pasteInfoHeader = document.querySelector('.paste-information');
|
||||
const pasteActions = document.querySelector('.paste-actions');
|
||||
const prevButton = document.getElementById('previous-button');
|
||||
const nextButton = document.getElementById('next-button');
|
||||
|
||||
|
||||
if (userPastes.length === 0) {
|
||||
if (pasteInfoHeader) pasteInfoHeader.style.display = 'none';
|
||||
if (pasteActions) pasteActions.style.display = 'none';
|
||||
if (prevButton) prevButton.disabled = true;
|
||||
if (nextButton) nextButton.disabled = true;
|
||||
const noItems = document.createElement('li');
|
||||
noItems.textContent = 'No pastes found';
|
||||
pastesList.appendChild(noItems);
|
||||
return;
|
||||
} else {
|
||||
if (pasteInfoHeader) pasteInfoHeader.style.display = '';
|
||||
if (pasteActions) pasteActions.style.display = '';
|
||||
}
|
||||
|
||||
|
||||
if (prevButton) prevButton.disabled = currentPage <= 1;
|
||||
if (nextButton) nextButton.disabled = currentPage >= totalPages || totalPages <= 1;
|
||||
|
||||
|
||||
const startIndex = (currentPage - 1) * pastesPerPage;
|
||||
const endIndex = Math.min(startIndex + pastesPerPage, userPastes.length);
|
||||
|
||||
|
||||
for (let i = startIndex; i < endIndex; i++) {
|
||||
const paste = userPastes[i];
|
||||
const pasteItem = document.createElement('li');
|
||||
|
||||
|
||||
const pasteLink = document.createElement('a');
|
||||
pasteLink.href = `/${paste.id}`;
|
||||
|
||||
pasteLink.style.display = 'grid';
|
||||
pasteLink.style.gridTemplateColumns = '2fr 1fr 1fr';
|
||||
pasteLink.style.gap = '1rem';
|
||||
|
||||
|
||||
const titleP = document.createElement('p');
|
||||
titleP.id = 'paste-title';
|
||||
titleP.textContent = paste.title || 'Untitled';
|
||||
|
||||
|
||||
const dateP = document.createElement('p');
|
||||
dateP.id = 'paste-date';
|
||||
const createdDate = new Date(paste.created * 1000);
|
||||
dateP.textContent = `${formatDate(createdDate)}`;
|
||||
|
||||
|
||||
const syntaxP = document.createElement('p');
|
||||
syntaxP.id = 'paste-syntax';
|
||||
syntaxP.textContent = paste.syntax || 'plaintext';
|
||||
|
||||
pasteLink.appendChild(titleP);
|
||||
pasteLink.appendChild(dateP);
|
||||
pasteLink.appendChild(syntaxP);
|
||||
pasteItem.appendChild(pasteLink);
|
||||
pastesList.appendChild(pasteItem);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function previousPage() {
|
||||
if (currentPage > 1) {
|
||||
currentPage--;
|
||||
document.getElementById('paste-pages').textContent = `${currentPage}/${totalPages || 1}`;
|
||||
displayPastes();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function nextPage() {
|
||||
if (currentPage < totalPages) {
|
||||
currentPage++;
|
||||
document.getElementById('paste-pages').textContent = `${currentPage}/${totalPages || 1}`;
|
||||
displayPastes();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function logout() {
|
||||
const confirmed = await Modal.confirm(
|
||||
"Are you sure you want to log out?",
|
||||
"Confirm Logout",
|
||||
"danger"
|
||||
);
|
||||
|
||||
if (confirmed) {
|
||||
try {
|
||||
await fetch('/api/auth/logout', { method: 'POST' });
|
||||
} catch { }
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function deleteAccount() {
|
||||
const username = document.getElementById('account-username').textContent.replace('Username: ', '').trim();
|
||||
const pasteCount = userPastes.length;
|
||||
|
||||
const customContent = document.createElement('div');
|
||||
customContent.innerHTML = `
|
||||
<p style="color: var(--text-color); margin-bottom: 1rem; line-height: 1.6;">
|
||||
This action is <strong>irreversible</strong> and will delete your account and all your ${pasteCount} pastes.
|
||||
</p>
|
||||
<p style="color: var(--text-color); margin-bottom: 1.5rem;">
|
||||
To confirm, type your username <strong>${username}</strong> and your paste count <strong>${pasteCount}</strong>:
|
||||
</p>
|
||||
<div style="margin-bottom: 1rem;">
|
||||
<label class="modal-label">Username:</label>
|
||||
<input type="text" id="delete-username" class="modal-input" placeholder="Username">
|
||||
</div>
|
||||
<div style="margin-bottom: 1.5rem;">
|
||||
<label class="modal-label">Paste count:</label>
|
||||
<input type="number" id="delete-pastecount" class="modal-input" placeholder="Paste count">
|
||||
</div>
|
||||
<div style="display: flex; gap: 0.75rem; justify-content: flex-end;">
|
||||
<button class="btn btn-secondary delete-cancel">Cancel</button>
|
||||
<button class="btn btn-danger delete-confirm" disabled>Delete Account</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const { body, close } = Modal.custom(customContent, {
|
||||
title: 'Delete Account',
|
||||
className: 'modal-delete-account'
|
||||
});
|
||||
|
||||
const userInput = customContent.querySelector('#delete-username');
|
||||
const countInput = customContent.querySelector('#delete-pastecount');
|
||||
const confirmBtn = customContent.querySelector('.delete-confirm');
|
||||
const cancelBtn = customContent.querySelector('.delete-cancel');
|
||||
|
||||
function validateInputs() {
|
||||
const usernameValid = userInput.value.trim() === username;
|
||||
const countValid = countInput.value.trim() === String(pasteCount);
|
||||
|
||||
if (usernameValid && countValid) {
|
||||
confirmBtn.disabled = false;
|
||||
confirmBtn.style.opacity = '1';
|
||||
} else {
|
||||
confirmBtn.disabled = true;
|
||||
confirmBtn.style.opacity = '0.6';
|
||||
}
|
||||
}
|
||||
|
||||
validateInputs();
|
||||
|
||||
userInput.addEventListener('input', validateInputs);
|
||||
countInput.addEventListener('input', validateInputs);
|
||||
|
||||
cancelBtn.onclick = () => close();
|
||||
|
||||
confirmBtn.onclick = async function () {
|
||||
if (confirmBtn.disabled) return;
|
||||
|
||||
if (userInput.value.trim() !== username || countInput.value.trim() !== String(pasteCount)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await fetch('/api/auth/delete', { method: 'DELETE' });
|
||||
} catch { }
|
||||
window.location.href = '/register';
|
||||
};
|
||||
|
||||
setTimeout(() => userInput.focus(), 100);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
const errors = {
|
||||
"400": "You've made a bad request.",
|
||||
"401": "You are unauthorized to access this page.",
|
||||
"403": "Forbidden! You don't have permission.",
|
||||
"404": "Page not found.",
|
||||
"500": "Internal server error.",
|
||||
};
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
var queries = new URLSearchParams(window.location.search);
|
||||
var error = queries.get("error");
|
||||
var message = queries.get("message");
|
||||
var errorElement = document.getElementById("error-header");
|
||||
var messageElement = document.getElementById("error-message");
|
||||
|
||||
if (error != null) {
|
||||
errorElement.innerText = errors[error];
|
||||
}
|
||||
if (message != null) {
|
||||
messageElement.innerText = message;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
const siteInfo = [];
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async function () {
|
||||
var visibility = document.getElementById("visibility");
|
||||
visibility.value = "0";
|
||||
getSiteInfo();
|
||||
});
|
||||
|
||||
|
||||
document.getElementById("create-form").addEventListener("submit", async function (event) {
|
||||
event.preventDefault();
|
||||
var title = document.getElementById("title").value;
|
||||
var content = document.getElementById("content").value;
|
||||
|
||||
var visibility = document.getElementById("visibility").value;
|
||||
var password = document.getElementById("password").value;
|
||||
var syntax = document.getElementById("syntax").value;
|
||||
|
||||
if (content.length > siteInfo.maxFileSize) {
|
||||
showNotification("Content exceeds maximum size.", "error");
|
||||
return;
|
||||
}
|
||||
if (content.length === 0) {
|
||||
showNotification("Content cannot be empty.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (visibility === "2" && password !== "" && password.length >= 6) {
|
||||
content = await encryptAES(content, password);
|
||||
}
|
||||
else if (visibility === "2") {
|
||||
showNotification("Password must be at least 6 characters long.", "error");
|
||||
return;
|
||||
}
|
||||
|
||||
fetch(`/api/pastes/create?title=${title}&visibility=${visibility}&syntax=${syntax}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'text/plain'
|
||||
},
|
||||
body: content
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const paste = data.paste;
|
||||
window.location.href = `/${paste.id}`;
|
||||
});
|
||||
});
|
||||
|
||||
function changeVisibility() {
|
||||
var visibility = document.getElementById("visibility").value;
|
||||
var password = document.getElementById("password");
|
||||
if (visibility === "2") {
|
||||
password.style.display = "block";
|
||||
} else {
|
||||
password.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
function getSiteInfo() {
|
||||
fetch("/api/site/info")
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
siteInfo = data.info;
|
||||
var content = document.getElementById("content")
|
||||
content.setAttribute("maxlength", siteInfo.maxFileSize);
|
||||
});
|
||||
}
|
||||
|
||||
async function encryptAES(content, password) {
|
||||
const enc = new TextEncoder();
|
||||
|
||||
const salt = crypto.getRandomValues(new Uint8Array(16));
|
||||
|
||||
const keyMaterial = await window.crypto.subtle.importKey(
|
||||
"raw",
|
||||
enc.encode(password),
|
||||
{ name: "PBKDF2" },
|
||||
false,
|
||||
["deriveKey"]
|
||||
);
|
||||
const key = await window.crypto.subtle.deriveKey(
|
||||
{
|
||||
name: "PBKDF2",
|
||||
salt: salt,
|
||||
iterations: 100000,
|
||||
hash: "SHA-256"
|
||||
},
|
||||
keyMaterial,
|
||||
{ name: "AES-GCM", length: 256 },
|
||||
false,
|
||||
["encrypt"]
|
||||
);
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const encryptedContent = await window.crypto.subtle.encrypt(
|
||||
{
|
||||
name: "AES-GCM",
|
||||
iv: iv
|
||||
},
|
||||
key,
|
||||
enc.encode(content)
|
||||
);
|
||||
|
||||
const combined = new Uint8Array(salt.length + iv.length + encryptedContent.byteLength);
|
||||
combined.set(salt, 0);
|
||||
combined.set(iv, salt.length);
|
||||
combined.set(new Uint8Array(encryptedContent), salt.length + iv.length);
|
||||
|
||||
return btoa(String.fromCharCode.apply(null, combined));
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const loginForm = document.getElementById('login-form');
|
||||
const errorMessage = document.getElementById('error-message');
|
||||
|
||||
|
||||
checkAuthStatus();
|
||||
|
||||
loginForm.addEventListener('submit', async function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
|
||||
if (!username || !password) {
|
||||
showError('Please fill in all required fields');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
const submitButton = loginForm.querySelector('button[type="submit"]');
|
||||
const originalButtonText = submitButton.textContent;
|
||||
submitButton.disabled = true;
|
||||
submitButton.textContent = 'Logging in...';
|
||||
|
||||
|
||||
const isEmail = username.includes('@');
|
||||
const requestData = isEmail
|
||||
? { email: username, password: password }
|
||||
: { username: username, password: password };
|
||||
|
||||
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(requestData)
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
|
||||
window.location.href = '/dash';
|
||||
} else {
|
||||
showError(data.message || 'Login failed. Please check your credentials.');
|
||||
submitButton.disabled = false;
|
||||
submitButton.textContent = originalButtonText;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
showError('An unexpected error occurred. Please try again later.');
|
||||
|
||||
const submitButton = loginForm.querySelector('button[type="submit"]');
|
||||
submitButton.disabled = false;
|
||||
submitButton.textContent = 'Login';
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
function showError(message) {
|
||||
errorMessage.textContent = message;
|
||||
errorMessage.classList.add('visible');
|
||||
|
||||
|
||||
setTimeout(() => {
|
||||
errorMessage.classList.remove('visible');
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
|
||||
async function checkAuthStatus() {
|
||||
try {
|
||||
const response = await fetch('/api/auth/authenticated');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
|
||||
window.location.href = '/dash';
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
console.log('Not logged in');
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,310 @@
|
||||
const navbarHTML = `
|
||||
<div class="nav-bar">
|
||||
<div class="nav-brand">
|
||||
<a href="/" class="brand-link">Sharpbin</a>
|
||||
</div>
|
||||
<div class="nav-center">
|
||||
<div class="nav-links">
|
||||
<a href="/archive" class="nav-link">Archives</a>
|
||||
<a href="/" class="nav-link home-link">Home</a>
|
||||
<a href="#" class="nav-link">Account</a>
|
||||
</div>
|
||||
</div>
|
||||
<button class="hamburger" onclick="toggleMenu()" aria-label="Toggle menu">
|
||||
<span class="hamburger-line"></span>
|
||||
<span class="hamburger-line"></span>
|
||||
<span class="hamburger-line"></span>
|
||||
</button>
|
||||
<style>
|
||||
.nav-bar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 0.75rem 2rem;
|
||||
background-color: var(--neutral-900);
|
||||
color: #fff;
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
top: 0;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.nav-brand {
|
||||
flex: 0 0 auto;
|
||||
z-index: 15;
|
||||
}
|
||||
|
||||
.brand-link {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
letter-spacing: 0.5px;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.brand-link:hover {
|
||||
transform: scale(1.05);
|
||||
}
|
||||
|
||||
.nav-center {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
background-color: #171717;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
text-decoration: none;
|
||||
font-size: 1.1rem;
|
||||
padding: 0.6rem 1.2rem;
|
||||
border-radius: 6px;
|
||||
transition: all 0.3s ease;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
max-width: 125px;
|
||||
width: 125px;
|
||||
}
|
||||
|
||||
.nav-link:hover {
|
||||
color: #fff;
|
||||
background-color: rgba(255, 255, 255, 0.1);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
#nav-bar-selected {
|
||||
color: #fff;
|
||||
background-color: rgba(255, 255, 255, 0.15);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.hamburger {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
width: 30px;
|
||||
height: 21px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
z-index: 15;
|
||||
}
|
||||
|
||||
.hamburger-line {
|
||||
display: block;
|
||||
height: 3px;
|
||||
width: 100%;
|
||||
border-radius: 10px;
|
||||
background: #fff;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.nav-center {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.nav-links {
|
||||
position: fixed;
|
||||
top: 55px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background-color: var(--neutral-900);
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 0;
|
||||
max-height: 0;
|
||||
overflow: hidden;
|
||||
transition: max-height 0.3s ease-out, padding 0.3s ease;
|
||||
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.nav-links.show {
|
||||
max-height: 350px;
|
||||
padding: 1rem 0;
|
||||
padding-bottom: 2rem;
|
||||
}
|
||||
|
||||
.nav-link {
|
||||
width: 90%;
|
||||
max-width: 90%;
|
||||
text-align: center;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.home-link {
|
||||
order: -1;
|
||||
}
|
||||
|
||||
.hamburger {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.hamburger.active .hamburger-line:nth-child(1) {
|
||||
transform: translateY(9px) rotate(45deg);
|
||||
}
|
||||
|
||||
.hamburger.active .hamburger-line:nth-child(2) {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.hamburger.active .hamburger-line:nth-child(3) {
|
||||
transform: translateY(-9px) rotate(-45deg);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</div>
|
||||
`;
|
||||
|
||||
let authData = null;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
document.body.insertAdjacentHTML('afterbegin', navbarHTML);
|
||||
var path = window.location.pathname;
|
||||
var links = document.querySelectorAll('.nav-link');
|
||||
|
||||
let accountHref = '/login';
|
||||
try {
|
||||
const resp = await fetch('/api/auth/authenticated');
|
||||
const data = await resp.json();
|
||||
authData = data;
|
||||
if (data && data.success !== false) {
|
||||
accountHref = '/dash';
|
||||
}
|
||||
} catch {}
|
||||
|
||||
const accountLink = document.querySelector('.nav-link[href="#"]');
|
||||
if (accountLink) {
|
||||
accountLink.setAttribute('href', accountHref);
|
||||
}
|
||||
|
||||
links.forEach(link => {
|
||||
const href = link.getAttribute('href');
|
||||
if (href === path) {
|
||||
link.id = 'nav-bar-selected';
|
||||
}
|
||||
|
||||
if ((path === '/dash' || path === '/login' || path === '/register') && (href === '/dash' || href === '/login')) {
|
||||
link.id = 'nav-bar-selected';
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
window.toggleMenu = function () {
|
||||
const nav = document.querySelector('.nav-links');
|
||||
const hamburger = document.querySelector('.hamburger');
|
||||
nav.classList.toggle('show');
|
||||
hamburger.classList.toggle('active');
|
||||
};
|
||||
|
||||
function showNotification(message, type = 'info', duration = 3000) {
|
||||
if (!document.getElementById('notification-style')) {
|
||||
const style = document.createElement('style');
|
||||
style.id = 'notification-style';
|
||||
style.textContent = `
|
||||
.notification-container {
|
||||
position: fixed;
|
||||
bottom: 32px;
|
||||
right: 32px;
|
||||
z-index: 1000;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.notification {
|
||||
min-width: 240px;
|
||||
max-width: 350px;
|
||||
padding: 12px 20px;
|
||||
border-radius: 8px;
|
||||
color: #ef4444;
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
box-shadow: 0 6px 24px rgba(0,0,0,0.28);
|
||||
margin-top: 0.5rem;
|
||||
opacity: 0;
|
||||
transform: translateY(20px);
|
||||
animation: notification-in 0.3s forwards;
|
||||
border: 1px solid rgba(220, 38, 38, 0.2);
|
||||
background: rgba(220, 38, 38, 0.1);
|
||||
letter-spacing: 0.01em;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75em;
|
||||
}
|
||||
.notification-info {
|
||||
color: #e5e7eb;
|
||||
background: var(--neutral-900, #181a20);
|
||||
border: 1px solid var(--neutral-800, #23272f);
|
||||
}
|
||||
.notification-warning {
|
||||
color: #f59e42;
|
||||
background: rgba(245, 158, 66, 0.10);
|
||||
border: 1px solid rgba(245, 158, 66, 0.18);
|
||||
}
|
||||
.notification-error {
|
||||
color: #ef4444;
|
||||
background: rgba(220, 38, 38, 0.1);
|
||||
border: 1px solid rgba(220, 38, 38, 0.2);
|
||||
}
|
||||
@keyframes notification-in {
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.notification-container {
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
}
|
||||
.notification {
|
||||
min-width: 160px;
|
||||
max-width: 90vw;
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
let container = document.querySelector('.notification-container');
|
||||
if (!container) {
|
||||
container = document.createElement('div');
|
||||
container.className = 'notification-container';
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
|
||||
const notif = document.createElement('div');
|
||||
notif.className = `notification notification-${type}`;
|
||||
notif.textContent = message;
|
||||
container.appendChild(notif);
|
||||
|
||||
setTimeout(() => {
|
||||
notif.style.opacity = '0';
|
||||
notif.style.transform = 'translateY(20px)';
|
||||
setTimeout(() => {
|
||||
notif.remove();
|
||||
if (container.childElementCount === 0) {
|
||||
container.remove();
|
||||
}
|
||||
}, 300);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,707 @@
|
||||
const Modal = {
|
||||
createModal(options = {}) {
|
||||
const {
|
||||
id = 'modal-' + Date.now(),
|
||||
title = '',
|
||||
className = '',
|
||||
closable = true,
|
||||
backdrop = true,
|
||||
noAnimation = false
|
||||
} = options;
|
||||
|
||||
this.removeModal(id);
|
||||
|
||||
const modalBg = this.createElement('div', {
|
||||
id: id + '-bg',
|
||||
className: `modal-backdrop ${className} ${noAnimation ? 'no-animation' : ''}`,
|
||||
style: backdrop ? '' : 'pointer-events: none;'
|
||||
});
|
||||
|
||||
const modal = this.createElement('div', {
|
||||
className: `modal ${noAnimation ? 'no-animation' : ''}`,
|
||||
style: 'pointer-events: auto;'
|
||||
});
|
||||
|
||||
if (title) {
|
||||
const header = this.createElement('div', {
|
||||
className: 'modal-header',
|
||||
innerHTML: `
|
||||
<h3 class="modal-title">${title}</h3>
|
||||
${closable ? '<button class="modal-close" aria-label="Close">×</button>' : ''}
|
||||
`
|
||||
});
|
||||
modal.appendChild(header);
|
||||
}
|
||||
|
||||
const body = this.createElement('div', { className: 'modal-body' });
|
||||
modal.appendChild(body);
|
||||
|
||||
modalBg.appendChild(modal);
|
||||
document.body.appendChild(modalBg);
|
||||
|
||||
this.addModalStyles();
|
||||
|
||||
const closeModal = () => this.removeModal(id);
|
||||
|
||||
if (closable) {
|
||||
const closeBtn = modal.querySelector('.modal-close');
|
||||
if (closeBtn) closeBtn.onclick = closeModal;
|
||||
|
||||
modal.addEventListener('keydown', e => {
|
||||
if (e.key === 'Escape') closeModal();
|
||||
});
|
||||
|
||||
if (backdrop) {
|
||||
modalBg.addEventListener('click', e => {
|
||||
if (e.target === modalBg) closeModal();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
modal.querySelector('.modal-body').focus = () => {
|
||||
const focusable = modal.querySelector('input, select, textarea, button');
|
||||
if (focusable) focusable.focus();
|
||||
};
|
||||
|
||||
setTimeout(() => modal.querySelector('.modal-body').focus(), 100);
|
||||
|
||||
return {
|
||||
modal,
|
||||
body: modal.querySelector('.modal-body'),
|
||||
close: closeModal,
|
||||
updateContent: (newContent) => {
|
||||
const body = modal.querySelector('.modal-body');
|
||||
if (typeof newContent === 'string') {
|
||||
body.innerHTML = newContent;
|
||||
} else if (newContent instanceof HTMLElement) {
|
||||
body.innerHTML = '';
|
||||
body.appendChild(newContent);
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
const focusable = body.querySelector('input, select, textarea, button');
|
||||
if (focusable) focusable.focus();
|
||||
}, 50);
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
createElement(tag, props = {}) {
|
||||
const element = document.createElement(tag);
|
||||
Object.assign(element, props);
|
||||
return element;
|
||||
},
|
||||
|
||||
removeModal(id) {
|
||||
const existingModal = document.getElementById(id + '-bg');
|
||||
if (existingModal) existingModal.remove();
|
||||
},
|
||||
|
||||
confirm(message, title = 'Confirm', type = 'default') {
|
||||
return new Promise((resolve) => {
|
||||
const { body, close } = this.createModal({ title, className: `modal-confirm modal-confirm-${type}` });
|
||||
|
||||
const confirmButtonClass = type === 'danger' ? 'btn-danger' : 'btn-primary';
|
||||
|
||||
body.innerHTML = `
|
||||
<p class="modal-message">${message}</p>
|
||||
<div class="modal-buttons">
|
||||
<button class="btn btn-secondary modal-cancel">Cancel</button>
|
||||
<button class="btn ${confirmButtonClass} modal-confirm-btn">Confirm</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const handleResult = (result) => {
|
||||
close();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
body.querySelector('.modal-cancel').onclick = () => handleResult(false);
|
||||
body.querySelector('.modal-confirm-btn').onclick = () => handleResult(true);
|
||||
|
||||
body.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') handleResult(true);
|
||||
else if (e.key === 'Escape') handleResult(false);
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
prompt(message, defaultValue = '', title = 'Input', inputType = 'text', options = {}) {
|
||||
return new Promise((resolve) => {
|
||||
const { keepOpen = false } = options;
|
||||
const { body, close, updateContent } = this.createModal({
|
||||
title,
|
||||
className: 'modal-prompt',
|
||||
...options
|
||||
});
|
||||
|
||||
const createPromptContent = (message, defaultValue = '', clearValue = false) => {
|
||||
const inputId = 'modal-input-' + Date.now();
|
||||
return `
|
||||
<label for="${inputId}" class="modal-label">${message}</label>
|
||||
<input type="${inputType}" id="${inputId}" class="modal-input" value="${clearValue ? '' : defaultValue}" autocomplete="off">
|
||||
<div class="modal-buttons">
|
||||
<button class="btn btn-secondary modal-cancel">Cancel</button>
|
||||
<button class="btn btn-primary modal-ok">OK</button>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
body.innerHTML = createPromptContent(message, defaultValue);
|
||||
|
||||
const handleResult = (result) => {
|
||||
if (!keepOpen) {
|
||||
close();
|
||||
}
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
const setupEventListeners = () => {
|
||||
const input = body.querySelector('.modal-input');
|
||||
const cancelBtn = body.querySelector('.modal-cancel');
|
||||
const okBtn = body.querySelector('.modal-ok');
|
||||
|
||||
const newCancelBtn = cancelBtn.cloneNode(true);
|
||||
const newOkBtn = okBtn.cloneNode(true);
|
||||
cancelBtn.parentNode.replaceChild(newCancelBtn, cancelBtn);
|
||||
okBtn.parentNode.replaceChild(newOkBtn, okBtn);
|
||||
|
||||
newCancelBtn.onclick = () => handleResult(null);
|
||||
newOkBtn.onclick = () => handleResult(input.value);
|
||||
|
||||
input.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') handleResult(input.value);
|
||||
else if (e.key === 'Escape') handleResult(null);
|
||||
});
|
||||
|
||||
input.focus();
|
||||
input.select();
|
||||
};
|
||||
|
||||
setupEventListeners();
|
||||
|
||||
if (keepOpen) {
|
||||
resolve({
|
||||
value: null,
|
||||
update: (newMessage, clearInput = true) => {
|
||||
return new Promise((updateResolve) => {
|
||||
updateContent(createPromptContent(newMessage, defaultValue, clearInput));
|
||||
|
||||
const handleUpdateResult = (result) => {
|
||||
updateResolve(result);
|
||||
};
|
||||
|
||||
const setupUpdateListeners = () => {
|
||||
const input = body.querySelector('.modal-input');
|
||||
const cancelBtn = body.querySelector('.modal-cancel');
|
||||
const okBtn = body.querySelector('.modal-ok');
|
||||
|
||||
cancelBtn.onclick = () => handleUpdateResult(null);
|
||||
okBtn.onclick = () => handleUpdateResult(input.value);
|
||||
|
||||
input.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') handleUpdateResult(input.value);
|
||||
else if (e.key === 'Escape') handleUpdateResult(null);
|
||||
});
|
||||
|
||||
input.focus();
|
||||
input.select();
|
||||
};
|
||||
|
||||
setupUpdateListeners();
|
||||
});
|
||||
},
|
||||
close
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
select(message, options = [], title = 'Select') {
|
||||
return new Promise((resolve) => {
|
||||
const { body, close } = this.createModal({ title, className: 'modal-select' });
|
||||
|
||||
const selectId = 'modal-select-' + Date.now();
|
||||
const optionsHtml = options.map(opt => {
|
||||
const value = typeof opt === 'object' ? opt.value : opt;
|
||||
const label = typeof opt === 'object' ? opt.label : opt;
|
||||
return `<option value="${value}">${label}</option>`;
|
||||
}).join('');
|
||||
|
||||
body.innerHTML = `
|
||||
<label for="${selectId}" class="modal-label">${message}</label>
|
||||
<select id="${selectId}" class="modal-select-input">
|
||||
${optionsHtml}
|
||||
</select>
|
||||
<div class="modal-buttons">
|
||||
<button class="btn btn-secondary modal-cancel">Cancel</button>
|
||||
<button class="btn btn-primary modal-ok">OK</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const select = body.querySelector('.modal-select-input');
|
||||
const handleResult = (result) => {
|
||||
close();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
body.querySelector('.modal-cancel').onclick = () => handleResult(null);
|
||||
body.querySelector('.modal-ok').onclick = () => handleResult(select.value);
|
||||
|
||||
select.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') handleResult(select.value);
|
||||
else if (e.key === 'Escape') handleResult(null);
|
||||
});
|
||||
|
||||
select.focus();
|
||||
});
|
||||
},
|
||||
|
||||
date(message, defaultDate = '', title = 'Select Date') {
|
||||
return new Promise((resolve) => {
|
||||
const { body, close } = this.createModal({ title, className: 'modal-date' });
|
||||
|
||||
const inputId = 'modal-date-' + Date.now();
|
||||
const dateValue = defaultDate || new Date().toISOString().split('T')[0];
|
||||
|
||||
body.innerHTML = `
|
||||
<label for="${inputId}" class="modal-label">${message}</label>
|
||||
<input type="date" id="${inputId}" class="modal-input" value="${dateValue}">
|
||||
<div class="modal-buttons">
|
||||
<button class="btn btn-secondary modal-cancel">Cancel</button>
|
||||
<button class="btn btn-primary modal-ok">OK</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const input = body.querySelector('.modal-input');
|
||||
const handleResult = (result) => {
|
||||
close();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
body.querySelector('.modal-cancel').onclick = () => handleResult(null);
|
||||
body.querySelector('.modal-ok').onclick = () => handleResult(input.value);
|
||||
|
||||
input.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') handleResult(input.value);
|
||||
else if (e.key === 'Escape') handleResult(null);
|
||||
});
|
||||
|
||||
input.focus();
|
||||
});
|
||||
},
|
||||
|
||||
form(fields = [], title = 'Form') {
|
||||
return new Promise((resolve) => {
|
||||
const { body, close } = this.createModal({ title, className: 'modal-form' });
|
||||
|
||||
const formHtml = fields.map((field, index) => {
|
||||
const id = `modal-field-${Date.now()}-${index}`;
|
||||
const {
|
||||
type = 'text',
|
||||
label = '',
|
||||
name = `field_${index}`,
|
||||
value = '',
|
||||
required = false,
|
||||
options = []
|
||||
} = field;
|
||||
|
||||
let inputHtml = '';
|
||||
switch (type) {
|
||||
case 'select':
|
||||
const optionsHtml = options.map(opt => {
|
||||
const optValue = typeof opt === 'object' ? opt.value : opt;
|
||||
const optLabel = typeof opt === 'object' ? opt.label : opt;
|
||||
return `<option value="${optValue}" ${optValue === value ? 'selected' : ''}>${optLabel}</option>`;
|
||||
}).join('');
|
||||
inputHtml = `<select id="${id}" name="${name}" class="modal-input" ${required ? 'required' : ''}>${optionsHtml}</select>`;
|
||||
break;
|
||||
case 'textarea':
|
||||
inputHtml = `<textarea id="${id}" name="${name}" class="modal-input" ${required ? 'required' : ''}>${value}</textarea>`;
|
||||
break;
|
||||
case 'checkbox':
|
||||
inputHtml = `<input type="checkbox" id="${id}" name="${name}" class="modal-checkbox" ${value ? 'checked' : ''} ${required ? 'required' : ''}>`;
|
||||
break;
|
||||
default:
|
||||
inputHtml = `<input type="${type}" id="${id}" name="${name}" class="modal-input" value="${value}" ${required ? 'required' : ''}>`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="modal-field">
|
||||
<label for="${id}" class="modal-label">${label}${required ? ' *' : ''}</label>
|
||||
${inputHtml}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
body.innerHTML = `
|
||||
<form class="modal-form-content">
|
||||
${formHtml}
|
||||
<div class="modal-buttons">
|
||||
<button type="button" class="btn btn-secondary modal-cancel">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary modal-submit">Submit</button>
|
||||
</div>
|
||||
</form>
|
||||
`;
|
||||
|
||||
const form = body.querySelector('.modal-form-content');
|
||||
const handleResult = (result) => {
|
||||
close();
|
||||
resolve(result);
|
||||
};
|
||||
|
||||
body.querySelector('.modal-cancel').onclick = () => handleResult(null);
|
||||
|
||||
form.addEventListener('submit', e => {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(form);
|
||||
const result = {};
|
||||
|
||||
fields.forEach(field => {
|
||||
const name = field.name || `field_${fields.indexOf(field)}`;
|
||||
if (field.type === 'checkbox') {
|
||||
result[name] = formData.has(name);
|
||||
} else {
|
||||
result[name] = formData.get(name);
|
||||
}
|
||||
});
|
||||
|
||||
handleResult(result);
|
||||
});
|
||||
|
||||
const firstInput = body.querySelector('.modal-input');
|
||||
if (firstInput) firstInput.focus();
|
||||
});
|
||||
},
|
||||
|
||||
alert(message, title = 'Alert', type = 'info') {
|
||||
return new Promise((resolve) => {
|
||||
const { body, close } = this.createModal({ title, className: `modal-alert modal-alert-${type}` });
|
||||
|
||||
const icon = {
|
||||
info: 'ℹ️',
|
||||
warning: '⚠️',
|
||||
error: '❌',
|
||||
success: '✅'
|
||||
}[type] || 'ℹ️';
|
||||
|
||||
body.innerHTML = `
|
||||
<div class="modal-alert-content">
|
||||
<span class="modal-alert-icon">${icon}</span>
|
||||
<p class="modal-message">${message}</p>
|
||||
</div>
|
||||
<div class="modal-buttons">
|
||||
<button class="btn btn-primary modal-ok">OK</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const handleResult = () => {
|
||||
close();
|
||||
resolve();
|
||||
};
|
||||
|
||||
body.querySelector('.modal-ok').onclick = handleResult;
|
||||
|
||||
body.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter' || e.key === 'Escape') handleResult();
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
custom(content, options = {}) {
|
||||
const { body, close } = this.createModal(options);
|
||||
|
||||
if (typeof content === 'string') {
|
||||
body.innerHTML = content;
|
||||
} else if (content instanceof HTMLElement) {
|
||||
body.appendChild(content);
|
||||
}
|
||||
|
||||
return { body, close };
|
||||
},
|
||||
|
||||
addModalStyles() {
|
||||
if (document.getElementById('modal-styles')) return;
|
||||
|
||||
const style = document.createElement('style');
|
||||
style.id = 'modal-styles';
|
||||
style.textContent = `
|
||||
.modal ::selection {
|
||||
background-color: var(--neutral-600, #525252);
|
||||
color: var(--neutral-100, #f5f5f5);
|
||||
}
|
||||
|
||||
.modal ::-moz-selection {
|
||||
background-color: var(--neutral-600, #525252);
|
||||
color: var(--neutral-100, #f5f5f5);
|
||||
}
|
||||
|
||||
.modal input::selection,
|
||||
.modal textarea::selection,
|
||||
.modal-input::selection,
|
||||
.modal-backdrop input::selection,
|
||||
.modal-backdrop textarea::selection {
|
||||
background-color: #3b82f6;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.modal input::-moz-selection,
|
||||
.modal textarea::-moz-selection,
|
||||
.modal-input::-moz-selection,
|
||||
.modal-backdrop input::-moz-selection,
|
||||
.modal-backdrop textarea::-moz-selection {
|
||||
background-color: #3b82f6;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 999;
|
||||
animation: modal-fade-in 0.2s ease-out;
|
||||
}
|
||||
|
||||
.modal-backdrop.no-animation {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.modal {
|
||||
background: var(--neutral-900, #1a1a1a);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
|
||||
max-width: 500px;
|
||||
width: 90%;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--neutral-800, #333);
|
||||
animation: modal-slide-in 0.2s ease-out;
|
||||
}
|
||||
|
||||
.modal.no-animation {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1.5rem 1.5rem 1rem;
|
||||
border-bottom: 1px solid var(--neutral-800, #333);
|
||||
}
|
||||
|
||||
.modal-title {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-color, #fff);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.modal-close {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 1.5rem;
|
||||
color: var(--text-color-secondary, #aaa);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 4px;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.modal-close:hover {
|
||||
background: var(--neutral-800, #333);
|
||||
color: var(--text-color, #fff);
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 1.5rem;
|
||||
}
|
||||
|
||||
.modal-label {
|
||||
display: block;
|
||||
font-weight: 500;
|
||||
color: var(--text-color, #fff);
|
||||
margin-bottom: 0.75rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.modal-input, .modal-select-input {
|
||||
width: 100%;
|
||||
padding: 0.75rem;
|
||||
border: 1px solid var(--neutral-700, #444);
|
||||
border-radius: 6px;
|
||||
background: var(--neutral-800, #2a2a2a);
|
||||
color: var(--text-color, #fff);
|
||||
font-size: 1rem;
|
||||
transition: border-color 0.2s ease;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.modal-input:focus, .modal-select-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary-color, #3b82f6);
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
|
||||
}
|
||||
|
||||
textarea.modal-input {
|
||||
resize: vertical;
|
||||
min-height: 100px;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.modal-checkbox {
|
||||
width: auto !important;
|
||||
margin-right: 0.5rem;
|
||||
accent-color: var(--primary-color, #3b82f6);
|
||||
}
|
||||
|
||||
.modal-field {
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.modal-field:last-of-type {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.modal-message {
|
||||
color: var(--text-color, #fff);
|
||||
margin: 0 0 1.5rem 0;
|
||||
line-height: 1.6;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.modal-buttons {
|
||||
display: flex;
|
||||
gap: 0.75rem;
|
||||
justify-content: flex-end;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: 0.75rem 1.25rem;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
min-width: 80px;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--primary-color, #3b82f6);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background: var(--primary-hover, #2563eb);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: var(--neutral-700, #444);
|
||||
color: var(--text-color, #fff);
|
||||
border: 1px solid var(--neutral-600, #555);
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: var(--neutral-600, #555);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: #dc2626;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-danger:hover {
|
||||
background: #b91c1c;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.modal-alert-content {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.modal-alert-icon {
|
||||
font-size: 1.5rem;
|
||||
flex-shrink: 0;
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
|
||||
.modal-confirm-danger .modal-title {
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
.modal-confirm-danger .modal-message {
|
||||
color: #f3f4f6;
|
||||
}
|
||||
|
||||
.modal-alert-error .modal-alert-icon {
|
||||
filter: hue-rotate(0deg);
|
||||
}
|
||||
|
||||
.modal-alert-warning .modal-alert-icon {
|
||||
filter: hue-rotate(45deg);
|
||||
}
|
||||
|
||||
.modal-alert-success .modal-alert-icon {
|
||||
filter: hue-rotate(120deg);
|
||||
}
|
||||
|
||||
@keyframes modal-fade-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes modal-slide-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-20px) scale(0.95);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.modal {
|
||||
width: 95%;
|
||||
max-height: 90vh;
|
||||
}
|
||||
|
||||
.modal-header, .modal-body {
|
||||
padding-left: 1rem;
|
||||
padding-right: 1rem;
|
||||
}
|
||||
|
||||
.modal-buttons {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.btn {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
};
|
||||
|
||||
window.Modal = Modal;
|
||||
@@ -0,0 +1,271 @@
|
||||
const visibility = [{ id: 0, name: "Public" }, { id: 1, name: "Unlisted" }, { id: 2, name: "Private" }];
|
||||
|
||||
let paste = null;
|
||||
|
||||
const ELEMENTS = {
|
||||
get: (id) => document.getElementById(id),
|
||||
create: (tag, props = {}) => {
|
||||
const element = document.createElement(tag);
|
||||
Object.assign(element, props);
|
||||
return element;
|
||||
},
|
||||
setText: (id, text) => ELEMENTS.get(id).innerText = text,
|
||||
setStyle: (id, styles) => Object.assign(ELEMENTS.get(id).style, styles),
|
||||
hide: (id) => ELEMENTS.get(id).style.display = "none",
|
||||
show: (id, display = "inline-block") => ELEMENTS.get(id).style.display = display
|
||||
};
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async function () {
|
||||
const id = window.location.pathname.split("/")[1];
|
||||
const [content, info] = await Promise.all([
|
||||
fetch(`/api/pastes/${id}`).then(response => response.text()),
|
||||
fetch(`/api/pastes/${id}/info`).then(response => response.json())
|
||||
]);
|
||||
|
||||
const blur = ELEMENTS.create("div", { id: "blur" });
|
||||
blur.dataset.decrypted = "false";
|
||||
document.body.appendChild(blur);
|
||||
|
||||
paste = info.paste;
|
||||
const finalContent = paste.visibility === 2 ? await handlePrivatePaste(content) : content;
|
||||
|
||||
if (finalContent) {
|
||||
blur.dataset.decrypted = "true";
|
||||
addContent(finalContent, paste.syntax);
|
||||
}
|
||||
|
||||
document.title = `${paste.title} - Sharpbin`;
|
||||
addInfo(paste);
|
||||
});
|
||||
|
||||
async function handlePrivatePaste(content) {
|
||||
try {
|
||||
const modalController = await Modal.prompt(
|
||||
"Enter the password to view this paste:",
|
||||
"",
|
||||
"Private Paste",
|
||||
"password",
|
||||
{ keepOpen: true }
|
||||
);
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
const password = await modalController.update("Enter the password to view this paste:");
|
||||
|
||||
if (password === null) {
|
||||
modalController.close();
|
||||
return null;
|
||||
}
|
||||
|
||||
const decrypted = await decryptAES(content, password);
|
||||
modalController.close();
|
||||
return decrypted;
|
||||
} catch (error) {
|
||||
showNotification("Incorrect password. Please try again.", "error", 3000);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error in handlePrivatePaste:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function addInfo(paste) {
|
||||
const isAnonymous = paste.username === "Anonymous";
|
||||
|
||||
ELEMENTS.setText("paste-title", paste.title);
|
||||
ELEMENTS.setText("paste-date", convertUnixToLocal(paste.created));
|
||||
ELEMENTS.setText("paste-syntax", paste.syntax);
|
||||
ELEMENTS.setText("paste-size", paste.size === 0 ? "" : formatSize(paste.size));
|
||||
|
||||
setupSizeTooltip(paste);
|
||||
setupAuthorLink(paste, isAnonymous);
|
||||
|
||||
ELEMENTS.setText("paste-views", paste.views);
|
||||
ELEMENTS.hide("info-throbber");
|
||||
|
||||
setupActionButtons(paste);
|
||||
setupDeleteButton(paste);
|
||||
}
|
||||
|
||||
function setupSizeTooltip(paste) {
|
||||
if (paste.size !== paste.trueSize && paste.trueSize) {
|
||||
const sizeElem = ELEMENTS.get("paste-size");
|
||||
sizeElem.classList.add("has-true-size-tooltip");
|
||||
const tooltip = ELEMENTS.create("div", {
|
||||
className: "true-size-tooltip",
|
||||
innerText: `True size: ${formatSize(paste.trueSize)}`
|
||||
});
|
||||
sizeElem.appendChild(tooltip);
|
||||
sizeElem.onmouseenter = () => tooltip.style.opacity = 1;
|
||||
sizeElem.onmouseleave = () => tooltip.style.opacity = 0;
|
||||
}
|
||||
}
|
||||
|
||||
function setupAuthorLink(paste, isAnonymous) {
|
||||
const authorLink = ELEMENTS.get("author-link");
|
||||
ELEMENTS.setText("paste-author", paste.username);
|
||||
|
||||
if (isAnonymous) {
|
||||
Object.assign(authorLink, {
|
||||
innerText: "Anonymous",
|
||||
href: ""
|
||||
});
|
||||
Object.assign(authorLink.style, {
|
||||
pointerEvents: "none",
|
||||
textDecoration: "none"
|
||||
});
|
||||
} else {
|
||||
authorLink.href = `/u/${paste.username}`;
|
||||
}
|
||||
}
|
||||
|
||||
function setupActionButtons(paste) {
|
||||
const actions = [
|
||||
{
|
||||
id: "copy-button",
|
||||
action: () => {
|
||||
const content = ELEMENTS.get("paste-content").innerText;
|
||||
navigator.clipboard.writeText(content);
|
||||
showNotification("Paste copied to clipboard!", "info", 2000);
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "download-button",
|
||||
action: () => downloadPaste(paste.title)
|
||||
},
|
||||
{
|
||||
id: "raw-button",
|
||||
action: () => window.location.href = `/raw/${paste.id}`
|
||||
}
|
||||
];
|
||||
|
||||
actions.forEach(({ id, action }) => {
|
||||
ELEMENTS.get(id).addEventListener("click", action);
|
||||
});
|
||||
}
|
||||
|
||||
function downloadPaste(title) {
|
||||
const content = ELEMENTS.get("paste-content").innerText;
|
||||
const blob = new Blob([content], { type: "text/plain" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = ELEMENTS.create("a", {
|
||||
href: url,
|
||||
download: `${title}.txt`
|
||||
});
|
||||
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
showNotification("Paste downloaded!", "info", 2000);
|
||||
}
|
||||
|
||||
function setupDeleteButton(paste) {
|
||||
waitForAuthData().then(() => {
|
||||
if (authData.user.uuid === paste.authorUUID || authData.user.type === 255) {
|
||||
ELEMENTS.show("delete-button");
|
||||
ELEMENTS.get("delete-button").addEventListener("click", async () => {
|
||||
const confirmed = await Modal.confirm(
|
||||
"Are you sure you want to delete this paste? This action cannot be undone.",
|
||||
"Delete Paste",
|
||||
"danger"
|
||||
);
|
||||
if (confirmed) {
|
||||
deletePaste(paste.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function deletePaste(pasteId) {
|
||||
fetch(`/api/pastes/${pasteId}`, { method: "DELETE" })
|
||||
.then(response => {
|
||||
const message = response.ok ? "Paste deleted!" : "Failed to delete paste.";
|
||||
const type = response.ok ? "info" : "error";
|
||||
showNotification(message, type, 2000);
|
||||
if (response.ok) window.location.href = "/";
|
||||
});
|
||||
}
|
||||
|
||||
function waitForAuthData() {
|
||||
return new Promise((resolve) => {
|
||||
const checkAuth = setInterval(() => {
|
||||
if (authData) {
|
||||
clearInterval(checkAuth);
|
||||
resolve();
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
}
|
||||
|
||||
function addContent(content, syntax) {
|
||||
const code = ELEMENTS.create("code", {
|
||||
textContent: content,
|
||||
id: "paste-content"
|
||||
});
|
||||
const pre = ELEMENTS.get("paste-content");
|
||||
|
||||
pre.innerText = "";
|
||||
pre.appendChild(code);
|
||||
pre.removeAttribute("id");
|
||||
|
||||
const isPlaintext = ["plaintext", "none", "", null].includes(syntax);
|
||||
code.classList.add(`language-${isPlaintext ? "none" : syntax}`);
|
||||
|
||||
if (!isPlaintext) {
|
||||
hljs.highlightElement(code);
|
||||
code.style.padding = "0px";
|
||||
}
|
||||
|
||||
hljs.lineNumbersBlock(code);
|
||||
ELEMENTS.hide("content-throbber");
|
||||
}
|
||||
|
||||
async function decryptAES(content, password) {
|
||||
const rawData = atob(content);
|
||||
const rawDataArray = Uint8Array.from(rawData, c => c.charCodeAt(0));
|
||||
const [salt, iv, ciphertext] = [
|
||||
rawDataArray.slice(0, 16),
|
||||
rawDataArray.slice(16, 28),
|
||||
rawDataArray.slice(28)
|
||||
];
|
||||
|
||||
const keyMaterial = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
new TextEncoder().encode(password),
|
||||
{ name: "PBKDF2" },
|
||||
false,
|
||||
["deriveKey"]
|
||||
);
|
||||
|
||||
const key = await crypto.subtle.deriveKey(
|
||||
{
|
||||
name: "PBKDF2",
|
||||
salt,
|
||||
iterations: 100000,
|
||||
hash: "SHA-256"
|
||||
},
|
||||
keyMaterial,
|
||||
{ name: "AES-GCM", length: 256 },
|
||||
false,
|
||||
["decrypt"]
|
||||
);
|
||||
|
||||
const decrypted = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv },
|
||||
key,
|
||||
ciphertext
|
||||
);
|
||||
|
||||
return new TextDecoder().decode(decrypted);
|
||||
}
|
||||
|
||||
const convertUnixToLocal = (unix) => new Date(unix * 1000).toLocaleString();
|
||||
|
||||
const formatSize = (bytes) => {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
||||
};
|
||||
@@ -0,0 +1,111 @@
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const registerForm = document.getElementById('register-form');
|
||||
const errorMessage = document.getElementById('error-message');
|
||||
|
||||
|
||||
checkAuthStatus();
|
||||
|
||||
registerForm.addEventListener('submit', async function(event) {
|
||||
event.preventDefault();
|
||||
|
||||
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const email = document.getElementById('email').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
const confirmPassword = document.getElementById('confirm-password').value;
|
||||
|
||||
|
||||
if (!username || !password) {
|
||||
showError('Please fill in all required fields');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
showError('Passwords do not match');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
showError('Password must be at least 6 characters long');
|
||||
return;
|
||||
}
|
||||
|
||||
if (username.length < 3) {
|
||||
showError('Username must be at least 3 characters long');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
const submitButton = registerForm.querySelector('button[type="submit"]');
|
||||
const originalButtonText = submitButton.textContent;
|
||||
submitButton.disabled = true;
|
||||
submitButton.textContent = 'Creating account...';
|
||||
|
||||
|
||||
const requestData = {
|
||||
username: username,
|
||||
password: password
|
||||
};
|
||||
|
||||
|
||||
if (email) {
|
||||
requestData.email = email;
|
||||
}
|
||||
|
||||
|
||||
const response = await fetch('/api/auth/register', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(requestData)
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
|
||||
window.location.href = '/dash';
|
||||
} else {
|
||||
showError(data.message || 'Registration failed. Please try again.');
|
||||
submitButton.disabled = false;
|
||||
submitButton.textContent = originalButtonText;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Registration error:', error);
|
||||
showError('An unexpected error occurred. Please try again later.');
|
||||
|
||||
const submitButton = registerForm.querySelector('button[type="submit"]');
|
||||
submitButton.disabled = false;
|
||||
submitButton.textContent = 'Register';
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
function showError(message) {
|
||||
errorMessage.textContent = message;
|
||||
errorMessage.classList.add('visible');
|
||||
|
||||
|
||||
setTimeout(() => {
|
||||
errorMessage.classList.remove('visible');
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
|
||||
async function checkAuthStatus() {
|
||||
try {
|
||||
const response = await fetch('/api/auth/authenticated');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
|
||||
window.location.href = '/dash';
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
console.log('Not logged in');
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
let currentPage = 0;
|
||||
const PAGE_SIZE = 25;
|
||||
let totalPastes = 0;
|
||||
let lastPage = false;
|
||||
|
||||
async function loadUserPastes(userData, page = 0) {
|
||||
const pastesRes = await fetch(`/api/users/${userData.uuid}/pastes?limit=${PAGE_SIZE}&page=${page}`);
|
||||
const data = await pastesRes.json();
|
||||
let pastes = [];
|
||||
if (pastesRes.ok) {
|
||||
pastes = data.pastes || [];
|
||||
totalPastes = data.total || 0;
|
||||
lastPage = pastes.length < PAGE_SIZE;
|
||||
}
|
||||
const list = document.getElementById("user-pastes-list");
|
||||
list.innerHTML = "";
|
||||
if (!pastes.length) {
|
||||
list.innerHTML = "<p style='color:var(--neutral-400)'>No pastes found.</p>";
|
||||
return;
|
||||
}
|
||||
for (const paste of pastes) {
|
||||
const li = document.createElement("li");
|
||||
const link = document.createElement("a");
|
||||
link.href = `/${paste.id}`;
|
||||
link.innerHTML = `
|
||||
<p>${paste.title}</p>
|
||||
<p>${new Date(paste.created * 1000).toLocaleDateString()}</p>
|
||||
<p>${paste.syntax || "Plaintext"}</p>
|
||||
`;
|
||||
li.appendChild(link);
|
||||
list.appendChild(li);
|
||||
}
|
||||
document.getElementById("paste-pages").innerText = `${page + 1}/${data.pages + 1}`;
|
||||
document.getElementById("next-button").disabled = page === 0;
|
||||
document.getElementById("previous-button").disabled = lastPage;
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", async function () {
|
||||
const username = window.location.pathname.split("/")[2]
|
||||
if (!username) {
|
||||
window.location.href = "/error?code=404&message=User not found";
|
||||
return;
|
||||
}
|
||||
const userInfoRes = await fetch(`/api/users/username/${username}`);
|
||||
if (!userInfoRes.ok) {
|
||||
document.getElementById("user-name").innerText = "User not found";
|
||||
document.getElementById("user-pastes-list").innerHTML = "<p style='color:var(--neutral-400)'>No user data.</p>";
|
||||
return;
|
||||
}
|
||||
const user = await userInfoRes.json();
|
||||
const userData = user.user ? user.user : user;
|
||||
document.title = `${userData.username} - Sharpbin`;
|
||||
document.getElementById("user-name").innerText = userData.username;
|
||||
document.getElementById("user-uuid").innerText = userData.uuid;
|
||||
|
||||
await loadUserPastes(userData, 0);
|
||||
currentPage = 0;
|
||||
document.getElementById("previous-button").onclick = async function () {
|
||||
if (currentPage > 0) {
|
||||
currentPage--;
|
||||
await loadUserPastes(userData, currentPage);
|
||||
}
|
||||
};
|
||||
document.getElementById("next-button").onclick = async function () {
|
||||
if (!lastPage) {
|
||||
currentPage++;
|
||||
await loadUserPastes(userData, currentPage);
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
function formatSize(bytes) {
|
||||
if (bytes < 1024) return bytes + ' B';
|
||||
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
|
||||
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Login - Sharpbin</title>
|
||||
<link rel="preload" href="css/style.css" as="style">
|
||||
<link rel="preload" href="css/auth.css" as="style">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<link rel="stylesheet" href="css/auth.css">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="auth-container">
|
||||
<div class="auth-form-container">
|
||||
<h1 class="auth-title">Login to Sharpbin</h1>
|
||||
<div id="error-message" class="error-message"></div>
|
||||
<form id="login-form" class="auth-form">
|
||||
<div class="form-group">
|
||||
<label for="username">Username or Email</label>
|
||||
<input type="text" id="username" name="username" placeholder="Enter your username or email" required autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Password</label>
|
||||
<input type="password" id="password" name="password" placeholder="Enter your password" required autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<button type="submit" class="auth-button">Login</button>
|
||||
</form> <div class="auth-links">
|
||||
<p>Don't have an account? <a href="register.html">Register</a></p>
|
||||
<p>Forgot your password? <a href="reset-password.html">Reset Password</a></p>
|
||||
<p><a href="/">Back to Home</a></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="js/login.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,52 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="preload" href="css/style.css" as="style">
|
||||
<link rel="preload" href="css/paste.css" as="style">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<link rel="stylesheet" href="css/paste.css">
|
||||
<link rel="preload" href="js/paste.js" as="script">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
|
||||
rel="stylesheet">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.8.0/highlightjs-line-numbers.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="main-container">
|
||||
<div class="paste-header">
|
||||
<div style="display: flex;">
|
||||
<h1 id="paste-title">Title</h1>
|
||||
<span class="edit-icon" id="edit-button" style="width: 32px; height: 32px; display: none;" id="edit-button" title="Edit Paste"></span>
|
||||
</div>
|
||||
<div class="paste-information-card">
|
||||
<div id="info-throbber" class="throbber"></div>
|
||||
<div class="paste-info-item"><span class="info-icon syntax-icon"></span><span id="paste-syntax">Syntax</span></div>
|
||||
<div class="paste-info-item"><span class="info-icon date-icon"></span><span id="paste-date">Date</span></div>
|
||||
<div class="paste-info-item"><span class="info-icon size-icon"></span><span id="paste-size">Size</span></div>
|
||||
<div class="paste-info-item"><span class="info-icon views-icon"></span><span id="paste-views">Views</span></div>
|
||||
<div class="paste-info-item"><span class="info-icon author-icon"></span><a id="author-link" href="#"><span id="paste-author">Author</span></a></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="paste-content">
|
||||
<div class="paste-actions">
|
||||
<button id="copy-button">Copy</button>
|
||||
<button id="download-button">Download</button>
|
||||
<button id="raw-button">Raw</button>
|
||||
<button id="delete-button" style="display: none;">Delete</button>
|
||||
</div>
|
||||
<div id="content-throbber" class="throbber"></div>
|
||||
<pre id="paste-content">Loading...</pre>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<script src="js/modal.js"></script>
|
||||
<script src="js/paste.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</html>
|
||||
@@ -0,0 +1,52 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Register - Sharpbin</title>
|
||||
<link rel="preload" href="css/style.css" as="style">
|
||||
<link rel="preload" href="css/auth.css" as="style">
|
||||
<link rel="stylesheet" href="css/style.css">
|
||||
<link rel="stylesheet" href="css/auth.css">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap" rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="auth-container">
|
||||
<div class="auth-form-container">
|
||||
<h1 class="auth-title">Create an Account</h1>
|
||||
<div id="error-message" class="error-message"></div>
|
||||
<form id="register-form" class="auth-form">
|
||||
<div class="form-group">
|
||||
<label for="username">Username</label>
|
||||
<input type="text" id="username" name="username" placeholder="Choose a username" required autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="email">Email (optional)</label>
|
||||
<input type="email" id="email" name="email" placeholder="Enter your email" autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Password</label>
|
||||
<input type="password" id="password" name="password" placeholder="Create a password" required autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="confirm-password">Confirm Password</label>
|
||||
<input type="password" id="confirm-password" name="confirm-password" placeholder="Confirm your password" required autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
<button type="submit" class="auth-button">Register</button>
|
||||
</form>
|
||||
<div class="auth-links">
|
||||
<p>Already have an account? <a href="login.html">Login</a></p>
|
||||
<p><a href="/">Back to Home</a></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="js/register.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,46 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Loading - Sharpbin</title>
|
||||
<link rel="preload" href="/css/style.css" as="style">
|
||||
<link rel="preload" href="/css/user.css" as="style">
|
||||
<link rel="stylesheet" href="/css/style.css">
|
||||
<link rel="stylesheet" href="/css/user.css">
|
||||
<link rel="preload" href="/js/user.js" as="script">
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Noto+Sans+Mono:wght@100..900&display=swap"
|
||||
rel="stylesheet">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="main-container">
|
||||
<div class="user-header">
|
||||
<h1 id="user-name">Loading...</h1>
|
||||
<p id="user-uuid"></p>
|
||||
</div>
|
||||
<div class="user-pastes-section">
|
||||
<div class="archive-information">
|
||||
<p id="archive-title">Title</p>
|
||||
<p id="archive-date">Date</p>
|
||||
<p id="archive-syntax">Syntax</p>
|
||||
</div>
|
||||
<ul id="user-pastes-list" class="archive-list">
|
||||
<div class="user-pastes-throbber throbber"></div>
|
||||
</ul>
|
||||
<div class="pastes-actions">
|
||||
<button id="previous-button"><span id="previous-button-svg"></span></button>
|
||||
<p id="paste-pages">0/0</p>
|
||||
<button id="next-button"><span id="next-button-svg"></span></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
<script src="/js/user.js"></script>
|
||||
<script src="/js/main.js"></script>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.10.35122.118
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpbinV2.Server", "SharpbinV2.Server\SharpbinV2.Server.csproj", "{AEEAD9CC-3EB9-4576-98D0-51C04F1B8D21}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{AEEAD9CC-3EB9-4576-98D0-51C04F1B8D21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AEEAD9CC-3EB9-4576-98D0-51C04F1B8D21}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AEEAD9CC-3EB9-4576-98D0-51C04F1B8D21}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AEEAD9CC-3EB9-4576-98D0-51C04F1B8D21}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {481923D9-3518-41F9-9878-65AC793960AB}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,24 +0,0 @@
|
||||
node_modules
|
||||
|
||||
# Output
|
||||
.output
|
||||
.vercel
|
||||
.netlify
|
||||
.wrangler
|
||||
/.svelte-kit
|
||||
/build
|
||||
.cache
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Env
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
!.env.test
|
||||
|
||||
# Vite
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
@@ -1 +0,0 @@
|
||||
engine-strict=true
|
||||
@@ -1,9 +0,0 @@
|
||||
# Package Managers
|
||||
package-lock.json
|
||||
pnpm-lock.yaml
|
||||
yarn.lock
|
||||
bun.lock
|
||||
bun.lockb
|
||||
|
||||
# Miscellaneous
|
||||
/static/
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"useTabs": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"printWidth": 100,
|
||||
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
|
||||
"overrides": [
|
||||
{
|
||||
"files": "*.svelte",
|
||||
"options": {
|
||||
"parser": "svelte"
|
||||
}
|
||||
}
|
||||
],
|
||||
"tailwindStylesheet": "./src/routes/layout.css"
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"*.css": "tailwindcss"
|
||||
},
|
||||
"tailwindCSS.experimental.configFile": "src/routes/layout.css"
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM node:24-alpine as build
|
||||
ARG GIT_COMMIT_HASH
|
||||
ENV GIT_COMMIT_HASH=${GIT_COMMIT_HASH}
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM node:24-alpine as runner
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production
|
||||
ENV HOST=0.0.0.0
|
||||
ENV PORT=5173
|
||||
COPY package.json package-lock.json ./
|
||||
RUN apk add --no-cache wget libstdc++ \
|
||||
&& apk add --no-cache --virtual .build-deps python3 make g++ \
|
||||
&& npm ci --omit=dev \
|
||||
&& npm cache clean --force \
|
||||
&& apk del .build-deps
|
||||
COPY --from=build --chown=node:node /app/build ./build
|
||||
RUN chown -R node:node /app
|
||||
EXPOSE 5173
|
||||
USER node
|
||||
CMD ["node", "build"]
|
||||
@@ -1,65 +0,0 @@
|
||||
# SharpbinV3 Client
|
||||
|
||||
This is the SvelteKit frontend for SharpbinV3.
|
||||
|
||||
## Development Setup
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 24
|
||||
- npm
|
||||
|
||||
### Installation
|
||||
|
||||
Install the project dependencies:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
### Environment Configuration
|
||||
|
||||
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 backend URL reachable from the frontend server. Export this in the shell when changing the development backend URL so the Vite proxy and server-side requests use the same value.
|
||||
- `VITE_ALLOWED_HOSTS`: A comma-separated list of hosts for Vite dev/preview. Export this in the shell before starting Vite. It does not configure the production Node server.
|
||||
|
||||
In development, the frontend uses a fixed internal view-recording key matching `appsettings.Development.json`. It ignores `VIEW_INTERNAL_API_KEY` and `View_HMAC_Internal_API_Key` while `NODE_ENV=development`.
|
||||
|
||||
### Running in Development
|
||||
|
||||
Start the development server with Hot Module Replacement (HMR):
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
The frontend will be available at http://localhost:5173.
|
||||
|
||||
### Running in Production
|
||||
|
||||
Docker Compose reads the root `.env` file and runs the built Node server on port 5173. Configure these values there:
|
||||
|
||||
- `VITE_API_URL`: Backend URL. Defaults to `http://backend:8080` in Compose.
|
||||
- `ORIGIN`: Public frontend URL, such as `https://example.com` or `http://localhost:5173` for local Docker testing.
|
||||
- `PasteSettings__View_Internal_API_Key`: Shared view-recording key. Compose passes it to the frontend as `VIEW_INTERNAL_API_KEY`, so you only set it once.
|
||||
|
||||
For a standalone Node deployment, set `VITE_API_URL`, `ORIGIN`, and `VIEW_INTERNAL_API_KEY` in the client's own `.env` file. The key must match the backend's `PasteSettings__View_Internal_API_Key`. The frontend still supports `View_HMAC_Internal_API_Key` as a fallback; it does not read the backend setting name directly.
|
||||
|
||||
The standalone server does not load `.env` automatically. Build the frontend, then load your environment file explicitly:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
node --env-file=.env build
|
||||
```
|
||||
|
||||
Set `PORT=5173` in that file to use the same port as Docker; the Node adapter otherwise defaults to port 3000. See the [Node adapter documentation](https://svelte.dev/docs/kit/adapter-node#Environment-variables) for runtime configuration.
|
||||
|
||||
## Script Reference
|
||||
|
||||
- `npm run dev`: Start the Vite development server.
|
||||
- `npm run build`: Create a production build of the frontend.
|
||||
- `npm run preview`: Locally preview the production build.
|
||||
- `npm run check`: Run type checking with svelte-check.
|
||||
- `npm run lint`: Run ESLint and Prettier checks.
|
||||
- `npm run format`: Format the codebase with Prettier.
|
||||
@@ -1,39 +0,0 @@
|
||||
import prettier from 'eslint-config-prettier';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { includeIgnoreFile } from '@eslint/compat';
|
||||
import js from '@eslint/js';
|
||||
import svelte from 'eslint-plugin-svelte';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import globals from 'globals';
|
||||
import ts from 'typescript-eslint';
|
||||
|
||||
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
|
||||
|
||||
export default defineConfig(
|
||||
includeIgnoreFile(gitignorePath),
|
||||
js.configs.recommended,
|
||||
...ts.configs.recommended,
|
||||
...svelte.configs.recommended,
|
||||
prettier,
|
||||
...svelte.configs.prettier,
|
||||
{
|
||||
languageOptions: { globals: { ...globals.browser, ...globals.node } },
|
||||
|
||||
rules: {
|
||||
// typescript-eslint strongly recommend that you do not use the no-undef lint rule on TypeScript projects.
|
||||
// see: https://typescript-eslint.io/troubleshooting/faqs/eslint/#i-get-errors-from-the-no-undef-rule-about-global-variables-not-being-defined-even-though-there-are-no-typescript-errors
|
||||
'no-undef': 'off'
|
||||
}
|
||||
},
|
||||
{
|
||||
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
|
||||
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
projectService: true,
|
||||
extraFileExtensions: ['.svelte'],
|
||||
parser: ts.parser
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
Generated
-6251
File diff suppressed because it is too large
Load Diff
@@ -1,69 +0,0 @@
|
||||
{
|
||||
"name": "sharpbinv3.client",
|
||||
"private": true,
|
||||
"version": "3.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"prepare": "svelte-kit sync || echo ''",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||
"format": "prettier --write .",
|
||||
"lint": "prettier --check . && eslint .",
|
||||
"change-log": "conventional-changelog -p angular -i ../CHANGELOG.md -s -r 0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/compat": "^1.4.0",
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@sveltejs/adapter-auto": "^8.0.0",
|
||||
"@sveltejs/kit": "^3.0.1",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.1.2",
|
||||
"@tailwindcss/vite": "^4.3.1",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/jsdom": "^27.0.0",
|
||||
"@types/node": "^22",
|
||||
"@types/papaparse": "^5.5.2",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/sharp": "^0.31.1",
|
||||
"conventional-changelog": "^7.1.1",
|
||||
"conventional-changelog-angular": "^8.1.0",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-svelte": "^3.13.1",
|
||||
"globals": "^16.5.0",
|
||||
"prettier": "^3.7.4",
|
||||
"prettier-plugin-svelte": "^3.4.0",
|
||||
"prettier-plugin-tailwindcss": "^0.7.2",
|
||||
"svelte": "^5.55.7",
|
||||
"svelte-check": "^4.3.4",
|
||||
"tailwind-scrollbar": "^4.0.2",
|
||||
"tailwindcss": "^4.1.17",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.71.2",
|
||||
"vite": "^8.0.16"
|
||||
},
|
||||
"imports": {
|
||||
"#lib": "./src/lib/index.ts",
|
||||
"#lib/*": "./src/lib/*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.2.8",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@lucide/svelte": "^0.562.0",
|
||||
"@resvg/resvg-js": "^2.6.2",
|
||||
"@sveltejs/adapter-node": "^6.0.0",
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"dompurify": "^3.4.16",
|
||||
"hash-wasm": "^4.12.0",
|
||||
"highlight.js": "^11.8.0",
|
||||
"jsdom": "^27.4.0",
|
||||
"marked": "^17.0.1",
|
||||
"papaparse": "^5.5.3",
|
||||
"qrcode": "^1.5.4",
|
||||
"satori": "^0.26.0",
|
||||
"satori-html": "^0.3.2",
|
||||
"sharp": "^0.35.5"
|
||||
}
|
||||
}
|
||||
Vendored
-33
@@ -1,33 +0,0 @@
|
||||
// See https://svelte.dev/docs/kit/types#app.d.ts
|
||||
// for information about these interfaces
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
// interface Locals {}
|
||||
// interface PageData {}
|
||||
// interface PageState {}
|
||||
// interface Platform {}
|
||||
}
|
||||
interface Window {
|
||||
turnstile?: {
|
||||
getResponse: () => string | null;
|
||||
render: (container: string | HTMLElement, options?: Record<string, unknown>) => string;
|
||||
reset: (widgetId?: string) => void;
|
||||
remove: (widgetId?: string) => void;
|
||||
};
|
||||
turnstileLoaded?: () => void;
|
||||
}
|
||||
var turnstile:
|
||||
| {
|
||||
getResponse: () => string | null;
|
||||
render: (container: string | HTMLElement, options?: Record<string, unknown>) => string;
|
||||
reset: (widgetId?: string) => void;
|
||||
remove: (widgetId?: string) => void;
|
||||
}
|
||||
| undefined;
|
||||
var turnstileLoaded: (() => void) | undefined;
|
||||
declare const __APP_VERSION__: string;
|
||||
declare const COMMIT_HASH: string;
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -1,19 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
%sveltekit.head%
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,6 +0,0 @@
|
||||
<svg width="275" height="275" viewBox="0 0 275 275" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M83 146.5H191M83 187H191M123.5 106L110 227.5M164 106L150.5 227.5" stroke="white" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M223.178 253.186C223.103 253.77 223.008 254.349 222.894 254.919C220.763 265.573 211.972 273.602 201.261 274.835C200.968 274.869 200.673 274.895 200.377 274.919C200.263 274.928 200.148 274.938 200.033 274.945C199.68 274.968 199.326 274.985 198.97 274.993L198.382 275H76.6182V260H198.382C203.412 260 207.659 256.263 208.3 251.274L230.949 75H44.0508L66.7002 251.274C67.3413 256.263 71.5881 260 76.6182 260V275C75.9889 275 75.3646 274.976 74.7461 274.93C74.41 274.905 74.0757 274.873 73.7432 274.835C62.839 273.582 53.9239 265.286 51.999 254.346C51.9316 253.962 51.8723 253.575 51.8223 253.186L27 60H248L223.178 253.186Z" fill="white"/>
|
||||
<path d="M0 42.5C0 38.3579 3.48458 35 7.78302 35H267.217C271.515 35 275 38.3579 275 42.5C275 46.6421 271.515 50 267.217 50H7.78302C3.48458 50 0 46.6421 0 42.5Z" fill="white"/>
|
||||
<path d="M159.811 0C174.139 0 185.755 11.9073 185.755 26.5957V35H88.2075V26.5957C88.2076 11.9073 99.8228 0 114.151 0H159.811ZM114.151 15C108.42 15 103.774 19.4772 103.774 25V35H170.189V25C170.189 19.4772 165.543 15 159.811 15H114.151Z" fill="white"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.3 KiB |
@@ -1,159 +0,0 @@
|
||||
<script lang="ts">
|
||||
interface Option {
|
||||
value: string | number;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
options?: Option[];
|
||||
value?: string | number;
|
||||
placeholder?: string;
|
||||
searchable?: boolean;
|
||||
displayValue?: (val: string | number) => string;
|
||||
variant?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
options = [],
|
||||
value = $bindable(''),
|
||||
placeholder = 'Select...',
|
||||
searchable = false,
|
||||
displayValue = (val) => {
|
||||
return options.find((o) => o.value === val)?.label ?? String(val);
|
||||
},
|
||||
variant = ''
|
||||
}: Props = $props();
|
||||
|
||||
let isOpen = $state(false);
|
||||
let searchQuery = $state('');
|
||||
let dropdownElement = $state<HTMLDivElement | undefined>(undefined);
|
||||
let dropdownListElement = $state<HTMLDivElement | undefined>(undefined);
|
||||
let dropdownMaxHeight = $state('12rem');
|
||||
|
||||
let filteredOptions = $derived(
|
||||
searchable
|
||||
? options.filter(
|
||||
(opt) =>
|
||||
opt.label.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
String(opt.value).toLowerCase().includes(searchQuery.toLowerCase())
|
||||
)
|
||||
: options
|
||||
);
|
||||
|
||||
function handleSelect(selectedValue: string | number) {
|
||||
value = selectedValue;
|
||||
isOpen = false;
|
||||
searchQuery = '';
|
||||
}
|
||||
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
isOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleDropdown() {
|
||||
isOpen = !isOpen;
|
||||
if (isOpen) {
|
||||
setTimeout(() => {
|
||||
if (dropdownElement && dropdownListElement) {
|
||||
const rect = dropdownElement.getBoundingClientRect();
|
||||
const spaceBelow = window.innerHeight - rect.bottom - 8;
|
||||
const maxCap = 416;
|
||||
dropdownMaxHeight = Math.max(120, Math.min(spaceBelow, maxCap)) + 'px';
|
||||
}
|
||||
if (searchable) {
|
||||
const input = dropdownElement?.querySelector('input[type="text"]') as HTMLInputElement;
|
||||
input?.focus();
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
function handleClickOutside(event: MouseEvent) {
|
||||
if (dropdownElement && !dropdownElement.contains(event.target as Node)) {
|
||||
isOpen = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onclick={handleClickOutside} />
|
||||
|
||||
<div bind:this={dropdownElement} class="relative mb-2 w-full" class:dropdown-sm={variant === 'sm'}>
|
||||
<button
|
||||
type="button"
|
||||
onclick={toggleDropdown}
|
||||
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-left transition-colors hover:bg-neutral-700"
|
||||
class:dropdown-sm-btn={variant === 'sm'}
|
||||
>
|
||||
{displayValue(value) || placeholder}
|
||||
</button>
|
||||
|
||||
{#if isOpen}
|
||||
<div
|
||||
class="absolute top-full z-50 mt-1 w-full rounded border border-neutral-700 bg-neutral-800 shadow-lg"
|
||||
class:dropdown-sm-list={variant === 'sm'}
|
||||
bind:this={dropdownListElement}
|
||||
style="max-height: {dropdownMaxHeight}; width: 100%;"
|
||||
>
|
||||
{#if searchable}
|
||||
<div style="position: sticky; top: 0; z-index: 1; background: inherit;">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Search..."
|
||||
class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none"
|
||||
class:dropdown-sm-input={variant === 'sm'}
|
||||
bind:value={searchQuery}
|
||||
onkeydown={handleKeyDown}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
<div
|
||||
class="scrollbar-thin scrollbar-thumb-neutral-600 scrollbar-track-neutral-700"
|
||||
style="overflow-y: auto; max-height: calc({dropdownMaxHeight} - 3rem);"
|
||||
>
|
||||
{#each filteredOptions as option (option.value)}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => handleSelect(option.value)}
|
||||
class="w-full border-b border-neutral-700 px-3 py-2 text-left last:border-b-0 hover:bg-neutral-600"
|
||||
class:bg-neutral-700={value === option.value}
|
||||
class:dropdown-sm-option={variant === 'sm'}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.dropdown-sm {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.dropdown-sm-btn {
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
padding-left: 0.5rem;
|
||||
padding-right: 0.5rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.dropdown-sm-list {
|
||||
min-width: 160px;
|
||||
}
|
||||
.dropdown-sm-input {
|
||||
padding-top: 0;
|
||||
padding-bottom: 0;
|
||||
padding-left: 0.5rem;
|
||||
padding-right: 0.5rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
.dropdown-sm-option {
|
||||
padding-top: 0.15rem;
|
||||
padding-bottom: 0.15rem;
|
||||
padding-left: 0.5rem;
|
||||
padding-right: 0.5rem;
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,31 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from '$app/paths';
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="mb-5 max-h-10 w-full border-t border-neutral-800 pt-5 text-center text-sm text-neutral-500"
|
||||
>
|
||||
<a
|
||||
href="https://github.com/whoswhip/Sharpbin"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-neutral-400 underline hover:text-neutral-200"
|
||||
>
|
||||
Source Code
|
||||
</a>
|
||||
<span class="mx-1">•</span>
|
||||
<a href={resolve('/stats')} class="text-neutral-400 underline hover:text-neutral-200"
|
||||
>Statistics</a
|
||||
>
|
||||
<span class="mx-1">•</span>
|
||||
v{__APP_VERSION__}
|
||||
<a
|
||||
href="https://github.com/whoswhip/Sharpbin/commit/{COMMIT_HASH}"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-neutral-400 underline hover:text-neutral-200"
|
||||
>{(COMMIT_HASH?.length ?? 0) >= 7 && COMMIT_HASH !== 'unknown'
|
||||
? `(${COMMIT_HASH.slice(0, 7)})`
|
||||
: ''}</a
|
||||
>
|
||||
</div>
|
||||
@@ -1,576 +0,0 @@
|
||||
<script lang="ts">
|
||||
import QRCode from 'qrcode';
|
||||
import { getRefreshToken, getToken, setTokens } from '#lib/utils/auth';
|
||||
import { parseTotpEnabled } from '#lib/utils/totp';
|
||||
import { tick } from 'svelte';
|
||||
import { extractError } from '#lib/utils/misc';
|
||||
import type { ModalItem, ModalMode } from '#lib/types/modal';
|
||||
|
||||
interface Props {
|
||||
show?: boolean;
|
||||
mode?: ModalMode;
|
||||
title?: string;
|
||||
message?: string;
|
||||
error?: string;
|
||||
placeholder?: string;
|
||||
inputType?: string;
|
||||
inputMaxLength?: number | null;
|
||||
items?: ModalItem[];
|
||||
initialValue?: unknown;
|
||||
totpActive?: boolean | null;
|
||||
reportTarget?: 'user' | 'paste' | null;
|
||||
reportTargetId?: string | number | null;
|
||||
reportSiteKey?: string | null;
|
||||
onConfirm: (value: unknown) => void;
|
||||
onCancel: () => void;
|
||||
confirmButtonText?: string;
|
||||
}
|
||||
|
||||
let {
|
||||
show = false,
|
||||
mode = 'decrypt',
|
||||
title = '',
|
||||
message = '',
|
||||
error = $bindable(''),
|
||||
placeholder = '',
|
||||
inputType = 'text',
|
||||
inputMaxLength = null,
|
||||
items = [],
|
||||
initialValue = null,
|
||||
totpActive = null,
|
||||
reportTarget = null,
|
||||
reportTargetId = null,
|
||||
reportSiteKey = null,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
confirmButtonText = ''
|
||||
}: Props = $props();
|
||||
|
||||
let inputValue: string | unknown[] | boolean = $state('');
|
||||
let totpSecret = $state('');
|
||||
let totpQr = $state('');
|
||||
let totpEnabled = $state(false);
|
||||
let totpInitialized = $state(false);
|
||||
let totpLoading = $state(false);
|
||||
let totpError = $state('');
|
||||
let displayError = $derived(error || totpError);
|
||||
let reportTypes: string[] = $state([]);
|
||||
let reportType = $state('');
|
||||
let reportInitialized = $state(false);
|
||||
let reportLoading = $state(false);
|
||||
let multiselectInitialized = $state(false);
|
||||
let turnstileEl: HTMLDivElement | null = $state(null);
|
||||
let turnstileWidgetId: string | null = null;
|
||||
|
||||
const titleMap = {
|
||||
decrypt: 'Enter password to decrypt',
|
||||
encrypt: 'Enter password to encrypt',
|
||||
confirm: 'Confirm action',
|
||||
multiselect: 'Select items',
|
||||
totpSetup: 'Set up two-factor authentication',
|
||||
totp: 'Enter TOTP code',
|
||||
report: 'Create Report',
|
||||
prompt: 'Input Required'
|
||||
};
|
||||
|
||||
const confirmLabelMap = {
|
||||
decrypt: 'Decrypt',
|
||||
encrypt: 'Encrypt',
|
||||
confirm: 'Confirm',
|
||||
multiselect: 'Confirm',
|
||||
totpSetup: 'Enable',
|
||||
totp: 'Verify',
|
||||
report: 'Submit Report',
|
||||
prompt: 'Submit'
|
||||
};
|
||||
|
||||
function resetModal() {
|
||||
inputValue =
|
||||
initialValue !== null
|
||||
? JSON.parse(JSON.stringify(initialValue))
|
||||
: mode === 'multiselect'
|
||||
? []
|
||||
: '';
|
||||
totpSecret = '';
|
||||
totpQr = '';
|
||||
totpEnabled = false;
|
||||
totpInitialized = false;
|
||||
totpLoading = false;
|
||||
totpError = '';
|
||||
reportTypes = [];
|
||||
reportType = '';
|
||||
reportInitialized = false;
|
||||
reportLoading = false;
|
||||
multiselectInitialized = false;
|
||||
if (turnstileWidgetId && typeof window !== 'undefined' && window.turnstile?.remove) {
|
||||
window.turnstile.remove(turnstileWidgetId);
|
||||
}
|
||||
turnstileEl = null;
|
||||
turnstileWidgetId = null;
|
||||
}
|
||||
|
||||
function getCodeOrError(message: string) {
|
||||
if (typeof inputValue !== 'string') {
|
||||
totpError = message;
|
||||
return null;
|
||||
}
|
||||
const code = inputValue.trim();
|
||||
if (!code) {
|
||||
totpError = message;
|
||||
return null;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
function onCodeInput(e: Event) {
|
||||
if (!(e.target instanceof HTMLInputElement)) return;
|
||||
const sanitized = e.target.value.replace(/\D/g, '').slice(0, 6);
|
||||
e.target.value = sanitized;
|
||||
inputValue = sanitized;
|
||||
}
|
||||
|
||||
async function initializeTotp() {
|
||||
totpError = '';
|
||||
totpLoading = true;
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
totpError = 'You need to be logged in to manage TOTP.';
|
||||
totpLoading = false;
|
||||
return;
|
||||
}
|
||||
if (totpEnabled || parseTotpEnabled(token)) {
|
||||
totpEnabled = true;
|
||||
totpLoading = false;
|
||||
return;
|
||||
}
|
||||
const res = await fetch('/api/auth/totp/enroll', {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
totpError = extractError(data) || 'Failed to start TOTP enrollment.';
|
||||
totpLoading = false;
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
totpSecret = data.secret || '';
|
||||
if (data.otpauth) {
|
||||
totpQr = await QRCode.toDataURL(data.otpauth, { margin: 1, width: 300 });
|
||||
}
|
||||
totpLoading = false;
|
||||
}
|
||||
|
||||
async function initializeReport() {
|
||||
reportLoading = true;
|
||||
error = '';
|
||||
try {
|
||||
const res = await fetch('/api/report/options');
|
||||
if (!res.ok) {
|
||||
reportLoading = false;
|
||||
error = 'Failed to load report options.';
|
||||
return;
|
||||
}
|
||||
const data = (await res.json().catch(() => null)) || {};
|
||||
const types = data.types || data.Types || [];
|
||||
reportTypes = Array.isArray(types) ? types : [];
|
||||
reportType = reportTypes.includes(reportType) ? reportType : reportTypes[0] || '';
|
||||
reportLoading = false;
|
||||
if (reportSiteKey) {
|
||||
await tick();
|
||||
renderTurnstile();
|
||||
}
|
||||
} catch {
|
||||
reportLoading = false;
|
||||
error = 'Failed to load report options.';
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshTokens() {
|
||||
const token = getToken();
|
||||
const refreshToken = getRefreshToken();
|
||||
if (!token || !refreshToken) return null;
|
||||
console.log('Refreshing tokens after TOTP change...');
|
||||
const res = await fetch('/api/auth/refresh', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token, refreshToken })
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
if (data.token?.token && data.token?.refreshToken && data.token?.success !== false) {
|
||||
setTokens(data.token.token, data.token.refreshToken);
|
||||
console.log('Tokens refreshed after TOTP change.');
|
||||
return data.token.token as string;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function handleSubmit(event: Event) {
|
||||
event.preventDefault();
|
||||
if (mode === 'report') {
|
||||
await submitReport();
|
||||
return;
|
||||
}
|
||||
if (mode === 'totp') {
|
||||
if (!inputValue || typeof inputValue !== 'string') return;
|
||||
onConfirm(inputValue.trim());
|
||||
return;
|
||||
}
|
||||
if (mode === 'totpSetup') {
|
||||
await submitTotp();
|
||||
return;
|
||||
}
|
||||
onConfirm(mode === 'confirm' ? true : inputValue);
|
||||
}
|
||||
|
||||
function renderTurnstile() {
|
||||
if (!reportSiteKey || typeof window === 'undefined') return;
|
||||
const mount = () => {
|
||||
if (!turnstileEl || !window.turnstile) return;
|
||||
if (turnstileWidgetId && window.turnstile.remove) {
|
||||
window.turnstile.remove(turnstileWidgetId);
|
||||
}
|
||||
turnstileWidgetId = window.turnstile.render(turnstileEl, {
|
||||
sitekey: reportSiteKey,
|
||||
theme: 'dark',
|
||||
size: 'flexible',
|
||||
appearence: 'interaction-only'
|
||||
});
|
||||
};
|
||||
if (window.turnstile) {
|
||||
mount();
|
||||
return;
|
||||
}
|
||||
const existing = document.querySelector('script[data-turnstile="true"]');
|
||||
if (!existing) {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
|
||||
script.async = true;
|
||||
script.defer = true;
|
||||
script.dataset.turnstile = 'true';
|
||||
script.onload = () => window.dispatchEvent(new Event('turnstile:loaded'));
|
||||
document.body.appendChild(script);
|
||||
}
|
||||
const handler = () => {
|
||||
mount();
|
||||
window.removeEventListener('turnstile:loaded', handler);
|
||||
};
|
||||
window.addEventListener('turnstile:loaded', handler, { once: true });
|
||||
}
|
||||
|
||||
async function submitReport() {
|
||||
error = '';
|
||||
if (!reportTarget || reportTargetId === null) {
|
||||
error = 'Missing report target.';
|
||||
return;
|
||||
}
|
||||
if (typeof inputValue !== 'string') inputValue = '';
|
||||
const description = inputValue.trim();
|
||||
if (!description) {
|
||||
error = 'Description is required.';
|
||||
return;
|
||||
}
|
||||
if (description.length < 12) {
|
||||
error = 'Description must be at least 12 characters.';
|
||||
return;
|
||||
}
|
||||
if (description.length > 1000) {
|
||||
error = 'Description must be 1000 characters or less.';
|
||||
return;
|
||||
}
|
||||
const type = reportType || reportTypes[0] || '';
|
||||
if (!type) {
|
||||
error = 'Select a report type.';
|
||||
return;
|
||||
}
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
error = 'You need to be logged in to report.';
|
||||
return;
|
||||
}
|
||||
const body: Record<string, unknown> = { description, reportType: type };
|
||||
if (reportSiteKey) {
|
||||
if (typeof window === 'undefined' || !window.turnstile) {
|
||||
error = 'Verification unavailable.';
|
||||
return;
|
||||
}
|
||||
const verification = window.turnstile.getResponse();
|
||||
if (!verification) {
|
||||
error = 'Complete verification.';
|
||||
return;
|
||||
}
|
||||
body.VerificationToken = verification;
|
||||
}
|
||||
const targetId = encodeURIComponent(String(reportTargetId));
|
||||
const reportPath = reportTarget === 'paste' ? 'pastes' : 'users';
|
||||
const res = await fetch(`/api/report/${reportPath}/${targetId}/report`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
error = extractError(data) || 'Failed to submit report.';
|
||||
if (reportSiteKey && typeof window !== 'undefined' && window.turnstile) {
|
||||
window.turnstile.reset();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const data = await res.json().catch(() => null);
|
||||
if (reportSiteKey && typeof window !== 'undefined' && window.turnstile) {
|
||||
window.turnstile.reset();
|
||||
}
|
||||
onConfirm(data || { description, reportType: type });
|
||||
}
|
||||
|
||||
async function submitTotp() {
|
||||
if (totpEnabled) {
|
||||
await disableTotp();
|
||||
return;
|
||||
}
|
||||
if (!totpSecret) {
|
||||
totpError = 'Missing TOTP secret. Please reopen the modal.';
|
||||
return;
|
||||
}
|
||||
const code = getCodeOrError('Enter the TOTP code from your authenticator app.');
|
||||
if (!code) return;
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
totpError = 'You need to be logged in to enable TOTP.';
|
||||
return;
|
||||
}
|
||||
const res = await fetch('/api/auth/totp/enable', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ secret: totpSecret, code: code })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
totpError = data?.message || 'Failed to enable TOTP.';
|
||||
return;
|
||||
}
|
||||
const newToken = await refreshTokens();
|
||||
totpEnabled = parseTotpEnabled(newToken || getToken());
|
||||
onConfirm({ enabled: totpEnabled, secret: totpSecret });
|
||||
}
|
||||
|
||||
async function disableTotp() {
|
||||
const code = getCodeOrError('Enter the TOTP code to disable two-factor authentication.');
|
||||
if (!code) return;
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
totpError = 'You need to be logged in to disable TOTP.';
|
||||
return;
|
||||
}
|
||||
const res = await fetch('/api/auth/totp/disable', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ code: code })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
totpError = data?.message || 'Failed to disable TOTP.';
|
||||
return;
|
||||
}
|
||||
const newToken = await refreshTokens();
|
||||
totpEnabled = parseTotpEnabled(newToken || getToken());
|
||||
onConfirm({ enabled: totpEnabled });
|
||||
}
|
||||
|
||||
async function copySecret() {
|
||||
if (!totpSecret) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(totpSecret);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!show) resetModal();
|
||||
});
|
||||
$effect(() => {
|
||||
if (show && mode === 'totpSetup' && !totpInitialized) {
|
||||
totpInitialized = true;
|
||||
if (totpActive !== null) {
|
||||
totpEnabled = totpActive;
|
||||
}
|
||||
initializeTotp();
|
||||
}
|
||||
});
|
||||
$effect(() => {
|
||||
if (show && mode === 'report' && !reportInitialized) {
|
||||
reportInitialized = true;
|
||||
initializeReport();
|
||||
}
|
||||
});
|
||||
$effect(() => {
|
||||
if (show && mode === 'multiselect' && !multiselectInitialized) {
|
||||
multiselectInitialized = true;
|
||||
inputValue = Array.isArray(initialValue) ? JSON.parse(JSON.stringify(initialValue)) : [];
|
||||
}
|
||||
});
|
||||
let displayTitle = $derived(title || titleMap[mode]);
|
||||
let confirmLabel = $derived(
|
||||
confirmButtonText ||
|
||||
(mode === 'totpSetup' ? (totpEnabled ? 'Disable' : 'Enable') : confirmLabelMap[mode])
|
||||
);
|
||||
let shouldShowInput = $derived(
|
||||
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report'
|
||||
);
|
||||
</script>
|
||||
|
||||
{#if show}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/20 backdrop-blur-xs">
|
||||
<form
|
||||
onsubmit={handleSubmit}
|
||||
class="w-full max-w-md rounded border border-neutral-800 bg-neutral-900 p-6"
|
||||
>
|
||||
<h2 class="mb-4 text-xl font-semibold text-white">
|
||||
{displayTitle}
|
||||
</h2>
|
||||
|
||||
{#if message}
|
||||
<p class="mb-4 text-neutral-300">
|
||||
{message}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if mode === 'totpSetup'}
|
||||
<div class="mb-4 space-y-3">
|
||||
<div
|
||||
class="rounded border border-neutral-700 bg-neutral-800 p-3 text-sm text-neutral-200"
|
||||
>
|
||||
{totpEnabled
|
||||
? 'Two-factor authentication is enabled. Enter a current 6-digit code to disable it.'
|
||||
: 'Scan the QR code with your authenticator app or copy the secret to add it manually.'}
|
||||
</div>
|
||||
{#if totpLoading}
|
||||
<p class="text-neutral-300">Preparing TOTP enrollment...</p>
|
||||
{:else}
|
||||
{#if !totpEnabled}
|
||||
{#if totpQr}
|
||||
<div class="flex justify-center">
|
||||
<img
|
||||
src={totpQr}
|
||||
alt="TOTP QR code"
|
||||
class="aspect-square w-full rounded bg-white object-contain p-2"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
{#if totpSecret}
|
||||
<div
|
||||
class="flex items-center gap-2 rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||
>
|
||||
<span class="flex-1 truncate font-mono text-sm text-neutral-100"
|
||||
>{totpSecret}</span
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onclick={copySecret}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-sm font-medium text-white transition-colors hover:bg-neutral-800"
|
||||
>
|
||||
Copy
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
<input
|
||||
type="text"
|
||||
bind:value={inputValue}
|
||||
placeholder="Enter the 6-digit code"
|
||||
maxlength="6"
|
||||
inputmode="numeric"
|
||||
pattern="[0-9]*"
|
||||
oninput={onCodeInput}
|
||||
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if mode === 'report'}
|
||||
<div class="mb-4 space-y-3">
|
||||
{#if reportLoading}
|
||||
<p class="text-neutral-300">Loading report options...</p>
|
||||
{:else}
|
||||
{#if reportTypes.length}
|
||||
<select
|
||||
bind:value={reportType}
|
||||
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
|
||||
>
|
||||
{#each reportTypes as type, i (i)}
|
||||
<option value={type}>{type.replace(/([A-Z])/g, ' $1').trim()}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{/if}
|
||||
<textarea
|
||||
bind:value={inputValue}
|
||||
maxlength={inputMaxLength ?? undefined}
|
||||
placeholder={placeholder || 'Describe the issue'}
|
||||
class="h-28 w-full resize-none rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
|
||||
></textarea>
|
||||
{#if reportSiteKey}
|
||||
<div class="cf-turnstile w-full" bind:this={turnstileEl}></div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{:else if shouldShowInput}
|
||||
<input
|
||||
type={inputType}
|
||||
maxlength={inputMaxLength ?? undefined}
|
||||
bind:value={inputValue}
|
||||
class="mb-3 w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
|
||||
{placeholder}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
{#if mode === 'multiselect'}
|
||||
<div
|
||||
class="mb-4 max-h-60 overflow-y-auto rounded border border-neutral-700 bg-neutral-800 p-2"
|
||||
>
|
||||
{#each items as item (item.label)}
|
||||
<label
|
||||
class="flex cursor-pointer items-center gap-2 rounded p-2 text-white hover:bg-neutral-700"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
bind:group={inputValue}
|
||||
value={item.value}
|
||||
class="h-4 w-4 rounded border-neutral-600 bg-neutral-700 text-neutral-500"
|
||||
/>
|
||||
<span>{item.label}</span>
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if displayError}
|
||||
<div class="mb-3 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
|
||||
{displayError}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex gap-2">
|
||||
<button
|
||||
type="submit"
|
||||
class={`flex-1 cursor-pointer rounded px-4 py-2 font-semibold text-white transition-colors ${
|
||||
mode === 'confirm'
|
||||
? 'bg-red-900 hover:bg-red-800'
|
||||
: 'bg-neutral-700 hover:bg-neutral-800'
|
||||
}`}
|
||||
>
|
||||
{confirmLabel}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={onCancel}
|
||||
class="cursor-pointer rounded border border-neutral-700 px-4 py-2 text-white hover:bg-neutral-950"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,26 +0,0 @@
|
||||
<script lang="ts">
|
||||
import Modal from '#lib/components/Modal.svelte';
|
||||
import { cancelModal, confirmModal, modal } from '#lib/stores/modal';
|
||||
|
||||
let state = $derived($modal);
|
||||
</script>
|
||||
|
||||
<Modal
|
||||
show={state.show}
|
||||
mode={state.mode}
|
||||
title={state.title}
|
||||
message={state.message}
|
||||
error={state.error}
|
||||
placeholder={state.placeholder}
|
||||
inputType={state.inputType}
|
||||
inputMaxLength={state.maxInputLength ?? null}
|
||||
items={state.items}
|
||||
initialValue={state.initialValue}
|
||||
totpActive={state.totpActive}
|
||||
reportTarget={state.reportTarget}
|
||||
reportTargetId={state.reportTargetId}
|
||||
reportSiteKey={state.reportSiteKey}
|
||||
confirmButtonText={state.confirmButtonText}
|
||||
onConfirm={(value) => confirmModal(value)}
|
||||
onCancel={() => cancelModal()}
|
||||
/>
|
||||
@@ -1,175 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { user } from '#lib/stores/user';
|
||||
import { resolve } from '$app/paths';
|
||||
import { page } from '$app/state';
|
||||
import { clearTokens, hasRole } from '#lib/utils/auth';
|
||||
import logo from '#lib/assets/favicon.svg';
|
||||
import type { PageData } from '../../routes/$types';
|
||||
import { slide } from 'svelte/transition';
|
||||
import { Menu, X } from '@lucide/svelte';
|
||||
import { onMount } from 'svelte';
|
||||
|
||||
function logout() {
|
||||
clearTokens();
|
||||
user.set(null);
|
||||
window.location.href = '/';
|
||||
}
|
||||
|
||||
interface Props {
|
||||
data: PageData;
|
||||
}
|
||||
|
||||
let { data }: Props = $props();
|
||||
|
||||
let menuOpen = $state(false);
|
||||
|
||||
let currentPath = page.url.pathname;
|
||||
let returnParam =
|
||||
currentPath !== '/' && !currentPath.startsWith('/login') && !currentPath.startsWith('/register')
|
||||
? `?return=${encodeURIComponent(page.url.pathname + page.url.search)}`
|
||||
: '';
|
||||
|
||||
function handleClickOutside(event: MouseEvent) {
|
||||
const navbar = document.getElementById('navbar');
|
||||
const mobileMenu = document.getElementById('mobile-menu');
|
||||
if (menuOpen && mobileMenu && navbar && !navbar.contains(event.target as Node)) {
|
||||
menuOpen = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
document.addEventListener('click', handleClickOutside);
|
||||
return () => {
|
||||
document.removeEventListener('click', handleClickOutside);
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="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="flex items-center gap-6">
|
||||
<a href={resolve('/')} class="group flex items-center gap-2">
|
||||
<img src={logo} alt="Sharpbin Logo" class="h-7 w-7 group-hover:opacity-80" />
|
||||
<span class="text-xl font-bold text-white group-hover:text-neutral-300">Sharpbin</span>
|
||||
</a>
|
||||
<div class="h-5 w-px bg-neutral-700"></div>
|
||||
<a
|
||||
href={resolve('/recent')}
|
||||
class="relative text-neutral-300 after:absolute after:-bottom-0.5 after:left-0 after:h-px after:w-0 after:bg-white after:transition-all hover:text-white hover:after:w-full"
|
||||
>Recent Pastes</a
|
||||
>
|
||||
</div>
|
||||
{#if $user}
|
||||
<div class="ml-auto flex items-center space-x-4">
|
||||
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
|
||||
<a
|
||||
href={resolve('/reports')}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||
>Reports</a
|
||||
>
|
||||
{/if}
|
||||
<a
|
||||
href={resolve(`/user/${$user.username}`)}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||
>Profile</a
|
||||
>
|
||||
<button
|
||||
onclick={logout}
|
||||
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||
>Logout</button
|
||||
>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="ml-auto flex items-center space-x-4">
|
||||
<a
|
||||
href={resolve(`/login${returnParam}`)}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||
>Login</a
|
||||
>
|
||||
<!-- eslint-disable svelte/no-navigation-without-resolve -->
|
||||
<a
|
||||
href={data.options?.registration_enabled ? resolve(`/register${returnParam}`) : '#'}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600 {data
|
||||
.options?.registration_enabled
|
||||
? ''
|
||||
: 'cursor-not-allowed bg-neutral-800 text-neutral-500!'}">Register</a
|
||||
>
|
||||
<!-- eslint-enable svelte/no-navigation-without-resolve -->
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="mx-auto flex h-15 w-[90%] max-w-7xl items-center py-2 md:hidden">
|
||||
<a href={resolve('/')} class="group">
|
||||
<img src={logo} alt="Sharpbin Logo" class="h-8 w-8 group-hover:opacity-80" />
|
||||
</a>
|
||||
<button
|
||||
class="ml-auto flex h-10 w-10 items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 hover:bg-neutral-700 focus:outline-none"
|
||||
onclick={() => (menuOpen = !menuOpen)}
|
||||
aria-label="Toggle Menu"
|
||||
aria-expanded={menuOpen}
|
||||
>
|
||||
{#if menuOpen}
|
||||
<X class="pointer-events-none h-6 w-6 text-white" />
|
||||
{:else}
|
||||
<Menu class="pointer-events-none h-6 w-6 text-white" />
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
{#if menuOpen}
|
||||
<div
|
||||
class="mx-auto mb-2 w-full rounded-b border-b border-neutral-800 bg-neutral-900 px-2 py-3 md:hidden"
|
||||
id="mobile-menu"
|
||||
in:slide={{ duration: 180 }}
|
||||
out:slide={{ duration: 180 }}
|
||||
style="z-index:1000;position:relative;"
|
||||
>
|
||||
<a
|
||||
href={resolve('/recent')}
|
||||
class="block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||
onclick={() => (menuOpen = false)}>Recent Pastes</a
|
||||
>
|
||||
{#if $user}
|
||||
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
|
||||
<a
|
||||
href={resolve('/reports')}
|
||||
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||
onclick={() => (menuOpen = false)}>Reports</a
|
||||
>
|
||||
{/if}
|
||||
<a
|
||||
href={resolve(`/user/${$user.username}`)}
|
||||
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||
onclick={() => (menuOpen = false)}>Profile</a
|
||||
>
|
||||
<button
|
||||
onclick={() => {
|
||||
logout();
|
||||
menuOpen = false;
|
||||
}}
|
||||
class="mt-1 w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||
>Logout</button
|
||||
>
|
||||
{:else}
|
||||
<a
|
||||
href={resolve(`/login${returnParam}`)}
|
||||
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||
onclick={() => (menuOpen = false)}>Login</a
|
||||
>
|
||||
<!-- eslint-disable svelte/no-navigation-without-resolve -->
|
||||
<a
|
||||
href={data.options?.registration_enabled ? resolve(`/register${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 {data
|
||||
.options?.registration_enabled
|
||||
? ''
|
||||
: 'cursor-not-allowed bg-neutral-900 text-neutral-500'}"
|
||||
onclick={() => (menuOpen = false)}>Register</a
|
||||
>
|
||||
<!-- eslint-enable svelte/no-navigation-without-resolve -->
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,217 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { tooltip, dateToRelativeString, formatNumber, formatBytes } from '#lib/utils/misc';
|
||||
import { resolve } from '$app/paths';
|
||||
import {
|
||||
Eye,
|
||||
FileBox,
|
||||
Code,
|
||||
User,
|
||||
History,
|
||||
CalendarDays,
|
||||
CalendarOff,
|
||||
Lock,
|
||||
EyeOff,
|
||||
Globe,
|
||||
HatGlasses,
|
||||
ThumbsUp
|
||||
} from '@lucide/svelte';
|
||||
import { syntaxes } from '#lib/consts';
|
||||
import type { Paste } from '#lib/types/paste';
|
||||
|
||||
interface Props {
|
||||
paste: Paste;
|
||||
now: Date;
|
||||
showUser?: boolean;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
let { paste, now, showUser = true, compact = false }: Props = $props();
|
||||
|
||||
let syntax = $derived(syntaxes[paste.syntax] ?? syntaxes['plaintext']);
|
||||
let netLikes = $derived(paste.likes - paste.dislikes);
|
||||
let netLikeText = $derived(`${formatNumber(netLikes)} Like${netLikes === 1 ? '' : 's'}`);
|
||||
</script>
|
||||
|
||||
{#if compact}
|
||||
<a
|
||||
href={resolve(`/[id]`, { id: paste.id })}
|
||||
class="flex flex-col gap-1 rounded border border-neutral-700 bg-neutral-800 px-4 py-3 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
|
||||
>
|
||||
<div class="flex w-full flex-row justify-between">
|
||||
<span
|
||||
class="text-md w-fit max-w-full truncate font-semibold text-neutral-100 hover:text-white"
|
||||
use:tooltip={paste.title || 'Untitled Paste'}
|
||||
>
|
||||
{paste.title || 'Untitled Paste'}
|
||||
</span>
|
||||
<div
|
||||
class="flex items-center gap-2 text-sm text-neutral-400"
|
||||
use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
|
||||
>
|
||||
<CalendarDays class="h-4 w-4" />
|
||||
{#if paste.createdAt}
|
||||
{#if paste.createdAt > Date.now() - 86_400_000}
|
||||
Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
|
||||
{:else}
|
||||
{new Date(paste.createdAt).toLocaleDateString()}
|
||||
{/if}
|
||||
{:else}
|
||||
Creation date unknown
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-row justify-between text-sm text-neutral-400">
|
||||
<div>
|
||||
{#if showUser}
|
||||
<div class="flex items-center gap-2">
|
||||
{#if paste.author}
|
||||
<User class="h-4 w-4" />
|
||||
{:else}
|
||||
<HatGlasses class="h-4 w-4" />
|
||||
{/if}
|
||||
{paste.author?.username ?? 'Anonymous'}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex items-center gap-2">
|
||||
{#if paste.visibility === 0}
|
||||
<Globe class="h-4 w-4" />
|
||||
Public
|
||||
{:else if paste.visibility === 1}
|
||||
<EyeOff class="h-4 w-4" />
|
||||
Unlisted
|
||||
{:else}
|
||||
<Lock class="h-4 w-4" />
|
||||
Private
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<span class="flex items-center gap-2">
|
||||
<Eye class="h-4 w-4" />
|
||||
{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<span
|
||||
class="flex items-center gap-2"
|
||||
use:tooltip={`${formatNumber(paste.likes)} likes, ${formatNumber(paste.dislikes)} dislikes`}
|
||||
>
|
||||
<ThumbsUp class="h-4 w-4" />
|
||||
{netLikeText}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div
|
||||
class="flex items-center gap-2"
|
||||
use:tooltip={paste.isCompressed
|
||||
? `Compressed Size: ${formatBytes(paste.storedSize)}`
|
||||
: ''}
|
||||
>
|
||||
<FileBox class="h-4 w-4" />
|
||||
{formatBytes(paste.originalSize)}
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<Code class="h-4 w-4" />
|
||||
{syntax.name}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
{:else}
|
||||
<a
|
||||
href={resolve(`/[id]`, { id: paste.id })}
|
||||
class="flex flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
|
||||
>
|
||||
<span
|
||||
class="w-fit max-w-full truncate text-lg font-semibold text-neutral-100 hover:text-white"
|
||||
use:tooltip={paste.title || 'Untitled Paste'}
|
||||
>
|
||||
{paste.title || 'Untitled Paste'}
|
||||
</span>
|
||||
<div class="flex flex-row justify-between">
|
||||
<div>
|
||||
<div
|
||||
class="flex items-center gap-2 text-sm text-neutral-400"
|
||||
use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
|
||||
>
|
||||
<CalendarDays class="h-4 w-4" />
|
||||
<span>
|
||||
{#if paste.createdAt}
|
||||
{#if paste.createdAt > Date.now() - 86_400_000}
|
||||
Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
|
||||
{:else}
|
||||
Created on {new Date(paste.createdAt).toLocaleDateString()}
|
||||
{/if}
|
||||
{:else}
|
||||
Creation date unknown
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{#if paste.editedAt && paste.editedAt != 0}
|
||||
<div
|
||||
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
|
||||
use:tooltip={new Date(paste.editedAt).toLocaleString()}
|
||||
>
|
||||
<History class="h-4 w-4" />
|
||||
<span>
|
||||
{#if paste.editedAt > Date.now() - 86_400_000}
|
||||
Edited {dateToRelativeString(new Date(paste.editedAt), true, false, now)}
|
||||
{:else}
|
||||
Edited on {new Date(paste.editedAt).toLocaleDateString()}
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if paste.expiresAt > 0}
|
||||
<div
|
||||
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
|
||||
use:tooltip={new Date(paste.expiresAt).toLocaleString()}
|
||||
>
|
||||
<CalendarOff class="h-4 w-4" />
|
||||
<span>
|
||||
{paste.expiresAt > 0 && paste.expiresAt < Date.now()
|
||||
? `Expired ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`
|
||||
: `Expires in ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`}
|
||||
</span>
|
||||
</div>
|
||||
{/if}
|
||||
{#if showUser}
|
||||
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
|
||||
{#if paste.author}
|
||||
<User class="h-4 w-4" />
|
||||
{:else}
|
||||
<HatGlasses class="h-4 w-4" />
|
||||
{/if}
|
||||
<span>{paste.author?.username ?? 'Anonymous'}</span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="grid grid-cols-[auto_auto] gap-x-4 gap-y-1 text-sm text-neutral-400">
|
||||
<div class="flex items-center gap-2">
|
||||
<Eye class="h-4 w-4" />
|
||||
<span>{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}</span>
|
||||
</div>
|
||||
<div
|
||||
class="flex items-center gap-2"
|
||||
use:tooltip={`${formatNumber(paste.likes)} likes, ${formatNumber(paste.dislikes)} dislikes`}
|
||||
>
|
||||
<ThumbsUp class="h-4 w-4" />
|
||||
<span>{netLikeText}</span>
|
||||
</div>
|
||||
<div
|
||||
class="flex items-center gap-2"
|
||||
use:tooltip={paste.isCompressed
|
||||
? `Compressed Size: ${formatBytes(paste.storedSize)}`
|
||||
: ''}
|
||||
>
|
||||
<FileBox class="h-4 w-4" />
|
||||
<span>{formatBytes(paste.originalSize)}</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<Code class="h-4 w-4" />
|
||||
<span>{syntax.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</a>
|
||||
{/if}
|
||||
@@ -1,290 +0,0 @@
|
||||
<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/[username]`, { username: 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>
|
||||
@@ -1,305 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { getToken } from '#lib/utils/auth';
|
||||
import { user } from '#lib/stores/user';
|
||||
import type {
|
||||
CommentReaction,
|
||||
CommentReactionResult,
|
||||
PasteComment,
|
||||
CommentTreeNode
|
||||
} from '#lib/types/comment';
|
||||
import PasteCommentItem from '#lib/components/PasteCommentItem.svelte';
|
||||
import { SvelteMap } from 'svelte/reactivity';
|
||||
import RichTextEditor from './RichTextEditor.svelte';
|
||||
import { openModal } from '#lib/stores/modal';
|
||||
import { RefreshCw } from '@lucide/svelte';
|
||||
|
||||
interface Props {
|
||||
pasteId: string;
|
||||
initialComments?: PasteComment[];
|
||||
}
|
||||
|
||||
let { pasteId, initialComments = [] }: Props = $props();
|
||||
|
||||
let comments = $derived.by(() => [...initialComments]);
|
||||
let loading = $state(false);
|
||||
let posting = $state(false);
|
||||
let now = $state(new Date());
|
||||
let interval: ReturnType<typeof setInterval> | null = null;
|
||||
let errorMessage = $state('');
|
||||
let newComment = $state('');
|
||||
let reactingIds = $state<Record<number, boolean>>({});
|
||||
|
||||
const sortedComments = $derived(
|
||||
[...comments].sort((a, b) => {
|
||||
if (a.createdAt !== b.createdAt) return a.createdAt - b.createdAt;
|
||||
return a.id - b.id;
|
||||
})
|
||||
);
|
||||
const threadedComments = $derived(buildCommentTree(sortedComments));
|
||||
|
||||
onMount(() => {
|
||||
interval = setInterval(() => {
|
||||
now = new Date();
|
||||
}, 1000 * 30);
|
||||
void refreshComments();
|
||||
return () => {
|
||||
if (interval) clearInterval(interval);
|
||||
};
|
||||
});
|
||||
|
||||
function buildCommentTree(list: PasteComment[]): CommentTreeNode[] {
|
||||
const nodes = new SvelteMap<number, CommentTreeNode>();
|
||||
const roots: CommentTreeNode[] = [];
|
||||
|
||||
for (const comment of list) {
|
||||
nodes.set(comment.id, {
|
||||
...comment,
|
||||
children: []
|
||||
});
|
||||
}
|
||||
|
||||
for (const node of nodes.values()) {
|
||||
if (node.parentCommentID && nodes.has(node.parentCommentID)) {
|
||||
nodes.get(node.parentCommentID)?.children.push(node);
|
||||
} else {
|
||||
roots.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
async function refreshComments() {
|
||||
loading = true;
|
||||
errorMessage = '';
|
||||
const token = getToken();
|
||||
const headers = new Headers();
|
||||
if (token) headers.set('Authorization', `Bearer ${token}`);
|
||||
try {
|
||||
const res = await fetch(`/api/paste/${pasteId}/comments`, { headers });
|
||||
if (!res.ok) {
|
||||
errorMessage = 'Failed to load comments.';
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
const json = await res.json();
|
||||
comments = Array.isArray(json?.comments) ? (json.comments as PasteComment[]) : [];
|
||||
} catch {
|
||||
errorMessage = 'Failed to load comments.';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function postComment(content: string, parentCommentID: number | null): Promise<boolean> {
|
||||
errorMessage = '';
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
errorMessage = 'You must be signed in to comment.';
|
||||
return false;
|
||||
}
|
||||
const trimmed = content.trim();
|
||||
if (!trimmed) {
|
||||
errorMessage = 'Comment cannot be empty.';
|
||||
return false;
|
||||
}
|
||||
|
||||
if (parentCommentID === null) posting = true;
|
||||
try {
|
||||
const res = await fetch(`/api/paste/${pasteId}/comments`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ content: trimmed, parentCommentID })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
errorMessage = err?.message || 'Failed to post comment.';
|
||||
return false;
|
||||
}
|
||||
const json = await res.json();
|
||||
const created = json?.comment as PasteComment | undefined;
|
||||
if (!created) {
|
||||
errorMessage = 'Failed to post comment.';
|
||||
return false;
|
||||
}
|
||||
comments = [...comments, created];
|
||||
if (parentCommentID === null) newComment = '';
|
||||
return true;
|
||||
} catch {
|
||||
errorMessage = 'Failed to post comment.';
|
||||
return false;
|
||||
} finally {
|
||||
if (parentCommentID === null) posting = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function reactToComment(commentId: number, target: 1 | 2, current: CommentReaction) {
|
||||
errorMessage = '';
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
errorMessage = 'You must be signed in to react.';
|
||||
return;
|
||||
}
|
||||
|
||||
reactingIds = { ...reactingIds, [commentId]: true };
|
||||
const nextReaction: CommentReaction = current === target ? null : target;
|
||||
try {
|
||||
const res = await fetch(`/api/paste/${pasteId}/comments/${commentId}/reaction`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify({ reaction: nextReaction })
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
errorMessage = err?.message || 'Failed to apply reaction.';
|
||||
return;
|
||||
}
|
||||
const json = await res.json();
|
||||
const reaction = json?.reaction as CommentReactionResult | undefined;
|
||||
if (!reaction) {
|
||||
errorMessage = 'Failed to apply reaction.';
|
||||
return;
|
||||
}
|
||||
comments = comments.map((comment) =>
|
||||
comment.id === commentId
|
||||
? {
|
||||
...comment,
|
||||
likes: reaction.likes,
|
||||
dislikes: reaction.dislikes,
|
||||
userReaction: reaction.userReaction
|
||||
}
|
||||
: comment
|
||||
);
|
||||
} catch {
|
||||
errorMessage = 'Failed to apply reaction.';
|
||||
} finally {
|
||||
const next = { ...reactingIds };
|
||||
delete next[commentId];
|
||||
reactingIds = next;
|
||||
}
|
||||
}
|
||||
|
||||
async function submitTopLevelComment(content: string) {
|
||||
await postComment(content, null);
|
||||
}
|
||||
|
||||
async function deleteComment(commentId: number, hardDelete = false): Promise<boolean> {
|
||||
errorMessage = '';
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
errorMessage = 'You must be signed in to delete comments.';
|
||||
return false;
|
||||
}
|
||||
|
||||
const title = hardDelete ? 'Hard delete comment?' : 'Delete comment?';
|
||||
const message = hardDelete
|
||||
? 'This permanently removes the comment from the thread. This cannot be undone.'
|
||||
: 'This will remove the comment content while preserving the thread structure.';
|
||||
const confirmButtonText = hardDelete ? 'Hard delete' : 'Delete';
|
||||
const ok = await openModal<boolean>({
|
||||
mode: 'confirm',
|
||||
title,
|
||||
message,
|
||||
confirmButtonText,
|
||||
cancelValue: false
|
||||
});
|
||||
if (!ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const query = hardDelete ? '?hardDelete=true' : '';
|
||||
const res = await fetch(`/api/paste/${pasteId}/comments/${commentId}${query}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
errorMessage = err?.message || 'Failed to delete comment.';
|
||||
return false;
|
||||
}
|
||||
|
||||
await refreshComments();
|
||||
return true;
|
||||
} catch {
|
||||
errorMessage = 'Failed to delete comment.';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<section
|
||||
id="comments-section"
|
||||
class="mt-4 w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
|
||||
>
|
||||
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<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>
|
||||
@@ -1,234 +0,0 @@
|
||||
<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>
|
||||
@@ -1,245 +0,0 @@
|
||||
export type Syntax = {
|
||||
name: string;
|
||||
extension: string;
|
||||
};
|
||||
|
||||
export const syntaxes: Record<string, Syntax> = {
|
||||
plaintext: { name: 'Plain Text', extension: 'txt' },
|
||||
'1c': { name: '1c', extension: '' },
|
||||
abnf: { name: 'Augmented Backus-Naur Form', extension: 'abnf' },
|
||||
accesslog: { name: 'Access Log', extension: 'log' },
|
||||
actionscript: { name: 'ActionScript', extension: 'as' },
|
||||
ada: { name: 'Ada', extension: 'ada' },
|
||||
angelscript: { name: 'AngelScript', extension: 'angelscript' },
|
||||
apache: { name: 'Apache', extension: 'apache' },
|
||||
applescript: { name: 'AppleScript', extension: 'applescript' },
|
||||
arcade: { name: 'Arcade', extension: 'arcade' },
|
||||
arduino: { name: 'Arduino', extension: 'ino' },
|
||||
arm: { name: 'ARM Assembly', extension: 's' },
|
||||
asciidoc: { name: 'AsciiDoc', extension: 'adoc' },
|
||||
aspectj: { name: 'AspectJ', extension: 'aj' },
|
||||
autohotkey: { name: 'AutoHotkey', extension: 'ahk' },
|
||||
autoit: { name: 'AutoIt', extension: 'au3' },
|
||||
avrasm: { name: 'AVR Assembly', extension: 's' },
|
||||
awk: { name: 'AWK', extension: 'awk' },
|
||||
bash: { name: 'Bash', extension: 'sh' },
|
||||
basic: { name: 'BASIC', extension: 'bas' },
|
||||
bnf: { name: 'Backus-Naur Form', extension: 'bnf' },
|
||||
brainfuck: { name: 'Brainfuck', extension: 'bf' },
|
||||
c: { name: 'C', extension: 'c' },
|
||||
cpp: { name: 'C++', extension: 'cpp' },
|
||||
hpp: { name: 'C++ Header', extension: 'h' },
|
||||
csharp: { name: 'C#', extension: 'cs' },
|
||||
cal: { name: 'C/AL', extension: '' },
|
||||
cos: { name: 'Cache Object Script', extension: '' },
|
||||
capnproto: { name: "Cap'n Proto", extension: 'capnp' },
|
||||
clojure: { name: 'Clojure', extension: 'clj' },
|
||||
cmake: { name: 'CMake', extension: 'cmake' },
|
||||
coffeescript: { name: 'CoffeeScript', extension: 'coffee' },
|
||||
coq: { name: 'Coq', extension: 'v' },
|
||||
crmsh: { name: 'CRMsH', extension: '' },
|
||||
crystal: { name: 'Crystal', extension: 'cr' },
|
||||
csp: { name: 'CSP', extension: 'csp' },
|
||||
css: { name: 'CSS', extension: 'css' },
|
||||
csv: { name: 'CSV', extension: 'csv' },
|
||||
d: { name: 'D', extension: 'd' },
|
||||
dart: { name: 'Dart', extension: 'dart' },
|
||||
deplhi: { name: 'Delphi', extension: 'pas' },
|
||||
diff: { name: 'Diff', extension: 'diff' },
|
||||
django: { name: 'Django', extension: 'django' },
|
||||
dns: { name: 'DNS Zone', extension: 'dns' },
|
||||
dockerfile: { name: 'Dockerfile', extension: 'dockerfile' },
|
||||
dos: { name: 'DOS', extension: 'bat' },
|
||||
bat: { name: 'Batchfile', extension: 'bat' },
|
||||
dsconfig: { name: 'DSConfig', extension: '' },
|
||||
dts: { name: 'Device Tree', extension: 'dts' },
|
||||
dust: { name: 'Dust', extension: 'dust' },
|
||||
ebnf: { name: 'Extended Backus-Naur Form', extension: 'ebnf' },
|
||||
elixir: { name: 'Elixir', extension: 'ex' },
|
||||
elm: { name: 'Elm', extension: 'elm' },
|
||||
erlang: { name: 'Erlang', extension: 'erl' },
|
||||
excel: { name: 'Excel', extension: 'xlsx' },
|
||||
fsharp: { name: 'F#', extension: 'fs' },
|
||||
fix: { name: 'FIX', extension: 'fix' },
|
||||
flix: { name: 'Flix', extension: 'flix' },
|
||||
fortran: { name: 'Fortran', extension: 'f90' },
|
||||
gcode: { name: 'G-code', extension: 'gcode' },
|
||||
gams: { name: 'GAMS', extension: 'gms' },
|
||||
gauss: { name: 'GAUSS', extension: 'gss' },
|
||||
gherkin: { name: 'Gherkin', extension: '' },
|
||||
go: { name: 'Go', extension: 'go' },
|
||||
golo: { name: 'Golo', extension: 'golo' },
|
||||
gradle: { name: 'Gradle', extension: 'gradle' },
|
||||
graphql: { name: 'GraphQL', extension: 'graphql' },
|
||||
groovy: { name: 'Groovy', extension: 'groovy' },
|
||||
haml: { name: 'HAML', extension: 'haml' },
|
||||
handlebars: { name: 'Handlebars', extension: 'hbs' },
|
||||
haskell: { name: 'Haskell', extension: 'hs' },
|
||||
haxe: { name: 'Haxe', extension: 'hx' },
|
||||
html: { name: 'HTML', extension: 'html' },
|
||||
xml: { name: 'XML', extension: 'xml' },
|
||||
rss: { name: 'RSS', extension: 'rss' },
|
||||
atom: { name: 'Atom', extension: 'atom' },
|
||||
svg: { name: 'SVG', extension: 'svg' },
|
||||
http: { name: 'HTTP', extension: 'http' },
|
||||
https: { name: 'HTTPS', extension: 'http' },
|
||||
hy: { name: 'Hy', extension: 'hy' },
|
||||
inform7: { name: 'Inform 7', extension: 'ni' },
|
||||
ini: { name: 'INI', extension: 'ini' },
|
||||
toml: { name: 'TOML', extension: 'toml' },
|
||||
irpf90: { name: 'IRPF90', extension: 'irpf90' },
|
||||
java: { name: 'Java', extension: 'java' },
|
||||
javascript: { name: 'JavaScript', extension: 'js' },
|
||||
jolie: { name: 'Jolie', extension: 'ol' },
|
||||
json: { name: 'JSON', extension: 'json' },
|
||||
json5: { name: 'JSON5', extension: 'json5' },
|
||||
julia: { name: 'Julia', extension: 'jl' },
|
||||
'julia-repl': { name: 'Julia REPL', extension: '' },
|
||||
kotlin: { name: 'Kotlin', extension: 'kt' },
|
||||
lasso: { name: 'Lasso', extension: 'lasso' },
|
||||
latex: { name: 'LaTeX', extension: 'tex' },
|
||||
ldif: { name: 'LDIF', extension: 'ldif' },
|
||||
leaf: { name: 'Leaf', extension: 'leaf' },
|
||||
less: { name: 'Less', extension: 'less' },
|
||||
lisp: { name: 'Lisp', extension: 'lisp' },
|
||||
livecodeserver: { name: 'LiveCode Server', extension: '' },
|
||||
livescript: { name: 'LiveScript', extension: 'ls' },
|
||||
lua: { name: 'Lua', extension: 'lua' },
|
||||
makefile: { name: 'Makefile', extension: 'makefile' },
|
||||
markdown: { name: 'Markdown', extension: 'md' },
|
||||
mathematica: { name: 'Mathematica', extension: 'nb' },
|
||||
matlab: { name: 'MATLAB', extension: 'm' },
|
||||
maxima: { name: 'Maxima', extension: 'max' },
|
||||
mel: { name: 'Maya Embedded Language', extension: 'mel' },
|
||||
mercury: { name: 'Mercury', extension: 'm' },
|
||||
mipsasm: { name: 'MIPS Assembly', extension: 's' },
|
||||
mizar: { name: 'Mizar', extension: 'miz' },
|
||||
mojolicious: { name: 'Mojolicious', extension: '' },
|
||||
monkey: { name: 'Monkey', extension: 'monkey' },
|
||||
moonscript: { name: 'MoonScript', extension: 'moon' },
|
||||
n1ql: { name: 'N1QL', extension: '' },
|
||||
nginx: { name: 'Nginx', extension: 'nginx' },
|
||||
nim: { name: 'Nim', extension: 'nim' },
|
||||
nix: { name: 'Nix', extension: 'nix' },
|
||||
nsis: { name: 'NSIS', extension: 'nsi' },
|
||||
objectivec: { name: 'Objective-C', extension: 'm' },
|
||||
ocaml: { name: 'OCaml', extension: 'ml' },
|
||||
glsl: { name: 'OpenGL Shading Language', extension: 'glsl' },
|
||||
openscad: { name: 'OpenSCAD', extension: 'scad' },
|
||||
ruleslanguage: { name: 'Oracle Rules Language', extension: '' },
|
||||
oxygene: { name: 'Oxygene', extension: 'oxygene' },
|
||||
parser3: { name: 'Parser3', extension: '' },
|
||||
perl: { name: 'Perl', extension: 'pl' },
|
||||
pf: { name: 'PF', extension: 'pf' },
|
||||
php: { name: 'PHP', extension: 'php' },
|
||||
pony: { name: 'Pony', extension: 'pony' },
|
||||
postgresql: { name: 'PostgreSQL', extension: 'sql' },
|
||||
powershell: { name: 'PowerShell', extension: 'ps1' },
|
||||
processing: { name: 'Processing', extension: 'pde' },
|
||||
prolog: { name: 'Prolog', extension: 'pl' },
|
||||
properties: { name: 'Java Properties', extension: 'properties' },
|
||||
protobuf: { name: 'Protocol Buffers', extension: 'proto' },
|
||||
puppet: { name: 'Puppet', extension: 'pp' },
|
||||
python: { name: 'Python', extension: 'py' },
|
||||
profiler: { name: 'Poython Profiler Results', extension: '' },
|
||||
'python-repl': { name: 'Python REPL', extension: '' },
|
||||
q: { name: 'Q', extension: 'q' },
|
||||
qml: { name: 'QML', extension: 'qml' },
|
||||
r: { name: 'R', extension: 'r' },
|
||||
reasonml: { name: 'ReasonML', extension: 're' },
|
||||
rib: { name: 'RenderMan Interface Bytestream', extension: 'rib' },
|
||||
rsl: { name: 'RenderMan Shading Language', extension: 'rsl' },
|
||||
graph: { name: 'Roboconf', extension: '' },
|
||||
ruby: { name: 'Ruby', extension: 'rb' },
|
||||
rust: { name: 'Rust', extension: 'rs' },
|
||||
sas: { name: 'SAS', extension: 'sas' },
|
||||
scala: { name: 'Scala', extension: 'scala' },
|
||||
scheme: { name: 'Scheme', extension: 'scm' },
|
||||
scilab: { name: 'Scilab', extension: 'sci' },
|
||||
scss: { name: 'SCSS', extension: 'scss' },
|
||||
shell: { name: 'Shell', extension: 'sh' },
|
||||
smali: { name: 'Smali', extension: 'smali' },
|
||||
smalltalk: { name: 'Smalltalk', extension: 'st' },
|
||||
sml: { name: 'Standard ML', extension: 'sml' },
|
||||
sql: { name: 'SQL', extension: 'sql' },
|
||||
stan: { name: 'Stan', extension: 'stan' },
|
||||
stata: { name: 'Stata', extension: 'do' },
|
||||
step21: { name: 'STEP Part 21', extension: 'stp' },
|
||||
stylus: { name: 'Stylus', extension: 'styl' },
|
||||
subunit: { name: 'SubUnit', extension: 'subunit' },
|
||||
svelte: { name: 'Svelte', extension: 'svelte' }, // svelte seems to work even though the docs say it requires a plugin
|
||||
swift: { name: 'Swift', extension: 'swift' },
|
||||
tcl: { name: 'Tcl', extension: 'tcl' },
|
||||
tap: { name: 'Test Anything Protocol', extension: 'tap' },
|
||||
thrift: { name: 'Thrift', extension: 'thrift' },
|
||||
toit: { name: 'Toit', extension: 'toit' },
|
||||
tp: { name: 'TP', extension: 'tp' },
|
||||
twig: { name: 'Twig', extension: 'twig' },
|
||||
typescript: { name: 'TypeScript', extension: 'ts' },
|
||||
vala: { name: 'Vala', extension: 'vala' },
|
||||
vbnet: { name: 'VB.NET', extension: 'vb' },
|
||||
vba: { name: 'VBA', extension: 'vba' },
|
||||
vbscript: { name: 'VBScript', extension: 'vbs' },
|
||||
verilog: { name: 'Verilog', extension: 'v' },
|
||||
vhdl: { name: 'VHDL', extension: 'vhd' },
|
||||
vim: { name: 'Vim Script', extension: 'vim' },
|
||||
axapta: { name: 'X++', extension: 'xpp' },
|
||||
x86asm: { name: 'x86 Assembly', extension: 's' },
|
||||
xl: { name: 'XL', extension: 'xl' },
|
||||
xquery: { name: 'XQuery', extension: 'xq' },
|
||||
yaml: { name: 'YAML', extension: 'yaml' },
|
||||
zephir: { name: 'Zephir', extension: 'zep' }
|
||||
};
|
||||
|
||||
export const expiresOptions = [
|
||||
{ value: 0, label: 'Never Expire' },
|
||||
{ value: 300000, label: 'Expire in 5 Minutes' },
|
||||
{ value: 600000, label: 'Expire in 10 Minutes' },
|
||||
{ value: 1800000, label: 'Expire in 30 Minutes' },
|
||||
{ value: 3600000, label: 'Expire in 1 Hour' },
|
||||
{ value: 21600000, label: 'Expire in 6 Hours' },
|
||||
{ value: 43200000, label: 'Expire in 12 Hours' },
|
||||
{ value: 86400000, label: 'Expire in 1 Day' },
|
||||
{ value: 604800000, label: 'Expire in 1 Week' },
|
||||
{ value: 1209600000, label: 'Expire in 2 Weeks' },
|
||||
{ value: 2592000000, label: 'Expire in 1 Month' },
|
||||
{ value: 7776000000, label: 'Expire in 3 Months' },
|
||||
{ value: 15552000000, label: 'Expire in 6 Months' },
|
||||
{ value: 31536000000, label: 'Expire in 1 Year' },
|
||||
{ value: 63072000000, label: 'Expire in 2 Years' },
|
||||
{ value: 157680000000, label: 'Expire in 5 Years' },
|
||||
{ value: 315360000000, label: 'Expire in 10 Years' }
|
||||
];
|
||||
|
||||
export const trustedDomains = [
|
||||
'img.youtube.com',
|
||||
'i.ytimg.com',
|
||||
|
||||
'github.com',
|
||||
'githubusercontent.com',
|
||||
'avatars.githubusercontent.com',
|
||||
'camo.githubusercontent.com',
|
||||
'raw.githubusercontent.com',
|
||||
'github.githubassets.com',
|
||||
|
||||
'cdn.discordapp.com',
|
||||
'media.discordapp.net',
|
||||
|
||||
'i.redd.it',
|
||||
'v.redd.it',
|
||||
'external-preview.redd.it',
|
||||
'preview.redd.it',
|
||||
|
||||
'i.imgur.com',
|
||||
'imgur.com',
|
||||
|
||||
'pbs.twimg.com',
|
||||
'video.twimg.com',
|
||||
'twitter.com',
|
||||
'x.com',
|
||||
|
||||
'images.cloudflare.com',
|
||||
'cloudflare-ipfs.com',
|
||||
|
||||
'upload.wikimedia.org'
|
||||
];
|
||||
@@ -1 +0,0 @@
|
||||
// place files you want to import through the `#lib` alias in this folder.
|
||||
@@ -1,7 +0,0 @@
|
||||
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 ?? '');
|
||||
@@ -1,118 +0,0 @@
|
||||
<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>
|
||||
@@ -1,210 +0,0 @@
|
||||
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;
|
||||
});
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
export type PasteEmbedMetadataItem = {
|
||||
icon:
|
||||
| 'size'
|
||||
| 'views'
|
||||
| 'created'
|
||||
| 'expires'
|
||||
| 'syntax'
|
||||
| 'visibility-0'
|
||||
| 'visibility-1'
|
||||
| 'visibility-2';
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type PasteEmbedProps = {
|
||||
title: string;
|
||||
uploader: string;
|
||||
metadata: PasteEmbedMetadataItem[];
|
||||
previewLines: string[];
|
||||
isEncrypted: boolean;
|
||||
};
|
||||
@@ -1,28 +0,0 @@
|
||||
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,51 +0,0 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import type { ModalOpenOptions, ModalState } from '#lib/types/modal';
|
||||
|
||||
const initialState: ModalState = {
|
||||
show: false,
|
||||
mode: 'confirm',
|
||||
title: '',
|
||||
message: '',
|
||||
error: '',
|
||||
placeholder: '',
|
||||
inputType: 'text',
|
||||
maxInputLength: undefined,
|
||||
items: [],
|
||||
initialValue: null,
|
||||
totpActive: null,
|
||||
reportTarget: null,
|
||||
reportTargetId: null,
|
||||
reportSiteKey: null,
|
||||
confirmButtonText: ''
|
||||
};
|
||||
|
||||
let resolver: ((value: unknown) => void) | null = null;
|
||||
let cancelValue: unknown = '';
|
||||
|
||||
export const modal = writable<ModalState>(initialState);
|
||||
|
||||
export function openModal<T = unknown>(options: ModalOpenOptions): Promise<T> {
|
||||
cancelValue = options.cancelValue ?? '';
|
||||
return new Promise<T>((resolve) => {
|
||||
resolver = resolve as (value: unknown) => void;
|
||||
modal.set({
|
||||
...initialState,
|
||||
...options,
|
||||
show: true
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function confirmModal(value: unknown) {
|
||||
const resolve = resolver;
|
||||
resolver = null;
|
||||
modal.set(initialState);
|
||||
resolve?.(value);
|
||||
}
|
||||
|
||||
export function cancelModal() {
|
||||
const resolve = resolver;
|
||||
resolver = null;
|
||||
modal.set(initialState);
|
||||
resolve?.(cancelValue);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import { browser } from '$app/environment';
|
||||
import type { AuthUser } from '#lib/types/user';
|
||||
|
||||
let initial: AuthUser | null = null;
|
||||
|
||||
if (browser) {
|
||||
try {
|
||||
const stored = localStorage.getItem('user');
|
||||
if (stored) {
|
||||
const parsed = JSON.parse(stored);
|
||||
if (parsed && 'user' in parsed && typeof parsed.user === 'object') {
|
||||
const { user: nestedUser, ...rest } = parsed;
|
||||
initial = { ...rest, ...nestedUser };
|
||||
} else {
|
||||
initial = parsed;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* empty */
|
||||
}
|
||||
}
|
||||
|
||||
export const user = writable<AuthUser | null>(initial);
|
||||
|
||||
if (browser) {
|
||||
user.subscribe((val) => {
|
||||
if (val) localStorage.setItem('user', JSON.stringify(val));
|
||||
else localStorage.removeItem('user');
|
||||
});
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
export interface Author {
|
||||
uid: number;
|
||||
uuid: string;
|
||||
username: string;
|
||||
visibility: 0 | 1 | 2;
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
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[];
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
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,6 +0,0 @@
|
||||
export interface Pagination {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
totalCount: number;
|
||||
totalPages: number;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import type { Author } from './author';
|
||||
|
||||
export type PasteReaction = 1 | 2 | null;
|
||||
|
||||
export interface Paste {
|
||||
id: string;
|
||||
uuid: string;
|
||||
createdAt: number;
|
||||
title: string | null;
|
||||
storedSize: number;
|
||||
originalSize: number;
|
||||
isCompressed: boolean;
|
||||
views: number;
|
||||
syntax: string;
|
||||
visibility: 0 | 1 | 2;
|
||||
expiresAt: number;
|
||||
editedAt: number | null;
|
||||
likes: number;
|
||||
dislikes: number;
|
||||
userReaction: PasteReaction;
|
||||
reportCount: number | null;
|
||||
author: Author | null;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { Pagination } from './pagination';
|
||||
|
||||
export interface Report {
|
||||
reportID: number;
|
||||
type: number;
|
||||
status: number;
|
||||
description: string | null;
|
||||
createdAt: number;
|
||||
updatedAt: number | null;
|
||||
reporterUUID: string;
|
||||
reporterUsername?: string | null;
|
||||
reporterDisplayName?: string | null;
|
||||
targetType: number;
|
||||
pastePID: number | null;
|
||||
pasteId?: string | null;
|
||||
pasteTitle?: string | null;
|
||||
userUUID: string | null;
|
||||
targetUsername?: string | null;
|
||||
targetDisplayName?: string | null;
|
||||
}
|
||||
|
||||
export interface ReportListResponse {
|
||||
reports: Report[];
|
||||
pagination: Pagination;
|
||||
}
|
||||
|
||||
export const reportTypeLabels = ['CopyrightViolation', 'IllegalContent', 'Fraud', 'Other'] as const;
|
||||
|
||||
export const reportStatusLabels = ['Open', 'Closed'] as const;
|
||||
|
||||
export const reportTargetLabels = ['Paste', 'User', 'Comment'] as const;
|
||||
@@ -1,30 +0,0 @@
|
||||
import type { Paste } from './paste';
|
||||
import type { Pagination } from './pagination';
|
||||
|
||||
export interface User {
|
||||
uid: number;
|
||||
uuid: string;
|
||||
username: string;
|
||||
displayName: string | null;
|
||||
email: string | null;
|
||||
emailVerified: boolean;
|
||||
lastLogin: number | null;
|
||||
roles: number; // bitfield; 5 = User | Admin
|
||||
isBanned: boolean;
|
||||
visibility: 0 | 1 | 2;
|
||||
pastes: Paste[] | null;
|
||||
pagination: Pagination | null;
|
||||
}
|
||||
|
||||
export interface AuthUser extends User {
|
||||
totpEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface JWTUser {
|
||||
uuid: string;
|
||||
username: string;
|
||||
displayname: string;
|
||||
totpEnabled: boolean;
|
||||
roles: number;
|
||||
isBanned: boolean;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { argon2id } from 'hash-wasm';
|
||||
|
||||
self.onmessage = async (event: MessageEvent<Parameters<typeof argon2id>[0]>) => {
|
||||
try {
|
||||
self.postMessage(await argon2id(event.data));
|
||||
} catch {
|
||||
self.postMessage(null);
|
||||
}
|
||||
};
|
||||
@@ -1,280 +0,0 @@
|
||||
import { browser } from '$app/environment';
|
||||
import type { Cookies } from '@sveltejs/kit';
|
||||
import { user } from '#lib/stores/user';
|
||||
import type { JWTUser } from '#lib/types/user';
|
||||
|
||||
export const roles = {
|
||||
User: 1,
|
||||
Moderator: 2,
|
||||
Admin: 4
|
||||
} as const;
|
||||
|
||||
export type Role = keyof typeof roles;
|
||||
|
||||
const TOKEN_KEY = 'token';
|
||||
const REFRESH_TOKEN_KEY = 'refreshToken';
|
||||
const TOKEN_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 180;
|
||||
const AUTH_TOKENS_UPDATED_EVENT = 'auth:tokens-updated';
|
||||
const AUTH_TOKENS_CLEARED_EVENT = 'auth:tokens-cleared';
|
||||
|
||||
let refreshPromise: Promise<void> | null = null;
|
||||
let lastRefreshAttempt = 0;
|
||||
let refreshFailureCount = 0;
|
||||
let refreshIntervalId: ReturnType<typeof setInterval> | null = null;
|
||||
let listenersRegistered = false;
|
||||
|
||||
function getCookieValue(key: string) {
|
||||
if (!browser) return null;
|
||||
const entry = document.cookie
|
||||
.split('; ')
|
||||
.find((cookieEntry) => cookieEntry.startsWith(`${key}=`));
|
||||
if (!entry) return null;
|
||||
const value = entry.slice(key.length + 1);
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function getCookieSecurityAttributes() {
|
||||
if (!browser) return '';
|
||||
return window.location.protocol === 'https:' ? '; secure' : '';
|
||||
}
|
||||
|
||||
function emitAuthEvent(eventName: string) {
|
||||
if (!browser) return;
|
||||
window.dispatchEvent(new CustomEvent(eventName));
|
||||
}
|
||||
|
||||
function decodeBase64Url(value: string) {
|
||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const padding = normalized.length % 4 === 0 ? '' : '='.repeat(4 - (normalized.length % 4));
|
||||
return atob(normalized + padding);
|
||||
}
|
||||
|
||||
function decodeJwtPayload(token: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const [, payload] = token.split('.');
|
||||
if (!payload) return null;
|
||||
return JSON.parse(decodeBase64Url(payload));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseBooleanClaim(value: unknown) {
|
||||
if (typeof value === 'string') return value.toLowerCase() === 'true';
|
||||
return Boolean(value);
|
||||
}
|
||||
|
||||
function parseNumberClaim(value: unknown): number | null {
|
||||
const numeric =
|
||||
typeof value === 'number' ? value : typeof value === 'string' ? parseInt(value, 10) : NaN;
|
||||
return Number.isFinite(numeric) ? numeric : null;
|
||||
}
|
||||
|
||||
function isPermanentRefreshFailure(status: number, message?: string) {
|
||||
if (status === 401 || status === 403) return true;
|
||||
if (!message) return false;
|
||||
const normalized = message.toLowerCase();
|
||||
return (
|
||||
normalized.includes('invalid') ||
|
||||
normalized.includes('expired') ||
|
||||
normalized.includes('revoked') ||
|
||||
normalized.includes('malformed')
|
||||
);
|
||||
}
|
||||
|
||||
async function queueRefresh(token: string, refreshToken: string) {
|
||||
if (refreshPromise) {
|
||||
await refreshPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const timeSinceLastAttempt = now - lastRefreshAttempt;
|
||||
const minDelay = getBackoffDelay(refreshFailureCount);
|
||||
if (timeSinceLastAttempt < minDelay) return;
|
||||
|
||||
refreshPromise = performRefresh(token, refreshToken);
|
||||
try {
|
||||
await refreshPromise;
|
||||
} finally {
|
||||
refreshPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
return getCookieValue(TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function getRefreshToken() {
|
||||
return getCookieValue(REFRESH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
export function setTokens(token: string, refreshToken: string) {
|
||||
if (!browser) return;
|
||||
const secureAttributes = getCookieSecurityAttributes();
|
||||
document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=${TOKEN_COOKIE_MAX_AGE_SECONDS}; samesite=strict${secureAttributes}`;
|
||||
document.cookie = `${REFRESH_TOKEN_KEY}=${encodeURIComponent(refreshToken)}; path=/; max-age=${TOKEN_COOKIE_MAX_AGE_SECONDS}; samesite=strict${secureAttributes}`;
|
||||
refreshFailureCount = 0;
|
||||
emitAuthEvent(AUTH_TOKENS_UPDATED_EVENT);
|
||||
}
|
||||
|
||||
export function clearTokens() {
|
||||
if (!browser) return;
|
||||
const secureAttributes = getCookieSecurityAttributes();
|
||||
document.cookie = `${TOKEN_KEY}=; path=/; max-age=0; samesite=strict${secureAttributes}`;
|
||||
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; max-age=0; samesite=strict${secureAttributes}`;
|
||||
user.set(null);
|
||||
emitAuthEvent(AUTH_TOKENS_CLEARED_EVENT);
|
||||
}
|
||||
|
||||
function getBackoffDelay(attempt: number): number {
|
||||
const baseDelay = 1000;
|
||||
const maxDelay = 30000;
|
||||
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
|
||||
return delay + Math.random() * 1000;
|
||||
}
|
||||
|
||||
export async function refreshTokenIfNeeded() {
|
||||
const token = getToken();
|
||||
const refreshToken = getRefreshToken();
|
||||
if (!token || !refreshToken) return;
|
||||
|
||||
const payload = decodeJwtPayload(token);
|
||||
const expClaim = payload ? parseNumberClaim(payload.exp) : null;
|
||||
if (expClaim === null) {
|
||||
await queueRefresh(token, refreshToken);
|
||||
return;
|
||||
}
|
||||
|
||||
const exp = expClaim * 1000;
|
||||
const now = Date.now();
|
||||
|
||||
if (exp - now >= 2 * 60 * 1000) return;
|
||||
await queueRefresh(token, refreshToken);
|
||||
}
|
||||
|
||||
async function performRefresh(token: string, refreshToken: string) {
|
||||
lastRefreshAttempt = Date.now();
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/auth/refresh', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token, refreshToken })
|
||||
});
|
||||
let data: {
|
||||
success?: boolean;
|
||||
message?: string;
|
||||
token?: { token?: string; refreshToken?: string };
|
||||
} | null = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
refreshFailureCount++;
|
||||
if (isPermanentRefreshFailure(res.status, data?.message)) {
|
||||
clearTokens();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (data?.success && data.token?.token && data.token?.refreshToken) {
|
||||
setTokens(data.token.token, data.token.refreshToken);
|
||||
} else {
|
||||
refreshFailureCount++;
|
||||
if (isPermanentRefreshFailure(res.status, data?.message)) {
|
||||
clearTokens();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
refreshFailureCount++;
|
||||
}
|
||||
}
|
||||
|
||||
export function startTokenRefreshInterval() {
|
||||
if (!browser) return;
|
||||
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) {
|
||||
return cookies.get('token');
|
||||
}
|
||||
|
||||
export function getServerRefreshToken(cookies: Cookies) {
|
||||
return cookies.get('refreshToken');
|
||||
}
|
||||
|
||||
export function setServerTokens(cookies: Cookies, token: string, refreshToken: string) {
|
||||
cookies.set('token', token, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'strict',
|
||||
secure: true,
|
||||
maxAge: TOKEN_COOKIE_MAX_AGE_SECONDS
|
||||
});
|
||||
cookies.set('refreshToken', refreshToken, {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'strict',
|
||||
secure: true,
|
||||
maxAge: TOKEN_COOKIE_MAX_AGE_SECONDS
|
||||
});
|
||||
}
|
||||
|
||||
export function clearServerTokens(cookies: Cookies) {
|
||||
cookies.delete('token', { path: '/' });
|
||||
cookies.delete('refreshToken', { path: '/' });
|
||||
}
|
||||
|
||||
export function getUserFromToken(token: string): JWTUser | null {
|
||||
const payload = decodeJwtPayload(token);
|
||||
if (!payload) return null;
|
||||
|
||||
const uuid = typeof payload.uuid === 'string' ? payload.uuid : null;
|
||||
const username = typeof payload.username === 'string' ? payload.username : null;
|
||||
const displayname = typeof payload.displayname === 'string' ? payload.displayname : '';
|
||||
const rolesClaim = parseNumberClaim(payload.roles);
|
||||
|
||||
if (!uuid || !username || rolesClaim === null) return null;
|
||||
|
||||
return {
|
||||
uuid,
|
||||
username,
|
||||
displayname,
|
||||
totpEnabled: parseBooleanClaim(payload.totp_enabled),
|
||||
roles: rolesClaim,
|
||||
isBanned: parseBooleanClaim(payload.is_banned)
|
||||
};
|
||||
}
|
||||
|
||||
export const hasRole = (userRoles: number, role: number) => (userRoles & role) !== 0;
|
||||
|
||||
export const getUserRoles = (userRoles: number): Role[] =>
|
||||
(Object.keys(roles) as Role[]).filter((role) => hasRole(userRoles, roles[role]));
|
||||
@@ -1,268 +0,0 @@
|
||||
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 = SALT_LENGTH + IV_LENGTH + 16;
|
||||
const MAX_ENVELOPE_LENGTH = 16 * 1024 * 1024;
|
||||
const ENCRYPTION_HEADER = {
|
||||
version: 5,
|
||||
kdf: 'Argon2id',
|
||||
memorySize: ARGON2_MEMORY_SIZE,
|
||||
iterations: ARGON2_ITERATIONS,
|
||||
parallelism: ARGON2_PARALLELISM,
|
||||
algorithm: 'AES-GCM',
|
||||
saltLength: SALT_LENGTH,
|
||||
ivLength: IV_LENGTH
|
||||
};
|
||||
let derivingKey = false;
|
||||
|
||||
async function argon2id(
|
||||
options: Parameters<typeof import('hash-wasm').argon2id>[0]
|
||||
): Promise<Uint8Array<ArrayBuffer>> {
|
||||
if (derivingKey) throw new Error('Another encryption operation is already running.');
|
||||
derivingKey = true;
|
||||
try {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const worker = new Worker(new URL('./argon2.worker.ts', import.meta.url), { type: 'module' });
|
||||
const finish = () => {
|
||||
clearTimeout(timeout);
|
||||
worker.terminate();
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
finish();
|
||||
reject(new Error('Key derivation timed out.'));
|
||||
}, 60_000);
|
||||
worker.onmessage = (event: MessageEvent<Uint8Array | null>) => {
|
||||
finish();
|
||||
if (event.data instanceof Uint8Array && event.data.length === ARGON2_HASH_LENGTH) {
|
||||
resolve(new Uint8Array(event.data));
|
||||
} else reject(new Error('Key derivation failed. The device may lack memory.'));
|
||||
};
|
||||
worker.onerror = (event) => {
|
||||
event.preventDefault();
|
||||
finish();
|
||||
reject(new Error('Unable to run the encryption worker.'));
|
||||
};
|
||||
try {
|
||||
worker.postMessage(options);
|
||||
} catch (error) {
|
||||
finish();
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
derivingKey = false;
|
||||
}
|
||||
}
|
||||
|
||||
function toBase64(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK_SIZE));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
function fromBase64(data: string): Uint8Array {
|
||||
const binary = atob(data);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export function encodePasswordFragment(password: string): string {
|
||||
return `u1.${toBase64(new TextEncoder().encode(password))}`;
|
||||
}
|
||||
|
||||
export function decodePasswordFragment(fragment: string): string {
|
||||
return fragment.startsWith('u1.')
|
||||
? new TextDecoder('utf-8', { fatal: true }).decode(fromBase64(fragment.slice(3)))
|
||||
: atob(fragment);
|
||||
}
|
||||
|
||||
export async function encryptAES(content: string, password: string): Promise<string> {
|
||||
if (!password) throw new Error('Password required for encryption.');
|
||||
if (estimateEncryptedSize(content) > MAX_ENVELOPE_LENGTH) {
|
||||
throw new Error('Encrypted paste exceeds the supported size limit.');
|
||||
}
|
||||
const enc = new TextEncoder();
|
||||
const salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
|
||||
|
||||
const keyMaterial = await argon2id({
|
||||
password,
|
||||
salt,
|
||||
iterations: ARGON2_ITERATIONS,
|
||||
memorySize: ARGON2_MEMORY_SIZE,
|
||||
parallelism: ARGON2_PARALLELISM,
|
||||
hashLength: ARGON2_HASH_LENGTH,
|
||||
outputType: 'binary'
|
||||
});
|
||||
|
||||
const key = await window.crypto.subtle.importKey(
|
||||
'raw',
|
||||
new Uint8Array(keyMaterial),
|
||||
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||
false,
|
||||
['encrypt']
|
||||
);
|
||||
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(IV_LENGTH));
|
||||
const encryptedContent = await window.crypto.subtle.encrypt(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
iv,
|
||||
additionalData: enc.encode(JSON.stringify(ENCRYPTION_HEADER))
|
||||
},
|
||||
key,
|
||||
enc.encode(content)
|
||||
);
|
||||
|
||||
const combined = new Uint8Array(salt.byteLength + iv.byteLength + encryptedContent.byteLength);
|
||||
combined.set(salt, 0);
|
||||
combined.set(iv, salt.byteLength);
|
||||
combined.set(new Uint8Array(encryptedContent), salt.byteLength + iv.byteLength);
|
||||
|
||||
return JSON.stringify({
|
||||
...ENCRYPTION_HEADER,
|
||||
data: toBase64(combined)
|
||||
});
|
||||
}
|
||||
|
||||
export function estimateEncryptedSize(content: string): number {
|
||||
const rawSize = new TextEncoder().encode(content).length;
|
||||
const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
|
||||
const b64Size = Math.ceil(combinedSize / 3) * 4;
|
||||
return b64Size + JSON.stringify({ ...ENCRYPTION_HEADER, data: '' }).length;
|
||||
}
|
||||
|
||||
export async function decryptAES(result: string, password: string): Promise<string | null> {
|
||||
try {
|
||||
const enc = new TextEncoder();
|
||||
if (result.length > MAX_ENVELOPE_LENGTH) {
|
||||
throw new Error('Encrypted paste exceeds the supported size limit.');
|
||||
}
|
||||
const parsed = JSON.parse(result);
|
||||
if (!parsed || typeof parsed !== 'object' || parsed.algorithm !== 'AES-GCM') {
|
||||
throw new Error('Unsupported or malformed encrypted paste.');
|
||||
}
|
||||
const legacyPBKDF2 =
|
||||
parsed.version === 1 &&
|
||||
parsed.kdf === 'PBKDF2' &&
|
||||
parsed.iterations === 100000 &&
|
||||
parsed.hash === 'SHA-256' &&
|
||||
(parsed.saltLength === undefined || parsed.saltLength === SALT_LENGTH) &&
|
||||
(parsed.ivLength === undefined || parsed.ivLength === IV_LENGTH);
|
||||
const legacyArgon2 =
|
||||
parsed.version === 4 && parsed.memorySize === 65536 && parsed.saltLength === 32;
|
||||
const currentArgon2 =
|
||||
(parsed.version === 4 || parsed.version === 5) &&
|
||||
parsed.memorySize === ARGON2_MEMORY_SIZE &&
|
||||
parsed.saltLength === SALT_LENGTH;
|
||||
if (
|
||||
!legacyPBKDF2 &&
|
||||
!(
|
||||
parsed.kdf === 'Argon2id' &&
|
||||
parsed.iterations === ARGON2_ITERATIONS &&
|
||||
parsed.parallelism === ARGON2_PARALLELISM &&
|
||||
parsed.ivLength === IV_LENGTH &&
|
||||
(legacyArgon2 || currentArgon2)
|
||||
)
|
||||
)
|
||||
throw new Error('Unsupported encryption profile.');
|
||||
if (
|
||||
typeof parsed.data !== 'string' ||
|
||||
!parsed.data.length ||
|
||||
parsed.data.length % 4 !== 0 ||
|
||||
!/^[A-Za-z0-9+/]*={0,2}$/.test(parsed.data)
|
||||
) {
|
||||
throw new Error('Malformed encrypted-paste encoding.');
|
||||
}
|
||||
const combined = fromBase64(parsed.data);
|
||||
|
||||
const saltLength = parsed.saltLength ?? SALT_LENGTH;
|
||||
const ivLength = parsed.ivLength ?? IV_LENGTH;
|
||||
if (combined.length < saltLength + ivLength + 16) {
|
||||
throw new Error('Encrypted paste is truncated.');
|
||||
}
|
||||
const salt = combined.slice(0, saltLength);
|
||||
const iv = combined.slice(saltLength, saltLength + ivLength);
|
||||
const data = combined.slice(saltLength + ivLength);
|
||||
|
||||
let keyMaterial: ArrayBuffer | Uint8Array;
|
||||
|
||||
if (parsed.kdf === 'Argon2id') {
|
||||
keyMaterial = await argon2id({
|
||||
password,
|
||||
salt,
|
||||
iterations: parsed.iterations,
|
||||
memorySize: parsed.memorySize,
|
||||
parallelism: parsed.parallelism,
|
||||
hashLength: ARGON2_HASH_LENGTH,
|
||||
outputType: 'binary'
|
||||
});
|
||||
} else {
|
||||
const baseKey = await window.crypto.subtle.importKey(
|
||||
'raw',
|
||||
enc.encode(password),
|
||||
{ name: 'PBKDF2' },
|
||||
false,
|
||||
['deriveBits', 'deriveKey']
|
||||
);
|
||||
const derivedKey = await window.crypto.subtle.deriveKey(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
salt,
|
||||
iterations: parsed.iterations,
|
||||
hash: parsed.hash
|
||||
},
|
||||
baseKey,
|
||||
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||
true,
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
keyMaterial = await window.crypto.subtle.exportKey('raw', derivedKey);
|
||||
}
|
||||
|
||||
const key = await window.crypto.subtle.importKey(
|
||||
'raw',
|
||||
new Uint8Array(keyMaterial),
|
||||
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||
false,
|
||||
['decrypt']
|
||||
);
|
||||
|
||||
const decryptedContent = await window.crypto.subtle.decrypt(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
iv,
|
||||
additionalData: enc.encode(
|
||||
parsed.version === 5
|
||||
? JSON.stringify(ENCRYPTION_HEADER)
|
||||
: currentArgon2
|
||||
? ENCRYPTION_AAD
|
||||
: ''
|
||||
)
|
||||
},
|
||||
key,
|
||||
data
|
||||
);
|
||||
|
||||
return new TextDecoder().decode(decryptedContent);
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === 'OperationError') return null;
|
||||
if (
|
||||
error instanceof SyntaxError ||
|
||||
(error instanceof DOMException && error.name === 'InvalidCharacterError')
|
||||
) {
|
||||
throw new Error('Malformed encrypted paste.');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
const htmlEscapeMap: Record<string, string> = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
'`': '`'
|
||||
};
|
||||
|
||||
export function escapeHtml(value: string): string {
|
||||
return value.replace(/[&<>"'`]/g, (char) => htmlEscapeMap[char]);
|
||||
}
|
||||
@@ -1,333 +0,0 @@
|
||||
import { marked } from 'marked';
|
||||
import createDOMPurify from 'dompurify';
|
||||
import type { WindowLike } from 'dompurify';
|
||||
import { trustedDomains } from '#lib/consts';
|
||||
import { escapeHtml } from './html';
|
||||
|
||||
export const externalMediaWarningStorageKey = 'sharpbin:ignore-external-media-warning';
|
||||
|
||||
const tagMap: Record<string, string> = {
|
||||
IMG: 'image',
|
||||
VIDEO: 'video',
|
||||
AUDIO: 'audio',
|
||||
IFRAME: 'iframe'
|
||||
};
|
||||
|
||||
export function getIgnoreExternalMediaWarning(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
|
||||
return window.localStorage.getItem(externalMediaWarningStorageKey) === 'true';
|
||||
}
|
||||
|
||||
export function setIgnoreExternalMediaWarning(ignore: boolean) {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
window.localStorage.setItem(externalMediaWarningStorageKey, ignore ? 'true' : 'false');
|
||||
}
|
||||
|
||||
export async function parseMarkdown(
|
||||
md: string,
|
||||
preventExternal: boolean = true,
|
||||
allowTrustedDomains: boolean = true
|
||||
): Promise<string> {
|
||||
const html = await marked.parse(md);
|
||||
let dom: WindowLike & { document: Document };
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
dom = window as unknown as WindowLike & { document: Document };
|
||||
} else if (import.meta.env.SSR) {
|
||||
const { JSDOM } = await import('jsdom');
|
||||
dom = new JSDOM('').window as unknown as WindowLike & { document: Document };
|
||||
} else {
|
||||
throw new Error('JSDOM should only be loaded on the server');
|
||||
}
|
||||
|
||||
const DOMPurify = createDOMPurify(dom);
|
||||
|
||||
if (preventExternal) {
|
||||
DOMPurify.addHook('afterSanitizeElements', (node) => {
|
||||
if (node.nodeType !== 1) return;
|
||||
const element = node as Element;
|
||||
|
||||
const tag = element.nodeName;
|
||||
if (tag === 'IMG' || tag === 'VIDEO' || tag === 'IFRAME' || tag === 'AUDIO') {
|
||||
const src = element.getAttribute('src');
|
||||
if (!src) return;
|
||||
|
||||
let hostname = 'external server';
|
||||
|
||||
try {
|
||||
hostname = new URL(src).hostname;
|
||||
} catch {
|
||||
//might be a relative url
|
||||
}
|
||||
|
||||
if (allowTrustedDomains && trustedDomains.includes(hostname)) return;
|
||||
|
||||
const placeholder = dom.document.createElement('span');
|
||||
placeholder.className = 'media-placeholder';
|
||||
placeholder.setAttribute(
|
||||
'style',
|
||||
'border: 1px solid #404040; padding: 1rem; margin: 1rem 0; border-radius: 0.5rem; background-color: #1e1e1e; text-align: center; display: block; font-style: normal; color: white; cursor: default; text-decoration: none; user-select: none;'
|
||||
);
|
||||
|
||||
const warning = dom.document.createElement('span');
|
||||
warning.textContent = `External ${tagMap[tag] || tag.toLowerCase()} hidden for privacy.`;
|
||||
warning.setAttribute(
|
||||
'style',
|
||||
'margin-bottom: 0.5rem; font-weight: bold; display: block; text-decoration: none;'
|
||||
);
|
||||
|
||||
const subWarning = dom.document.createElement('span');
|
||||
subWarning.textContent = `Loading this will expose your IP address to ${hostname}.`;
|
||||
subWarning.setAttribute(
|
||||
'style',
|
||||
'font-size: 0.75rem; color: #a3a3a3; margin-bottom: 1rem; display: block; text-decoration: none;'
|
||||
);
|
||||
|
||||
const button = dom.document.createElement('button');
|
||||
button.textContent = `Load ${tagMap[tag] || tag.toLowerCase()}`;
|
||||
button.className = 'load-media-btn';
|
||||
button.setAttribute('data-src', src);
|
||||
button.setAttribute('data-tag', tag.toLowerCase());
|
||||
button.setAttribute(
|
||||
'style',
|
||||
'background-color: #404040; color: white; padding: 0.25rem 0.75rem; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
|
||||
);
|
||||
|
||||
const ignoreButton = dom.document.createElement('button');
|
||||
ignoreButton.textContent = "Don't warn again";
|
||||
ignoreButton.className = 'ignore-media-warning-btn';
|
||||
ignoreButton.setAttribute(
|
||||
'style',
|
||||
'background-color: transparent; color: #d4d4d8; padding: 0.25rem 0.75rem; border: 1px solid #525252; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
|
||||
);
|
||||
|
||||
if (element.getAttribute('alt'))
|
||||
button.setAttribute('data-alt', element.getAttribute('alt') || '');
|
||||
if (element.getAttribute('title'))
|
||||
button.setAttribute('data-title', element.getAttribute('title') || '');
|
||||
if (element.getAttribute('width'))
|
||||
button.setAttribute('data-width', element.getAttribute('width') || '');
|
||||
if (element.getAttribute('height'))
|
||||
button.setAttribute('data-height', element.getAttribute('height') || '');
|
||||
|
||||
const actions = dom.document.createElement('span');
|
||||
actions.setAttribute(
|
||||
'style',
|
||||
'display: flex; gap: 0.5rem; justify-content: center; flex-wrap: wrap;'
|
||||
);
|
||||
actions.appendChild(button);
|
||||
actions.appendChild(ignoreButton);
|
||||
|
||||
placeholder.appendChild(warning);
|
||||
placeholder.appendChild(subWarning);
|
||||
placeholder.appendChild(actions);
|
||||
|
||||
const parent = element.parentNode;
|
||||
if (parent && parent.nodeName === 'A') {
|
||||
const anchor = parent as HTMLElement;
|
||||
button.setAttribute('data-href', anchor.getAttribute('href') || '');
|
||||
button.setAttribute('data-target', anchor.getAttribute('target') || '');
|
||||
anchor.parentNode?.replaceChild(placeholder, anchor);
|
||||
} else {
|
||||
element.parentNode?.replaceChild(placeholder, element);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user