Compare commits

..
151 Commits
Author SHA1 Message Date
whoswhip 8252d58f47 fix: update version number to 3.0.0 and remove beta check from footer 2026-01-24 02:30:42 -05:00
whoswhip bd7d1154ea fix: use margin-bottom instead of margin-top for elements 2026-01-23 22:32:00 -05:00
whoswhip 753d28f720 feat: create Paste component for displaying paste details 2026-01-23 21:15:43 -05:00
whoswhip 4dafde739a fix: center-align text in login and registration links in navbar 2026-01-23 20:48:22 -05:00
whoswhip 91810d284f chore: npm run format 2026-01-23 20:43:58 -05:00
whoswhip 63f55d2bda feat: implement mobile support for navbar 2026-01-23 20:43:52 -05:00
whoswhip 9e56c4eee1 fix: correct property name for TOTP enabled flag in parseTotpEnabled function 2026-01-23 19:52:39 -05:00
whoswhip 729898296b fix: correct conditional logic for user role checks in component rendering 2026-01-23 11:17:30 -05:00
whoswhip f8a1490582 fix: null user/paste fk in reports on delete 2026-01-23 10:56:08 -05:00
whoswhip ae91108484 feat: refactor refresh token handling; update schema and logic for improved security and functionality 2026-01-23 10:45:49 -05:00
whoswhip 35d891bed7 feat: bypass user confirmation when loading external assets in markdown for trusted domains 2026-01-23 08:17:20 -05:00
whoswhip 3cee99f9c2 chore: include syntax type in Open Graph description for pastes 2026-01-23 02:38:14 -05:00
whoswhip 3f27a3a3e7 feat: preview markdown in paste creation; prevent external option in parseMarkdown 2026-01-23 02:06:54 -05:00
whoswhip 825d384db4 fix(styling): add table styling for markdown elements 2026-01-23 01:41:31 -05:00
whoswhip 8f5499ae05 fix(styling): adjust margin and padding for first child in markdown elements 2026-01-23 01:34:04 -05:00
whoswhip 7789ab6cb2 fix: ensure JSDOM is only loaded in server-side environments 2026-01-23 01:33:58 -05:00
whoswhip 406381fbfe feat: add markdown parsing and rendering support
fix: resolve lint issues
chore: npm run format

- Added `parseMarkdown` function to handle markdown content with DOMPurify for sanitization.
- Updated `+page.svelte` to render markdown content and handle media loading.
- Introduced new styles for markdown elements in the Svelte component.
- Enhanced media placeholders for external content with privacy warnings.
2026-01-23 01:20:52 -05:00
whoswhip 5e4afafac0 fix: improve error handling in paste fetching and add error page 2026-01-20 17:30:54 -05:00
whoswhip 8accfa2dc5 fix(styling): enforce max width on recent pastes titles 2026-01-20 17:26:11 -05:00
whoswhip f467a2a899 fix: enhance paste size validation logic 2026-01-20 17:21:14 -05:00
whoswhip 2b60ee8636 fix: inline is expired calculation
should be reactive
2026-01-20 17:15:05 -05:00
whoswhip 6f990364a5 fix: properly set limiter 2026-01-20 17:11:35 -05:00
whoswhip 3a5738b531 feat: improve recent page; improve SEO for pages 2026-01-20 17:10:09 -05:00
whoswhip 3895bd9681 feat: implement rate limiting policy for site info endpoints in Auth and Paste controllers 2026-01-20 17:09:31 -05:00
whoswhip 8a6ab29f52 feat: add recent pastes page with data fetching and display logic 2026-01-20 11:26:06 -05:00
whoswhip 698183690c feat: update button styles for active state in paste creation 2026-01-20 10:59:00 -05:00
whoswhip c565c57e20 feat: update minimum height for main sections across multiple pages for consistent layout 2026-01-20 09:14:59 -05:00
whoswhip 7b3af77449 feat: enhance decryption process with status updates and improved user feedback 2026-01-20 09:14:48 -05:00
whoswhip 5410a8973a feat: enhance paste creation with dynamic textarea resizing and improved password handling; generate random password button in paste creation; show password in paste creation; 2026-01-20 09:14:35 -05:00
whoswhip 72206e9ba2 feat: declare application version constant in app.d.ts 2026-01-20 09:13:52 -05:00
whoswhip 7e1fb3add4 feat: integrate hash-wasm for enhanced AES encryption and decryption 2026-01-20 09:13:45 -05:00
whoswhip eca6867fca feat: add application version definition to Vite config 2026-01-20 09:13:27 -05:00
whoswhip e0935505ea feat: add Footer component to layout for improved user navigation 2026-01-20 09:13:10 -05:00
whoswhip 6c3caaf2ec fix(style): update Navbar styling for improved layout and consistency 2026-01-20 07:11:50 -05:00
whoswhip 62b5dcef00 fix: correct syntax selection logic for file drag and drop handling 2026-01-19 23:15:15 -05:00
whoswhip ca9fa81771 feat: refactor drag and drop file handling to update syntax selection conditionally 2026-01-19 23:14:50 -05:00
whoswhip fed06630b7 feat: improve file download naming by using syntax extension conditionally 2026-01-19 04:04:26 -05:00
whoswhip 9e056009e3 feat: auto detect syntax from file extension on drag and drop; syntax from extension function
refactor: syntax type with display and extension
2026-01-19 03:55:41 -05:00
whoswhip bf0eac9ed8 feat: add isBinaryData utility function and integrate it into paste handling; add drag and drop functionality when creating a paste 2026-01-19 03:37:28 -05:00
whoswhip 1ed21789e6 feat: update favicon and improve tooltip for paste size display 2026-01-18 23:50:53 -05:00
whoswhip b465725ec2 Merge branch 'SharpbinV3' of https://github.com/whoswhip/Sharpbin into SharpbinV3 2026-01-18 22:01:55 -05:00
whoswhip 28a0ccbfab feat: view raw button; paste header follows when scrolling; scroll to top button appears after scrolling far enough
chore: npm run format + lint
2026-01-18 22:01:50 -05:00
whoswhip ca87b1a5f2 feat: /raw/{id} endpoint 2026-01-18 22:00:54 -05:00
whoswhip c08fe0690f refactor: navbar no longer fixed position
this is just testing, im not sure what i prefer so far
2026-01-18 22:00:03 -05:00
whoswhip 08e88f5e75 chore: add license 2026-01-18 20:14:30 -05:00
whoswhip e907ca4615 Merge pull request #1 from whoswhip/dependabot/npm_and_yarn/SharpbinV3.Client/sveltejs/kit-2.50.0
chore(deps-dev): bump @sveltejs/kit from 2.49.2 to 2.50.0 in /SharpbinV3.Client
2026-01-18 02:09:48 -05:00
dependabot[bot] 0bbc219d76 chore(deps-dev): bump @sveltejs/kit in /SharpbinV3.Client
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.49.2 to 2.50.0.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.50.0/packages/kit)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-18 07:09:16 +00:00
whoswhip 67447d51ae feat: reports; improved+simplifed modals; extractError funcction;
refactor: change jwt claims to lowercase; use response dtos for sensitive data
fix: nullify user on token clears; change appsettings.dev View_Internal_API_Key
2026-01-14 19:41:52 -05:00
whoswhip 1da88dba4e fix: reset turnstile on login error handling 2026-01-11 18:54:23 -05:00
whoswhip 14bbd9c762 feat: reporting apis; better rate limiting
refactor: change certain apis to be more REST like (e.g. DELETE /api/paste/{pasteId}/delete -> DELETE /api/paste/{pasteId}
2026-01-10 00:06:36 -05:00
whoswhip 864a4ee91a chore: npm run format 2026-01-09 20:38:56 -05:00
whoswhip f9b63edf77 fix: update paste view count display in metadata 2026-01-09 20:38:26 -05:00
whoswhip 6072f7f674 fix: update API fetch calls to use dynamic apiUrl 2026-01-09 20:33:18 -05:00
whoswhip 8b84a2d8a3 fix: improve error logging for view count increment failure
i honestly have no clue whats causing it to fail right now
2026-01-09 20:16:45 -05:00
whoswhip ccdb000934 refactor: streamline API key handling in view increment logic 2026-01-09 20:13:17 -05:00
whoswhip a6fa65c3bd feat: add PasteSettings environment variables for internal API key and HMAC secret 2026-01-09 19:39:42 -05:00
whoswhip 3048af3a6d feat: paste views; configuration validation; hmacsha256 method; enhance paste clean up serivce; paste view clean up service; 2026-01-09 19:12:05 -05:00
whoswhip 60876eb1ba refactor: more verbose api responses
fix: exclude .idea folder from rider ide
2026-01-09 16:09:23 -05:00
whoswhip 6bea6c49be Revert "chore: format via csharpier"
This reverts commit 7a2eb699f4.
2026-01-09 15:24:19 -05:00
whoswhip 7a2eb699f4 chore: format via csharpier 2026-01-09 15:13:57 -05:00
whoswhip 284c5e927e fix: improve error handling and response messages in EditPaste method 2026-01-09 15:12:47 -05:00
whoswhip 1f2761f463 feat: update API routes for paste options and recent pastes 2026-01-08 17:31:02 -05:00
whoswhip 5a630d2a71 fix: reset Turnstile on login and registration error handling 2026-01-08 15:38:50 -05:00
whoswhip 54a4fe1a08 docs: update README with new environment variables for registration and paste settings 2026-01-08 15:27:04 -05:00
whoswhip 9f55aa1b22 feat: paste compression & verification enforcement settings; enforce 2fa on admins setting; increase paste validation; anonymous uploads
fix: minor styling issue on main elements; resolve lint issue
refactor: remove 2FA badge on user pages; enhance paste creation flow; body background color always neutral-950; improve paste creation paste info (lines, cchars etc) for mobile
2026-01-08 15:25:42 -05:00
whoswhip fabef95159 fix: enhance textarea styling and display content metrics 2026-01-07 22:00:22 -05:00
whoswhip 2a9a4b9eef fix: improve formatBytes function and display byte size in textarea 2026-01-07 20:18:42 -05:00
whoswhip 2773813c26 fix: correct environment variable key for Turnstile Site Key in docker-compose 2026-01-07 18:53:30 -05:00
whoswhip f96396b586 fix: remove quotes from DATA_PROTECTION_KEY_PATH in docker-compose 2026-01-07 18:43:04 -05:00
whoswhip d5565f9a68 fix: remove quotes from default connection string in docker-compose 2026-01-07 18:00:33 -05:00
whoswhip 4de6a6a118 fix: display 2FA status only for the account owner 2026-01-07 18:00:28 -05:00
whoswhip 5e8d7be864 fix: update environment variables in docker-compose for backend and frontend services 2026-01-07 17:52:15 -05:00
whoswhip 6bcc62a7e7 fix: update TOTP API request payload to use 'code' instead of 'totpcode' 2026-01-07 16:41:10 -05:00
whoswhip 20ceb91db8 feat: 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
refactor: organize dtos by domain; verification providers use verification context; move ip parsing into http context extensions
chore: clean code
2026-01-07 16:36:41 -05:00
whoswhip 361cf76f46 fix: adjust password hint display logic in registration form 2026-01-07 10:29:55 -05:00
whoswhip 3711885a38 fix: prevent moderators from modifiying higher roles(admin) 2026-01-07 10:24:51 -05:00
whoswhip d514e456bf fix: improve error handling for registration response 2026-01-07 10:24:16 -05:00
whoswhip ce66fe13e8 fix: improve error handling and display for login failures 2026-01-07 10:23:40 -05:00
whoswhip 1f4fda1a16 fix: resolve lint issues
chore: npm run format
2026-01-07 09:54:27 -05:00
whoswhip d3c2efd210 fix: enhance tooltip functionality and update last login display 2026-01-07 09:46:58 -05:00
whoswhip 7650fd786d fix: increase max height 2026-01-06 21:11:34 -05:00
whoswhip bffc4e2bf4 fix: ssr request to user; navbar positioning 2026-01-06 20:36:22 -05:00
whoswhip a912d0463b fix: update Navbar and layout server to improve structure and data handling 2026-01-06 17:51:19 -05:00
whoswhip 3bbd64631a feat: seo optimizations + opengraph embeds
fix: nullable AuthorUUIDs; assign admins member & mod role
2026-01-06 16:26:47 -05:00
whoswhip a7185d6a3d docs: update README files to include first user admin role configuration 2026-01-06 15:42:37 -05:00
whoswhip c934c85b13 feat: enhance AuthService to support admin role assignment for the first user 2026-01-06 15:42:29 -05:00
whoswhip edd94c45e8 docs: update configuration details for backend and frontend in README files 2026-01-06 15:02:59 -05:00
whoswhip 8bc031a13c docs: update README files for client and server setup, features, and tech stack 2026-01-06 14:59:26 -05:00
whoswhip 73b847c06b refactor: implement password validation in dto; remove redundant validation code in auth controller 2026-01-06 14:44:29 -05:00
whoswhip 21b6f95edc fix: lint issues resolved
chore: npm run format
2026-01-06 14:18:05 -05:00
whoswhip 99feb2795a feat: admins can change user's roles
refactor: banned role has priority over all other roles when displaying
chore: npm run format
2026-01-06 14:07:55 -05:00
whoswhip fe54ff15ce feat: account deletion; auto incremental uids; display name renaming UI + account deletion UI; enhanced username validation 2026-01-04 16:58:05 -05:00
whoswhip b1d2d3f5bb feat: add registration status check and disable form elements when registration is disabled 2026-01-04 11:28:02 -05:00
whoswhip bbfa9ffc56 fix: dont disabled login button when registrations are disabled 2026-01-04 11:18:10 -05:00
whoswhip 159fcc2a89 feat: enable registration toggle and update Navbar to reflect registration status 2026-01-04 11:16:09 -05:00
whoswhip f5de211611 fix: add cursor pointer to the submit button for better UX 2026-01-04 11:01:51 -05:00
whoswhip b6e020fa69 feat: implement modal component for password input and confirmation actions 2026-01-04 09:55:39 -05:00
whoswhip 48543c7ff0 fix: update API routes for fetching raw paste content and deleting pastes 2026-01-04 09:55:15 -05:00
whoswhip 2c24af5ac9 fix: load turnstile script in layout and explicitly render
chore: npm run format + lint
2026-01-04 09:22:27 -05:00
whoswhip 24b25c2291 feat: implement registration page with Turnstile verification and loading state 2026-01-01 10:14:06 -05:00
whoswhip 848b8598e5 feat: implement Turnstile verification for enhanced security during login and registration
refactor: remove unnecessary interfaces for services; change user key from UID to UUID
2025-12-31 12:11:09 -05:00
whoswhip 08c4be4f7e feat: add health checks for backend and frontend services in docker-compose.yml 2025-12-30 22:00:20 -05:00
whoswhip c4f606ecf2 fix: add ASPNETCORE_URLS environment variable for backend service in docker-compose.yml 2025-12-30 21:54:46 -05:00
whoswhip 095df2f3f3 fix: remove dependency condition for backend service health check in docker-compose.yml 2025-12-30 21:31:20 -05:00
whoswhip 57dad564a6 feat: add health checks for backend and frontend services in docker-compose.yml 2025-12-30 21:25:25 -05:00
whoswhip dfdce51c6e feat: add health check endpoint returning status ok 2025-12-30 21:21:43 -05:00
whoswhip cab1b170c1 feat: add health checks for database connectivity 2025-12-30 21:19:10 -05:00
whoswhip 011b523fd3 fix: update database connection string configuration in Program.cs and docker-compose.yml 2025-12-30 20:43:42 -05:00
whoswhip 9bb620a4a3 fix: add validation for display name length in user creation and update requests 2025-12-30 20:28:00 -05:00
whoswhip 27d5de3509 chore: update Svelte adapter to use @sveltejs/adapter-node 2025-12-30 17:58:05 -05:00
whoswhip e4966edbb5 i think this fixes it 2025-12-30 17:48:28 -05:00
whoswhip 0dff8f992b idk anymore man 2025-12-30 17:46:31 -05:00
whoswhip 6ed5ed935d maybe fix? 2025-12-30 17:44:02 -05:00
whoswhip da803cfea3 debug ls 2025-12-30 17:34:10 -05:00
whoswhip 747f70534d possible fix? 2025-12-30 17:17:14 -05:00
whoswhip 6178888246 fix: update SQLite connection string retrieval in Program.cs 2025-12-30 17:15:29 -05:00
whoswhip 0f44190312 refactor: simplify Dockerfile and docker-compose for backend service configuration 2025-12-30 17:07:24 -05:00
whoswhip 113ad499d9 fix: update docker-compose to reflect correct backend directory structure 2025-12-30 16:08:26 -05:00
whoswhip f40d4ab68c feat: implement user update functionality by UUID and add validation to UpdateUserRequest 2025-12-30 13:35:10 -05:00
whoswhip 1ec4877aad chore: rename SharpbinV3 dir to SharpbinV3.Server 2025-12-30 12:39:26 -05:00
whoswhip 31142e0cf9 feat: add Dockerfile and docker-compose for backend and frontend services 2025-12-30 12:38:22 -05:00
whoswhip 2fe2ce2f3a refactor: streamline user role checks and improve JWT token handling 2025-12-30 11:48:29 -05:00
whoswhip 7857c327ea fix: include url queries in resolve 2025-12-30 11:24:45 -05:00
whoswhip 86b74a140a feat: add editedAt field to Paste interface and enhance paste editing functionality 2025-12-30 11:24:23 -05:00
whoswhip 8ab66f5f15 feat: enhance tooltip functionality and improve date formatting 2025-12-30 11:24:07 -05:00
whoswhip d71b60bd7e chore: npm run format + lint 2025-12-30 11:23:55 -05:00
whoswhip 55bee20e5d fix: change to non-reactive statements 2025-12-30 11:22:42 -05:00
whoswhip b44f0bce0a fix: use $app/state 2025-12-30 11:20:39 -05:00
whoswhip 1950dc47ae feat: add variant support for dropdown component styling 2025-12-30 11:20:03 -05:00
whoswhip 3015f97ff9 feat: add delete functionality for pastes with authorization check 2025-12-30 11:19:33 -05:00
whoswhip f578b58780 feat: add PasteCleanUpService as a hosted service 2025-12-29 06:14:06 -05:00
whoswhip ff52498cf9 fix: update profile link to direct to user page instead of dashboard 2025-12-29 05:45:18 -05:00
whoswhip 5cb30a90a7 feat: enhance code highlighting for plaintext in syntax highlighter 2025-12-29 05:32:45 -05:00
whoswhip e45785e1b8 fix: token refreshing using wrong object path 2025-12-29 05:11:15 -05:00
whoswhip 3a549511f9 feat: implement paste decryption
refactor: switch back to highlight.js
2025-12-29 04:28:44 -05:00
whoswhip a9e1e82359 feat: add Pagination interface and integrate it into User type 2025-12-29 04:27:45 -05:00
whoswhip 7eb0204e67 feat: enhance tooltip functionality; prevent empty tooltips for paste titles 2025-12-29 04:27:26 -05:00
whoswhip f61f31de0e feat: implement decryptAes function; moved to encryption.ts 2025-12-29 04:26:58 -05:00
whoswhip 49b9673d48 feat: implement pagination for user pastes; enhance fetchPage function and update display logic 2025-12-29 04:26:09 -05:00
whoswhip 93df14e59c feat: add pagination to user retrieval endpoints; enhance BuildUserResponse to include pagination details 2025-12-29 04:25:47 -05:00
whoswhip dd6ce5c395 feat: improve paste creation validation; add content size check and remove unnecessary logging 2025-12-29 04:25:35 -05:00
whoswhip 5fca207ad6 feat: enhance user experience with tooltips; implement return URL handling on login and registration; add user roles; improve paste visibility checks 2025-12-28 15:31:13 -05:00
whoswhip 4151c62b8c feat: implement server-side user data fetching; enhance user controller for detailed responses; update token handling to use cookies 2025-12-28 14:30:46 -05:00
whoswhip db1d8704a1 feat: 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;
fix: auth check
refactor: remove user UID api endpoint
2025-12-28 13:54:01 -05:00
whoswhip b9b14a3d5a feat: paste creation; paste viewing; more langs supported; jwt settings class; paste settings class; data validation on paste metadata modification 2025-12-28 08:34:53 -05:00
whoswhip adad139081 feat: paste cleanup service; sveltekit frontend; paste editing; paste metadata modifying
refactor: rename SharpbinV3 -> SharpbinV3.Server; run cleanup
2025-12-28 05:39:18 -05:00
whoswhip 19f439a405 fix: refresh token 2025-11-25 14:33:35 -05:00
whoswhip 4bd6a18e31 fix: remove unused nuget package 2025-11-25 01:18:41 -05:00
whoswhip 93daa2e1a2 feat: paste creation, utilities, revert to gzip, grammar fixes etc 2025-11-25 01:17:16 -05:00
whoswhip 6ec1a7fa7b feat: auth, compression, jwt, paste wip, roles, ratelimiting 2025-11-24 21:50:26 -05:00
whoswhip 050f0bc935 feat: initial commit 2025-11-24 14:00:13 -05:00
200 changed files with 19563 additions and 7229 deletions
-5
View File
@@ -28,8 +28,3 @@ README.md
!.git/config !.git/config
!.git/packed-refs !.git/packed-refs
!.git/refs/heads/** !.git/refs/heads/**
SharpbinV2.Server/*.db
SharpbinV2.Server/logs
SharpbinV2.Server/pastes
SharpbinV2.Server/.env
+9 -8
View File
@@ -33,10 +33,6 @@ bld/
[Ll]og/ [Ll]og/
[Ll]ogs/ [Ll]ogs/
p/
privp/
raw/
# Visual Studio 2015/2017 cache/options directory # Visual Studio 2015/2017 cache/options directory
.vs/ .vs/
# Uncomment if you have tasks that create the project's static files in wwwroot # Uncomment if you have tasks that create the project's static files in wwwroot
@@ -318,8 +314,13 @@ MigrationBackup/
# Fody - auto-generated XML schema # Fody - auto-generated XML schema
FodyWeavers.xsd FodyWeavers.xsd
SharpbinV2.Server/*.db # Database
SharpbinV2.Server/logs **/*.db
SharpbinV2.Server/pastes **/*.wal
SharpbinV2.Server/.env **/*.db-wal
**/*.db-shm
**/*.sqlite
Data
!SharpbinV3.Server/Data
.idea
-10
View File
@@ -1,10 +0,0 @@
{
"configurations": [
{
"name": "C#: SharpbinV2.Server Debug",
"type": "dotnet",
"request": "launch",
"projectPath": "${workspaceFolder}/SharpbinV2.Server/SharpbinV2.Server.csproj"
}
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"files.associations": {
"*.css": "tailwindcss"
},
"tailwindCSS.experimental.configFile": "SharpbinV3.Client/src/routes/layout.css"
}
+61 -19
View File
@@ -1,21 +1,63 @@
# SharpbinV2 # SharpbinV3
SharpbinV2 is a re-write to the original messy code base.
Instead of using html files and replacing variables(Simple SSR) it is now done with just apis and static html pages served from `wwwroot`. Sharpbin is a pastebin-style website built with ASP.NET Core and SvelteKit.
## 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.)
## TODO ## Features
- [ ] Password Resets
- [x] Switch to Controllers - User authentication and account management.
- [ ] Admin Panel - Syntax highlighting for various programming languages.
- [ ] Paste Editing - Private pastes with client-side encryption.
- [ ] Paste Searching (maybe) - Raw text serving for easy sharing and scripting.
- [x] Paste Deletion - Paste editing including content, syntax, title, and expiration.
- [ ] Switch to Razor Pages? - Configurable paste expiration.
- Server-side paste compression to save storage.
- Captcha support via Cloudflare Turnstile.
## Project Structure
- **[SharpbinV3.Server](SharpbinV3.Server/README.md)**: Backend API built with C# and ASP.NET Core. Refer to its README for server-side development and configuration.
- **[SharpbinV3.Client](SharpbinV3.Client/README.md)**: Frontend application built with SvelteKit and TypeScript. Refer to its README for client-side development and setup.
## Getting Started
The easiest way to run SharpbinV3 is using Docker Compose.
1. Ensure Docker and Docker Compose are installed.
2. Clone the repository.
```bash
git clone https://github.com/whoswhip/Sharpbin.git
```
3. Run the following command in the root directory:
```bash
docker-compose up -d
```
### Configuration
You can configure the application using environment variables. When using Docker Compose, these can be set in the `docker-compose.yml` file.
#### Backend (SharpbinV3.Server)
- `ConnectionStrings__DefaultConnection`: SQLite connection string (e.g., `Data Source=/app/data/sharpbin.db`).
- `JwtSettings__Secret`: A secure string used for signing JWT tokens.
- `AuthSettings__CF_Turnstile_SecretKey`: Your Cloudflare Turnstile secret key.
- `AuthSettings__CF_Turnstile_SiteKey`: Your Cloudflare Turnstile site key.
- `AuthSettings__Registration_Enabled`: Set to `true` by default, enables/disables registration.
- `AuthSettings__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.
- `PasteSettings__MaxTitleLength`: Max title length in characters.
- `PasteSettings__MaxPasteSizeInBytes`: Max Paste Size set in bytes, the default is `1_048_576` (1MB)
- `PasteSettings__EnablePasteCompression`: Enables/Disables server-side paste compression, `true` by default.
- `PasteSettings__RequiresVerification`: Enables/Disables CAPTCHA verification when creating pastes, `true` by default.
- `PasteSettings__View_HMAC_Secret`: Required to securely hash viewer identifiers
- `PasteSettings__View_Internal_API_Key`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
- `ASPNETCORE_ENVIRONMENT`: Set to `Production` or `Development`.
#### Frontend (SharpbinV3.Client)
- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`).
- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`)
- `VIEW_INTERNAL_API_KEY`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
The frontend will be accessible at http://localhost:5173.
@@ -1,297 +0,0 @@
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;
}
}
@@ -1,527 +0,0 @@
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." });
}
}
}
}
@@ -1,30 +0,0 @@
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 });
}
}
}
@@ -1,203 +0,0 @@
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"
};
}
}
}
@@ -1,182 +0,0 @@
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" });
}
}
}
}
-25
View File
@@ -1,25 +0,0 @@
#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"]
-13
View File
@@ -1,13 +0,0 @@
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; }
}
}
-19
View File
@@ -1,19 +0,0 @@
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; }
}
}
@@ -1,9 +0,0 @@
namespace SharpbinV2.Server.Models
{
public class RequestDetails
{
public string? Ip { get; set; }
public string? UserAgent { get; set; }
public string? Token { get; set; }
}
}
-13
View File
@@ -1,13 +0,0 @@
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; }
}
}
-15
View File
@@ -1,15 +0,0 @@
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; }
}
}
-12
View File
@@ -1,12 +0,0 @@
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; }
}
}
-298
View File
@@ -1,298 +0,0 @@
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]);
}
}
}
}
@@ -1,74 +0,0 @@
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;
}
}
}
@@ -1,775 +0,0 @@
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;
}
}
}
}
-106
View File
@@ -1,106 +0,0 @@
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();
}
}
}
}
@@ -1,40 +0,0 @@
<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>
@@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
-9
View File
@@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
-43
View File
@@ -1,43 +0,0 @@
<!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>
-229
View File
@@ -1,229 +0,0 @@
.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%);
}
-177
View File
@@ -1,177 +0,0 @@
.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;
}
}
-502
View File
@@ -1,502 +0,0 @@
::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;
}
@@ -1,152 +0,0 @@
.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);
}
}
-501
View File
@@ -1,501 +0,0 @@
#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;
}
}
-184
View File
@@ -1,184 +0,0 @@
* {
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;
}
}
-248
View File
@@ -1,248 +0,0 @@
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;
}
-53
View File
@@ -1,53 +0,0 @@
<!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()">&lt;</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>
-24
View File
@@ -1,24 +0,0 @@
<!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.

Before

Width:  |  Height:  |  Size: 17 KiB

-63
View File
@@ -1,63 +0,0 @@
<!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>
-145
View File
@@ -1,145 +0,0 @@
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);
}
};
-268
View File
@@ -1,268 +0,0 @@
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);
}
-22
View File
@@ -1,22 +0,0 @@
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;
}
});
-110
View File
@@ -1,110 +0,0 @@
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));
}
-89
View File
@@ -1,89 +0,0 @@
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');
}
}
});
-310
View File
@@ -1,310 +0,0 @@
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);
}
-707
View File
@@ -1,707 +0,0 @@
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;
-271
View File
@@ -1,271 +0,0 @@
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`;
};
-111
View File
@@ -1,111 +0,0 @@
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');
}
}
});
-76
View File
@@ -1,76 +0,0 @@
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';
}
-44
View File
@@ -1,44 +0,0 @@
<!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>
-52
View File
@@ -1,52 +0,0 @@
<!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>
-52
View File
@@ -1,52 +0,0 @@
<!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>
-46
View File
@@ -1,46 +0,0 @@
<!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>
-25
View File
@@ -1,25 +0,0 @@
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
+23
View File
@@ -0,0 +1,23 @@
node_modules
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
+1
View File
@@ -0,0 +1 @@
engine-strict=true
+9
View File
@@ -0,0 +1,9 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock
bun.lock
bun.lockb
# Miscellaneous
/static/
+16
View File
@@ -0,0 +1,16 @@
{
"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
View File
@@ -0,0 +1,6 @@
{
"files.associations": {
"*.css": "tailwindcss"
},
"tailwindCSS.experimental.configFile": "src/routes/layout.css"
}
+14
View File
@@ -0,0 +1,14 @@
# syntax=docker/dockerfile:1
FROM node:20-alpine as build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine as runner
WORKDIR /app
COPY --from=build /app .
RUN apk add --no-cache wget
EXPOSE 5173
CMD ["npm", "run", "preview", "--", "--host", "0.0.0.0", "--port", "5173"]
+53
View File
@@ -0,0 +1,53 @@
# SharpbinV3 Client
This is the SvelteKit frontend for SharpbinV3.
## Development Setup
### Prerequisites
- Node.js (v20 or newer recommended)
- npm
### Installation
Install the project dependencies:
```bash
npm install
```
### Environment Configuration
The application requires an environment variable to point to the backend API. Create a `.env` file in this directory or set the variable in your environment:
- `VITE_API_URL`: The URL of the backend API (e.g., `http://localhost:8080`).
- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.whoswhip.dev`)
- `VIEW_INTERNAL_API_KEY`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
### Running in Development
Start the development server with Hot Module Replacement (HMR):
```bash
npm run dev
```
The application will be available at http://localhost:5173.
## Script Reference
- `npm run dev`: Start the Vite development server.
- `npm run build`: Create a production build of the application.
- `npm run preview`: Locally preview the production build.
- `npm run check`: Run type checking with svelte-check.
- `npm run lint`: Run ESLint and Prettier checks.
- `npm run format`: Format the codebase with Prettier.
## Tech Stack
- Svelte 5 with SvelteKit.
- Tailwind CSS for styling.
- Lucide Svelte for icons.
- Highlight.js for syntax highlighting.
- TypeScript for type safety.
+41
View File
@@ -0,0 +1,41 @@
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';
import svelteConfig from './svelte.config.js';
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,
svelteConfig
}
}
}
);
+4943
View File
File diff suppressed because it is too large Load Diff
+50
View File
@@ -0,0 +1,50 @@
{
"name": "sharpbinv3.client",
"private": true,
"version": "3.0.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 ."
},
"devDependencies": {
"@eslint/compat": "^1.4.0",
"@eslint/js": "^9.39.1",
"@sveltejs/adapter-auto": "^7.0.0",
"@sveltejs/kit": "^2.50.0",
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17",
"@types/jsdom": "^27.0.0",
"@types/node": "^22",
"@types/qrcode": "^1.5.6",
"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.45.6",
"svelte-check": "^4.3.4",
"tailwindcss": "^4.1.17",
"typescript": "^5.9.3",
"typescript-eslint": "^8.48.1",
"vite": "^7.2.6"
},
"dependencies": {
"@lucide/svelte": "^0.562.0",
"@sveltejs/adapter-node": "^5.4.0",
"dompurify": "^3.3.1",
"hash-wasm": "^4.12.0",
"highlight.js": "^11.8.0",
"jsdom": "^27.4.0",
"marked": "^17.0.1",
"qrcode": "^1.5.4"
}
}
+32
View File
@@ -0,0 +1,32 @@
// 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;
}
export {};
+19
View File
@@ -0,0 +1,19 @@
<!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>
@@ -0,0 +1,6 @@
<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>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1,130 @@
<script lang="ts">
interface Option {
value: string | number;
label: string;
}
export let options: Option[] = [];
export let value: string | number = '';
export let placeholder = 'Select...';
export let searchable = false;
export let displayValue: (val: string | number) => string = (val) => {
return options.find((o) => o.value === val)?.label ?? String(val);
};
export let variant: string = '';
let isOpen = false;
let searchQuery = '';
let dropdownElement: HTMLDivElement;
$: filteredOptions = 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 && searchable) {
setTimeout(() => {
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 on:click={handleClickOutside} />
<div bind:this={dropdownElement} class="relative mb-2 w-full" class:dropdown-sm={variant === 'sm'}>
<button
type="button"
on:click={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'}
>
{#if searchable}
<input
type="text"
placeholder="Search..."
class="w-full border-b border-neutral-700 bg-neutral-800 p-2 outline-none"
class:dropdown-sm-input={variant === 'sm'}
bind:value={searchQuery}
on:keydown={handleKeyDown}
/>
{/if}
<div class="max-h-48 overflow-y-auto">
{#each filteredOptions as option (option.value)}
<button
type="button"
on:click={() => 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>
@@ -0,0 +1,14 @@
<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>
v{__APP_VERSION__}
</div>
@@ -0,0 +1,545 @@
<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';
export let show = false;
export let mode:
| 'decrypt'
| 'encrypt'
| 'confirm'
| 'prompt'
| 'multiselect'
| 'totp'
| 'totpSetup'
| 'report' = 'decrypt';
export let title = '';
export let message = '';
export let error = '';
export let placeholder = '';
export let inputType = 'text';
export let items: { label: string; value: unknown }[] = [];
export let initialValue: unknown = null;
export let totpActive: boolean | null = null;
export let reportTarget: 'user' | 'paste' | null = null;
export let reportTargetId: string | number | null = null;
export let reportSiteKey: string | null = null;
export let onConfirm: (value: unknown) => void;
export let onCancel: () => void;
export let confirmButtonText = '';
let inputValue: string | unknown[] | boolean = '';
let totpSecret = '';
let totpQr = '';
let totpEnabled = false;
let totpInitialized = false;
let totpLoading = false;
let totpError = '';
let displayError = '';
let reportTypes: string[] = [];
let reportType = '';
let reportInitialized = false;
let reportLoading = false;
let turnstileEl: HTMLDivElement | null = null;
let 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: totpEnabled ? 'Disable' : 'Enable',
totp: 'Verify',
report: 'Submit Report',
prompt: 'Submit'
};
$: displayError = error || totpError;
$: if (!show) resetModal();
$: if (show && mode === 'totpSetup' && !totpInitialized) {
totpInitialized = true;
if (totpActive !== null) {
totpEnabled = totpActive;
}
initializeTotp();
}
$: if (show && mode === 'report' && !reportInitialized) {
reportInitialized = true;
initializeReport();
}
function resetModal() {
inputValue =
initialValue !== null
? JSON.parse(JSON.stringify(initialValue))
: mode === 'multiselect'
? []
: '';
totpSecret = '';
totpQr = '';
totpEnabled = false;
totpInitialized = false;
totpLoading = false;
totpError = '';
reportTypes = [];
reportType = '';
reportInitialized = false;
reportLoading = 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() {
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'
});
};
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 res = await fetch(`/api/${reportTarget}/${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;
}
}
$: displayTitle = title || titleMap[mode];
$: confirmLabel = confirmButtonText || confirmLabelMap[mode];
$: shouldShowInput =
mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup' && mode !== 'report';
</script>
{#if show}
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
<form
on:submit|preventDefault={handleSubmit}
class="w-full max-w-md rounded 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"
on:click={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]*"
on:input={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="1000"
placeholder={placeholder || 'Describe the issue'}
class="h-28 w-full resize-none rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
></textarea>
{#if reportSiteKey}
<div class="flex justify-center">
<div class="cf-turnstile" bind:this={turnstileEl}></div>
</div>
{/if}
{/if}
</div>
{:else if shouldShowInput}
<input
type={inputType}
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"
on:click={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}
@@ -0,0 +1,25 @@
<script lang="ts">
import Modal from '$lib/components/Modal.svelte';
import { cancelModal, confirmModal, modal } from '$lib/stores/modal';
$: state = $modal;
</script>
<Modal
show={state.show}
mode={state.mode}
title={state.title}
message={state.message}
error={state.error}
placeholder={state.placeholder}
inputType={state.inputType}
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()}
/>
@@ -0,0 +1,141 @@
<script lang="ts">
import { user } from '$lib/stores/user';
import { resolve } from '$app/paths';
import { page } from '$app/state';
import { clearTokens } 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';
function logout() {
clearTokens();
user.set(null);
window.location.href = '/';
}
export let data: PageData;
let menuOpen = false;
let currentPath = page.url.pathname;
let returnParam =
currentPath !== '/' && !currentPath.startsWith('/login') && !currentPath.startsWith('/register')
? `?return=${encodeURIComponent(page.url.pathname + page.url.search)}`
: '';
</script>
<div class="top-0 left-0 z-100 h-15 w-full bg-neutral-900">
<div class="mx-auto hidden h-15 w-[95%] max-w-7xl items-center py-2 md:flex">
<div>
<a href={resolve('/')} class="text-xl font-bold text-white hover:text-neutral-300">Sharpbin</a
>
<a href={resolve('/recent')} class="ml-6 text-white hover:text-neutral-300">Recent Pastes</a>
</div>
{#if $user}
<div class="ml-auto flex items-center space-x-4">
{#if $user.roles.includes(1) || $user.roles.includes(255)}
<a
href={resolve('/reports')}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Reports</a
>
{/if}
<a
href={resolve(`/user/${$user.username}`)}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Profile</a
>
<button
on:click={logout}
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800"
>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 hover:bg-neutral-800">Login</a
>
<!-- eslint-disable svelte/no-navigation-without-resolve -->
<a
href={data.options?.registration_enabled ? resolve(`/register${returnParam}`) : '#'}
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800 {data.options
?.registration_enabled
? ''
: '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"
on:click={() => (menuOpen = !menuOpen)}
aria-label="Toggle Menu"
aria-expanded={menuOpen}
>
{#if menuOpen}
<X class="h-6 w-6 text-white" />
{:else}
<Menu class="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"
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"
on:click={() => (menuOpen = false)}>Recent Pastes</a
>
{#if $user}
{#if $user.roles.includes(1) || $user.roles.includes(255)}
<a
href={resolve('/reports')}
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
on:click={() => (menuOpen = false)}>Reports</a
>
{/if}
<a
href={resolve(`/user/${$user.username}`)}
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
on:click={() => (menuOpen = false)}>Profile</a
>
<button
on:click={() => {
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"
on:click={() => (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'}"
on:click={() => (menuOpen = false)}>Register</a
>
<!-- eslint-enable svelte/no-navigation-without-resolve -->
{/if}
</div>
{/if}
</div>
@@ -0,0 +1,95 @@
<script lang="ts">
import {
tooltip,
dateToRelativeString,
extractDateFromUUIDv7,
formatNumber,
formatBytes
} from '$lib/utils/misc';
import { resolve } from '$app/paths';
import { Eye, FileBox, Code, User, History, Calendar, Timer } from '@lucide/svelte';
import { syntaxes } from '$lib/consts';
import type { Paste } from '$lib/types/paste';
export let paste: Paste;
export let now: Date;
const createdAt = extractDateFromUUIDv7(paste.uuid);
const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext'];
</script>
<a
href={resolve(`/${paste.id}`)}
class="flex flex-col gap-2 rounded border border-neutral-700 bg-neutral-800 px-5 py-4 transition-colors duration-200 hover:bg-neutral-700 focus:ring-2 focus:ring-neutral-600 focus:outline-none"
>
<span
class="w-fit max-w-full truncate text-lg font-semibold text-neutral-100 hover:text-white"
use:tooltip={paste.title || 'Untitled Paste'}
>
{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={`${createdAt?.toLocaleString()} • ${dateToRelativeString(createdAt ?? new Date(), true, false, now)}`}
>
<Calendar class="h-4 w-4" />
<span>
{#if createdAt}
{#if createdAt.getTime() > Date.now() - 86_400_000}
Created {dateToRelativeString(createdAt, true, false, now)}
{:else}
Created on {createdAt.toLocaleDateString()}
{/if}
{:else}
Creation date unknown
{/if}
</span>
</div>
{#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()}
>
<Timer 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}
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
<User class="h-4 w-4" />
<span>{paste.author?.username ?? 'Anonymous'}</span>
</div>
{#if paste.editedAt}
<div
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={new Date(paste.editedAt).toLocaleString()}
>
<History class="h-4 w-4" />
<span>Edited {dateToRelativeString(new Date(paste.editedAt), true, false, now)}</span>
</div>
{/if}
</div>
<div>
<div class="flex items-center gap-2 text-sm text-neutral-400">
<Eye class="h-4 w-4" />
<span>{formatNumber(paste.views)} View{paste.views !== 1 ? 's' : ''}</span>
</div>
<div
class="mt-1 flex items-center gap-2 text-sm text-neutral-400"
use:tooltip={paste.isCompressed ? `Compressed Size: ${formatBytes(paste.size)}` : ''}
>
<FileBox class="h-4 w-4" />
<span>{formatBytes(paste.trueSize)}</span>
</div>
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
<Code class="h-4 w-4" />
<span>{syntax.name}</span>
</div>
</div>
</div>
</a>
+197
View File
@@ -0,0 +1,197 @@
export type Syntax = {
name: string;
extension: string;
};
export const syntaxes: Record<string, Syntax> = {
plaintext: { name: 'Plain Text', extension: '' },
abap: { name: 'ABAP', extension: '.abap' },
'actionscript-3': { name: 'ActionScript 3', extension: '.as' },
ada: { name: 'Ada', extension: '.adb' },
apache: { name: 'Apache', extension: '.conf' },
apex: { name: 'Apex', extension: '.cls' },
apl: { name: 'APL', extension: '.apl' },
applescript: { name: 'AppleScript', extension: '.applescript' },
ara: { name: 'ARA', extension: '.ara' },
asm: { name: 'Assembly', extension: '.asm' },
astro: { name: 'Astro', extension: '.astro' },
awk: { name: 'AWK', extension: '.awk' },
ballerina: { name: 'Ballerina', extension: '.bal' },
bat: { name: 'Batch', extension: '.bat' },
berry: { name: 'Berry', extension: '.be' },
bibtex: { name: 'BibTeX', extension: '.bib' },
bicep: { name: 'Bicep', extension: '.bicep' },
blade: { name: 'Blade', extension: '.blade.php' },
c: { name: 'C', extension: '.c' },
cadence: { name: 'Cadence', extension: '.cdc' },
clarity: { name: 'Clarity', extension: '.clar' },
clojure: { name: 'Clojure', extension: '.clj' },
cmake: { name: 'CMake', extension: '.cmake' },
cobol: { name: 'COBOL', extension: '.cob' },
codeql: { name: 'CodeQL', extension: '.ql' },
coffee: { name: 'CoffeeScript', extension: '.coffee' },
cpp: { name: 'C++', extension: '.cpp' },
crystal: { name: 'Crystal', extension: '.cr' },
csharp: { name: 'C#', extension: '.cs' },
css: { name: 'CSS', extension: '.css' },
cue: { name: 'CUE', extension: '.cue' },
d: { name: 'D', extension: '.d' },
dart: { name: 'Dart', extension: '.dart' },
diff: { name: 'Diff', extension: '.diff' },
docker: { name: 'Docker', extension: 'Dockerfile' },
'dream-maker': { name: 'Dream Maker', extension: '.dm' },
elixir: { name: 'Elixir', extension: '.ex' },
elm: { name: 'Elm', extension: '.elm' },
erb: { name: 'ERB', extension: '.erb' },
erlang: { name: 'Erlang', extension: '.erl' },
fish: { name: 'Fish', extension: '.fish' },
fsharp: { name: 'F#', extension: '.fs' },
gdresource: { name: 'Godot Resource', extension: '.tres' },
gdscript: { name: 'GDScript', extension: '.gd' },
gdshader: { name: 'Godot Shader', extension: '.gdshader' },
gherkin: { name: 'Gherkin', extension: '.feature' },
'git-commit': { name: 'Git Commit', extension: '' },
'git-rebase': { name: 'Git Rebase', extension: '' },
glsl: { name: 'GLSL', extension: '.glsl' },
gnuplot: { name: 'Gnuplot', extension: '.gp' },
go: { name: 'Go', extension: '.go' },
graphql: { name: 'GraphQL', extension: '.graphql' },
groovy: { name: 'Groovy', extension: '.groovy' },
hack: { name: 'Hack', extension: '.hack' },
haml: { name: 'Haml', extension: '.haml' },
handlebars: { name: 'Handlebars', extension: '.hbs' },
haskell: { name: 'Haskell', extension: '.hs' },
hcl: { name: 'HCL', extension: '.hcl' },
hjson: { name: 'HJSON', extension: '.hjson' },
hlsl: { name: 'HLSL', extension: '.hlsl' },
html: { name: 'HTML', extension: '.html' },
ini: { name: 'INI', extension: '.ini' },
java: { name: 'Java', extension: '.java' },
javascript: { name: 'JavaScript', extension: '.js' },
jison: { name: 'Jison', extension: '.jison' },
json: { name: 'JSON', extension: '.json' },
json5: { name: 'JSON5', extension: '.json5' },
jsonc: { name: 'JSONC', extension: '.json' },
jsonnet: { name: 'Jsonnet', extension: '.jsonnet' },
jssm: { name: 'JSSM', extension: '.jssm' },
jsx: { name: 'JSX', extension: '.jsx' },
julia: { name: 'Julia', extension: '.jl' },
kotlin: { name: 'Kotlin', extension: '.kt' },
latex: { name: 'LaTeX', extension: '.tex' },
less: { name: 'Less', extension: '.less' },
liquid: { name: 'Liquid', extension: '.liquid' },
lisp: { name: 'Lisp', extension: '.lisp' },
logo: { name: 'Logo', extension: '.logo' },
lua: { name: 'Lua', extension: '.lua' },
makefile: { name: 'Makefile', extension: '.makefile' },
markdown: { name: 'Markdown', extension: '.md' },
marko: { name: 'Marko', extension: '.marko' },
matlab: { name: 'MATLAB', extension: '.m' },
mdx: { name: 'MDX', extension: '.mdx' },
nginx: { name: 'Nginx', extension: '.conf' },
nim: { name: 'Nim', extension: '.nim' },
nix: { name: 'Nix', extension: '.nix' },
'objective-c': { name: 'Objective-C', extension: '.m' },
'objective-cpp': { name: 'Objective-C++', extension: '.mm' },
ocaml: { name: 'OCaml', extension: '.ml' },
pascal: { name: 'Pascal', extension: '.pas' },
perl: { name: 'Perl', extension: '.pl' },
php: { name: 'PHP', extension: '.php' },
plsql: { name: 'PL/SQL', extension: '.sql' },
postcss: { name: 'PostCSS', extension: '.pcss' },
powerquery: { name: 'Power Query', extension: '.pq' },
powershell: { name: 'PowerShell', extension: '.ps1' },
prisma: { name: 'Prisma', extension: '.prisma' },
prolog: { name: 'Prolog', extension: '.pl' },
proto: { name: 'Protocol Buffers', extension: '.proto' },
pug: { name: 'Pug', extension: '.pug' },
puppet: { name: 'Puppet', extension: '.pp' },
purescript: { name: 'PureScript', extension: '.purs' },
python: { name: 'Python', extension: '.py' },
r: { name: 'R', extension: '.r' },
raku: { name: 'Raku', extension: '.raku' },
razor: { name: 'Razor', extension: '.cshtml' },
reg: { name: 'Registry', extension: '.reg' },
rel: { name: 'Rel', extension: '.rel' },
riscv: { name: 'RISC-V', extension: '.s' },
rst: { name: 'reStructuredText', extension: '.rst' },
ruby: { name: 'Ruby', extension: '.rb' },
rust: { name: 'Rust', extension: '.rs' },
sas: { name: 'SAS', extension: '.sas' },
sass: { name: 'Sass', extension: '.sass' },
scala: { name: 'Scala', extension: '.scala' },
scheme: { name: 'Scheme', extension: '.scm' },
scss: { name: 'SCSS', extension: '.scss' },
shaderlab: { name: 'ShaderLab', extension: '.shader' },
shell: { name: 'Shell', extension: '.sh' },
smalltalk: { name: 'Smalltalk', extension: '.st' },
solidity: { name: 'Solidity', extension: '.sol' },
sparql: { name: 'SPARQL', extension: '.rq' },
sql: { name: 'SQL', extension: '.sql' },
'ssh-config': { name: 'SSH Config', extension: '' },
stata: { name: 'Stata', extension: '.do' },
stylus: { name: 'Stylus', extension: '.styl' },
svelte: { name: 'Svelte', extension: '.svelte' },
swift: { name: 'Swift', extension: '.swift' },
'system-verilog': { name: 'SystemVerilog', extension: '.sv' },
tasl: { name: 'TASL', extension: '.tasl' },
tcl: { name: 'Tcl', extension: '.tcl' },
tex: { name: 'TeX', extension: '.tex' },
toml: { name: 'TOML', extension: '.toml' },
tsx: { name: 'TSX', extension: '.tsx' },
turtle: { name: 'Turtle', extension: '.ttl' },
twig: { name: 'Twig', extension: '.twig' },
typescript: { name: 'TypeScript', extension: '.ts' },
v: { name: 'V', extension: '.v' },
vb: { name: 'VB', extension: '.vb' },
verilog: { name: 'Verilog', extension: '.v' },
vhdl: { name: 'VHDL', extension: '.vhdl' },
viml: { name: 'VimL', extension: '.vim' },
vue: { name: 'Vue', extension: '.vue' },
wasm: { name: 'WebAssembly', extension: '.wasm' },
wenyan: { name: 'Wenyan', extension: '.wy' },
xml: { name: 'XML', extension: '.xml' },
xsl: { name: 'XSL', extension: '.xsl' },
yaml: { name: 'YAML', extension: '.yaml' },
zenscript: { name: 'ZenScript', extension: '.zs' }
};
export const roles = {
0: 'User',
1: 'Moderator',
255: 'Administrator',
403: 'Banned'
};
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
View File
@@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.
+83
View File
@@ -0,0 +1,83 @@
import { writable } from 'svelte/store';
type ModalMode =
| 'decrypt'
| 'encrypt'
| 'confirm'
| 'prompt'
| 'multiselect'
| 'totp'
| 'totpSetup'
| 'report';
type ModalItem = { label: string; value: unknown };
type ModalState = {
show: boolean;
mode: ModalMode;
title: string;
message: string;
error: string;
placeholder: string;
inputType: string;
items: ModalItem[];
initialValue: unknown;
totpActive: boolean | null;
reportTarget: 'user' | 'paste' | null;
reportTargetId: string | number | null;
reportSiteKey: string | null;
confirmButtonText: string;
};
type ModalOpenOptions = Partial<Omit<ModalState, 'show'>> & {
mode: ModalMode;
cancelValue?: unknown;
};
const initialState: ModalState = {
show: false,
mode: 'confirm',
title: '',
message: '',
error: '',
placeholder: '',
inputType: 'text',
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);
}
+31
View File
@@ -0,0 +1,31 @@
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');
});
}
@@ -0,0 +1,6 @@
export interface Author {
uid: number;
uuid: string;
username: string;
visibility: 0 | 1 | 2;
}
@@ -0,0 +1,6 @@
export interface Pagination {
page: number;
pageSize: number;
totalCount: number;
totalPages: number;
}
+17
View File
@@ -0,0 +1,17 @@
import type { Author } from './author';
export interface Paste {
id: string;
uuid: string;
title: string | null;
size: number;
trueSize: number;
isCompressed: boolean;
views: number;
syntax: string;
visibility: 0 | 1 | 2;
expiresAt: number;
editedAt: number | null;
reportCount: number | null;
author: Author | null;
}
+38
View File
@@ -0,0 +1,38 @@
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 = [
'Spam',
'Abuse',
'InappropriateContent',
'CopyrightViolation',
'Fraud',
'Other'
] as const;
export const reportStatusLabels = ['Open', 'InProgress', 'Resolved', 'Closed'] as const;
export const reportTargetLabels = ['Paste', 'User'] as const;
+19
View File
@@ -0,0 +1,19 @@
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;
lastLogin: number | null;
roles: number[];
visibility: 0 | 1 | 2;
pastes: Paste[] | null;
pagination: Pagination | null;
}
export interface AuthUser extends User {
totpEnabled: boolean;
}
+102
View File
@@ -0,0 +1,102 @@
import { browser } from '$app/environment';
import type { Cookies } from '@sveltejs/kit';
import { user } from '$lib/stores/user';
const TOKEN_KEY = 'token';
const REFRESH_TOKEN_KEY = 'refreshToken';
export function getToken() {
if (!browser) return null;
return (
document.cookie
.split('; ')
.find((c) => c.startsWith(`${TOKEN_KEY}=`))
?.split('=')[1] || null
);
}
export function getRefreshToken() {
if (!browser) return null;
return (
document.cookie
.split('; ')
.find((c) => c.startsWith(`${REFRESH_TOKEN_KEY}=`))
?.split('=')[1] || null
);
}
export function setTokens(token: string, refreshToken: string) {
if (!browser) return;
console.log('Setting tokens');
document.cookie = `${TOKEN_KEY}=${token}; path=/; secure; samesite=strict`;
document.cookie = `${REFRESH_TOKEN_KEY}=${refreshToken}; path=/; secure; samesite=strict`;
}
export function clearTokens() {
if (!browser) return;
console.log('Clearing tokens');
document.cookie = `${TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
document.cookie = `${REFRESH_TOKEN_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
user.set(null);
}
export async function refreshTokenIfNeeded() {
const token = getToken();
const refreshToken = getRefreshToken();
if (!token || !refreshToken) return;
const payload = JSON.parse(atob(token.split('.')[1]));
const exp = payload.exp * 1000;
const now = Date.now();
if (exp - now < 2 * 60 * 1000) {
console.log('Refreshing token...');
const res = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, refreshToken })
});
if (res.ok) {
const data = await res.json();
if (data.success && data.token?.token && data.token?.refreshToken) {
console.log('Token refreshed successfully');
setTokens(data.token.token, data.token.refreshToken);
} else {
console.log('Invalid tokens received during refresh');
clearTokens();
}
} else {
console.log('Failed to refresh token');
clearTokens();
}
}
console.log('Token is still valid, no refresh needed');
}
export function startTokenRefreshInterval() {
if (!browser) return;
setInterval(refreshTokenIfNeeded, 60 * 1000);
}
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 });
cookies.set('refreshToken', refreshToken, {
path: '/',
httpOnly: true,
sameSite: 'strict',
secure: true
});
}
export function clearServerTokens(cookies: Cookies) {
cookies.delete('token', { path: '/' });
cookies.delete('refreshToken', { path: '/' });
}
@@ -0,0 +1,149 @@
import { argon2id } from 'hash-wasm';
function toBase64(bytes: Uint8Array): string {
let binary = '';
const chunkSize = 0x8000;
for (let i = 0; i < bytes.length; i += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
}
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 async function encryptAES(content: string, password: string): Promise<string> {
const enc = new TextEncoder();
const salt = window.crypto.getRandomValues(new Uint8Array(32));
const memorySize = 65536;
const iterations = 3;
const parallelism = 1;
const keyMaterial = await argon2id({
password,
salt,
iterations,
memorySize,
parallelism,
hashLength: 32,
outputType: 'binary'
});
const key = await window.crypto.subtle.importKey(
'raw',
keyMaterial as unknown as BufferSource,
{ name: 'AES-GCM' },
false,
['encrypt']
);
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const encryptedContent = await window.crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv
},
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({
version: 4,
kdf: 'Argon2id',
memorySize,
iterations,
parallelism,
algorithm: 'AES-GCM',
saltLength: salt.byteLength,
ivLength: iv.byteLength,
data: toBase64(combined)
});
}
export function estimateEncryptedSize(content: string): number {
const rawSize = new TextEncoder().encode(content).length;
const combinedSize = rawSize + 60;
const b64Size = Math.ceil(combinedSize / 3) * 4;
return b64Size + 150;
}
export async function decryptAES(result: string, password: string): Promise<string | null> {
try {
const enc = new TextEncoder();
const parsed = JSON.parse(result);
const combined = fromBase64(parsed.data);
const saltLength = parsed.saltLength || 16;
const ivLength = parsed.ivLength || 12;
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: 32,
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: 256 },
true,
['encrypt', 'decrypt']
);
keyMaterial = await window.crypto.subtle.exportKey('raw', derivedKey);
}
const key = await window.crypto.subtle.importKey(
'raw',
keyMaterial as unknown as BufferSource,
{ name: 'AES-GCM' },
false,
['decrypt']
);
const decryptedContent = await window.crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv
},
key,
data
);
return new TextDecoder().decode(decryptedContent);
} catch {
return null;
}
}
+110
View File
@@ -0,0 +1,110 @@
import { marked } from 'marked';
import createDOMPurify from 'dompurify';
import type { WindowLike } from 'dompurify';
import { trustedDomains } from '$lib/consts';
const tagMap: Record<string, string> = {
IMG: 'image',
VIDEO: 'video',
AUDIO: 'audio',
IFRAME: 'iframe'
};
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;'
);
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') || '');
placeholder.appendChild(warning);
placeholder.appendChild(subWarning);
placeholder.appendChild(button);
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);
}
+286
View File
@@ -0,0 +1,286 @@
import { syntaxes } from '$lib/consts';
export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return '0 Bytes';
const unit = 1024;
const units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const exponent = Math.floor(Math.log(bytes) / Math.log(unit));
const value = bytes / Math.pow(unit, exponent);
const unitLabel = value === 1 && exponent === 0 ? 'Byte' : units[exponent];
const formattedValue = Number.isInteger(value) ? value : value.toFixed(decimals);
return `${formattedValue} ${unitLabel}`;
}
export function formatNumber(num: number): string {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
export function extractDateFromUUIDv7(uuid?: string): Date | null {
if (!uuid) return null;
const hex = uuid.replace(/-/g, '');
const timestampHex = hex.slice(0, 12);
return new Date(parseInt(timestampHex, 16));
}
export function isBinaryData(buffer: ArrayBuffer | Uint8Array): boolean {
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
if (bytes.includes(0)) return true;
try {
new TextDecoder('utf-8', { fatal: true }).decode(bytes);
return false;
} catch {
return true;
}
}
export function extractError(resData: unknown): string | null {
if (!resData || typeof resData !== 'object') return null;
const data = resData as { errors?: unknown; message?: unknown };
if (data.errors && typeof data.errors === 'object') {
return Object.values(data.errors as Record<string, unknown>)
.flat()
.filter((v) => typeof v === 'string')
.join('\n');
}
if (typeof data.message === 'string') {
return data.message;
}
return null;
}
export function syntaxFromExtension(extension: string): string | null {
const ext = extension.startsWith('.') ? extension.slice(1) : extension;
for (const [key, value] of Object.entries(syntaxes)) {
if (value.extension === `.${ext}`) {
return key;
}
}
return null;
}
export function dateToRelativeString(
date: Date,
useSuffix = true,
full = false,
nowArg?: Date,
accuracy = 1
): string {
const now = nowArg ?? new Date();
const isFuture = date > now;
const suffix = useSuffix ? (isFuture ? 'from now' : 'ago') : '';
const diff = Math.abs(now.getTime() - date.getTime());
let seconds = Math.floor(diff / 1000);
const units = [
{ name: 'year', value: 365 * 24 * 60 * 60 },
{ name: 'month', value: 30 * 24 * 60 * 60 },
{ name: 'week', value: 7 * 24 * 60 * 60 },
{ name: 'day', value: 24 * 60 * 60 },
{ name: 'hour', value: 60 * 60 },
{ name: 'minute', value: 60 },
{ name: 'second', value: 1 }
];
if (!full) {
for (const unit of units) {
const count = Math.floor(seconds / unit.value);
if (count > 0) {
return `${count} ${unit.name}${count > 1 ? 's' : ''} ${suffix}`.trim();
}
}
return `0 seconds ${suffix}`.trim();
}
const parts: string[] = [];
let acc = 0;
for (const unit of units) {
if (acc >= accuracy) break;
const count = Math.floor(seconds / unit.value);
if (count > 0) {
parts.push(`${count} ${unit.name}${count > 1 ? 's' : ''}`);
seconds -= count * unit.value;
acc++;
}
}
if (parts.length === 0) parts.push('0 seconds');
return `${parts.join(', ')} ${suffix}`.trim();
}
export function tooltip(node: HTMLElement, text: string) {
let currentText = text ?? '';
let tooltipEl: HTMLDivElement | null = null;
let caretEl: HTMLDivElement | null = null;
let showTimeout: ReturnType<typeof setTimeout>;
let hideTimeout: ReturnType<typeof setTimeout>;
function createTooltip() {
if (!currentText || currentText.trim() === '') return;
const el = document.createElement('div');
el.className =
'fixed z-50 rounded bg-neutral-800 px-2 py-1 text-sm text-white shadow-lg opacity-0 transition-opacity duration-150';
el.style.maxWidth = '90%';
el.style.wordBreak = 'break-word';
el.addEventListener('mouseover', () => {
clearTimeout(hideTimeout);
if (tooltipEl) tooltipEl.style.opacity = '1';
});
el.addEventListener('mouseout', mouseOut);
const lines = currentText.split('\n');
if (lines.length > 1) {
el.innerHTML = '';
lines.forEach((line, index) => {
const span = document.createElement('span');
span.textContent = line;
el.appendChild(span);
if (index < lines.length - 1) el.appendChild(document.createElement('br'));
});
} else {
el.textContent = currentText;
}
const caret = document.createElement('div');
caret.style.position = 'absolute';
caret.style.width = '0';
caret.style.height = '0';
caret.style.left = '50%';
caret.style.transform = 'translateX(-50%)';
caret.style.pointerEvents = 'none';
caretEl = caret;
el.appendChild(caret);
document.body.appendChild(el);
tooltipEl = el;
}
function updateContent() {
if (!tooltipEl) return;
if (!currentText || currentText.trim() === '') {
tooltipEl.remove();
tooltipEl = null;
caretEl = null;
return;
}
const lines = currentText.split('\n');
tooltipEl.innerHTML = '';
if (lines.length > 1) {
lines.forEach((line, index) => {
const span = document.createElement('span');
span.textContent = line;
tooltipEl?.appendChild(span);
if (index < lines.length - 1) tooltipEl?.appendChild(document.createElement('br'));
});
} else {
tooltipEl.textContent = currentText;
}
if (!caretEl) {
const caret = document.createElement('div');
caret.style.position = 'absolute';
caret.style.width = '0';
caret.style.height = '0';
caret.style.left = '50%';
caret.style.transform = 'translateX(-50%)';
caret.style.pointerEvents = 'none';
caretEl = caret;
tooltipEl.appendChild(caretEl);
} else {
tooltipEl.appendChild(caretEl);
}
}
function positionTooltip() {
if (!tooltipEl || !caretEl) return;
const rect = node.getBoundingClientRect();
const tooltipRect = tooltipEl.getBoundingClientRect();
let top = rect.top - tooltipRect.height - 8 + window.scrollY;
let left = rect.left + rect.width / 2 - tooltipRect.width / 2 + window.scrollX;
let caretOnTop = false;
if (top < window.scrollY) {
top = rect.bottom + 8 + window.scrollY;
caretOnTop = true;
}
if (left < 0) left = 8;
if (left + tooltipRect.width > window.innerWidth)
left = window.innerWidth - tooltipRect.width - 8;
tooltipEl.style.top = `${top}px`;
tooltipEl.style.left = `${left}px`;
tooltipEl.style.position = 'absolute';
caretEl.style.top = caretOnTop ? '-7px' : '';
caretEl.style.bottom = caretOnTop ? '' : '-7px';
caretEl.style.borderLeft = '7px solid transparent';
caretEl.style.borderRight = '7px solid transparent';
if (caretOnTop) {
caretEl.style.borderBottom = '7px solid #27272a';
caretEl.style.borderTop = '';
} else {
caretEl.style.borderTop = '7px solid #27272a';
caretEl.style.borderBottom = '';
}
}
function mouseOver() {
clearTimeout(hideTimeout);
if (tooltipEl) tooltipEl.style.opacity = '1';
showTimeout = setTimeout(() => {
if (!tooltipEl) createTooltip();
else updateContent();
positionTooltip();
requestAnimationFrame(() => {
if (tooltipEl) tooltipEl.style.opacity = '1';
});
}, 200);
}
function mouseOut() {
clearTimeout(showTimeout);
if (tooltipEl) {
tooltipEl.style.opacity = '0';
hideTimeout = setTimeout(() => {
if (tooltipEl) {
tooltipEl.remove();
tooltipEl = null;
caretEl = null;
}
}, 150);
}
}
node.addEventListener('mouseover', mouseOver);
node.addEventListener('mouseout', mouseOut);
window.addEventListener('scroll', mouseOut, true);
window.addEventListener('resize', mouseOut, true);
return {
update(newText: string) {
currentText = newText ?? '';
if (!currentText || currentText.trim() === '') {
if (tooltipEl) {
tooltipEl.remove();
tooltipEl = null;
caretEl = null;
}
return;
}
if (tooltipEl) {
updateContent();
positionTooltip();
}
},
destroy() {
node.removeEventListener('mouseover', mouseOver);
node.removeEventListener('mouseout', mouseOut);
window.removeEventListener('scroll', mouseOut, true);
window.removeEventListener('resize', mouseOut, true);
if (tooltipEl) tooltipEl.remove();
}
};
}
+18
View File
@@ -0,0 +1,18 @@
export function parseTotpEnabled(tokenValue: string | null) {
if (!tokenValue) return false;
try {
const payload = JSON.parse(atob(tokenValue.split('.')[1]));
const flag = payload?.totp_enabled;
if (typeof flag === 'string') return flag.toLowerCase() === 'true';
return Boolean(flag);
} catch {
return false;
}
}
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number[], nextRoles: number[]) {
if (!totpEnabled) return false;
const nextHasAdmin = nextRoles.includes(255);
const alreadyAdmin = currentRoles.includes(255);
return nextHasAdmin && !alreadyAdmin;
}
@@ -0,0 +1,24 @@
<script lang="ts">
import { page } from '$app/state';
let status = page.status;
let error = page.error;
let message = error?.message || 'An unexpected error occurred.';
</script>
<svelte:head>
<title>{status} - Error - Sharpbin</title>
<meta name="description" content="An error occurred while processing your request." />
</svelte:head>
<main
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div
class="w-[95%] max-w-7xl rounded border-2
border-neutral-800 bg-neutral-900 p-6 text-center"
>
<h1 class="mb-4 text-4xl font-bold">Error {status}</h1>
<p class="mb-2 text-lg">{message}</p>
</div>
</main>
@@ -0,0 +1,13 @@
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ fetch, url }) => {
try {
const res = await fetch('/api/auth/info');
const pasteOptionsRes = await fetch('/api/paste/info');
const options = await res.json();
const pasteOptions = await pasteOptionsRes.json();
return { options, pasteOptions, url: url.href };
} catch {
return { options: null, pasteOptions: null, url: url.href };
}
};
@@ -0,0 +1,65 @@
<script lang="ts">
import { onMount } from 'svelte';
import './layout.css';
import favicon from '$lib/assets/favicon.svg';
import Navbar from '$lib/components/Navbar.svelte';
import Footer from '$lib/components/Footer.svelte';
import ModalHost from '$lib/components/ModalHost.svelte';
import { user } from '$lib/stores/user';
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
import { parseTotpEnabled } from '$lib/utils/totp';
import { page } from '$app/state';
import type { LayoutData } from './$types';
export let data: LayoutData;
if (typeof window !== 'undefined') {
startTokenRefreshInterval();
window.turnstileLoaded = () => {
window.dispatchEvent(new CustomEvent('turnstile:loaded'));
};
}
onMount(async () => {
await refreshTokenIfNeeded();
const token = getToken();
if (!token) {
user.set(null);
return;
}
const res = await fetch('/api/user/me', {
headers: { Authorization: `Bearer ${token}` }
});
if (res.ok) {
const me = await res.json();
let userData = me;
if (me && 'user' in me && typeof me.user === 'object') {
const { user: nestedUser, ...rest } = me;
userData = { ...rest, ...nestedUser };
}
user.set({ ...userData, totpEnabled: parseTotpEnabled(getToken()) });
} else {
user.set(null);
}
});
</script>
<svelte:head>
<link rel="icon" href={favicon} />
{#if data.options?.cf_turnstile_site_key && (page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/')}
<script
src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=turnstileLoaded"
async
defer
></script>
{/if}
</svelte:head>
<Navbar {data} />
<!-- <div class="h-15 w-full"></div> -->
<slot />
<Footer />
<ModalHost />
@@ -0,0 +1,13 @@
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch, url }) => {
try {
const optionsRes = await fetch('/api/paste/info');
const authInfo = await fetch('/api/auth/info');
const options = await optionsRes.json();
const auth = await authInfo.json();
return { options, auth, url: url.href };
} catch {
return { options: null, url: url.href };
}
};
+512
View File
@@ -0,0 +1,512 @@
<script lang="ts">
import type { PageData } from './$types';
import { syntaxes } from '$lib/consts';
import { user } from '$lib/stores/user';
import { getToken } from '$lib/utils/auth';
import { onMount } from 'svelte';
import { fly, fade } from 'svelte/transition';
import { encryptAES, estimateEncryptedSize } from '$lib/utils/encryption';
import {
formatBytes,
formatNumber,
isBinaryData,
tooltip,
syntaxFromExtension
} from '$lib/utils/misc';
import { parseMarkdown } from '$lib/utils/markdown';
import Dropdown from '$lib/components/Dropdown.svelte';
import { SvelteURLSearchParams } from 'svelte/reactivity';
import { FileUp, X, Eye, EyeClosed, Dices } from '@lucide/svelte';
export let data: PageData;
let textArea: HTMLTextAreaElement;
let error = '';
let title = '';
let content = '';
let selectedSyntax = data.options?.syntaxes?.[0];
let expiresIn: number = 0;
let selectedVisibility = data.options?.visibilities?.[0]?.value;
let password = '';
let passwordVisible = false;
let anonymousUpload = false;
let isDragging = false;
let dragError = '';
let previewMode = false;
let renderedMarkdown = '';
$: currentByteSize =
selectedVisibility === 2
? estimateEncryptedSize(content)
: new TextEncoder().encode(content).length;
$: if (selectedSyntax !== 'markdown') {
previewMode = false;
}
const MAX_HEIGHT = () => Math.floor((window.innerHeight - 120) * 0.6);
let previewHeight = 'auto';
async function togglePreview(toPreview: boolean) {
if (toPreview && !previewMode) {
previewHeight = textArea?.style.height || 'auto';
renderedMarkdown = await parseMarkdown(content, false);
}
previewMode = toPreview;
if (!toPreview) {
requestAnimationFrame(resize);
}
}
function resize() {
if (!textArea) return;
textArea.style.height = 'auto';
const h = textArea.scrollHeight;
const max = MAX_HEIGHT();
if (h > max) {
textArea.style.height = max + 'px';
textArea.style.overflowY = 'auto';
} else {
textArea.style.height = h + 'px';
textArea.style.overflowY = 'hidden';
}
}
onMount(() => {
resize();
const render = () => {
if (
window.turnstile &&
data.options?.requiresVerification &&
data.auth?.cf_turnstile_site_key
) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.auth.cf_turnstile_site_key,
theme: 'dark'
});
}
};
if (window.turnstile) {
render();
} else {
window.addEventListener('turnstile:loaded', render, { once: true });
}
return () => {
window.removeEventListener('turnstile:loaded', render);
};
});
const syntaxOptions =
data.options?.syntaxes?.map((lang: string) => ({
value: lang,
label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1)
})) ?? [];
const expiresOptions = [
{ value: 0, label: 'Never Expire' },
{ value: 600000, label: 'Expire in 10 Minutes' },
{ value: 3600000, label: 'Expire in 1 Hour' },
{ value: 86400000, label: 'Expire in 1 Day' },
{ value: 604800000, label: 'Expire in 1 Week' },
{ value: 1209600000, label: 'Expire in 2 Weeks' },
{ value: 2592000000, label: 'Expire in 1 Month' },
{ value: 7776000000, label: 'Expire in 3 Months' },
{ value: 15552000000, label: 'Expire in 6 Months' },
{ value: 31536000000, label: 'Expire in 1 Year' },
{ value: 63072000000, label: 'Expire in 2 Years' },
{ value: 157680000000, label: 'Expire in 5 Years' },
{ value: 315360000000, label: 'Expire in 10 Years' }
];
const visibilityOptions =
data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value,
label: visibility.displayName
})) ?? [];
async function handleSubmit(event: Event) {
event.preventDefault();
const params = new SvelteURLSearchParams({
title: title.trim(),
syntax: selectedSyntax,
visibility: selectedVisibility.toString(),
expiresAt: expiresIn > 0 ? (Date.now() + Number(expiresIn)).toString() : '0'
});
if (
data.options?.requiresVerification &&
data.auth?.cf_turnstile_site_key &&
window.turnstile
) {
const token = window.turnstile.getResponse();
if (token) {
params.append('token', token);
}
}
if (content.trim().length === 0) {
error = 'Paste content cannot be empty.';
setTimeout(() => {
error = '';
}, 5000);
return;
}
let body = content;
if (selectedVisibility === 2) {
body = await encryptAES(content, password);
}
if (
data.options?.maxPasteSize &&
new TextEncoder().encode(body).length > data.options.maxPasteSize
) {
error = `Paste exceeds the maximum size limit of ${formatBytes(data.options.maxPasteSize)}. ${selectedVisibility === 2 ? 'Encryption adds some overhead.' : ''}`;
setTimeout(() => {
error = '';
}, 5000);
return;
}
const url = `/api/paste/create?${params.toString()}`;
const options: RequestInit = {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body
};
if ($user && !anonymousUpload) {
const token = getToken();
if (token) {
options.headers = {
...options.headers,
Authorization: `Bearer ${token}`
};
}
}
const response = await fetch(url, options);
if (response.ok) {
const result = await response.json();
if (selectedVisibility === 2) {
const passwordBase64 = btoa(password);
window.location.href = `/${result.id}#${passwordBase64}`;
return;
}
window.location.href = `/${result.id}`;
} else {
if (window.turnstile) {
window.turnstile.reset();
}
if (response.status === 403) {
error = 'You are banned from creating new pastes.';
} else {
const resData = await response.json();
if (resData.errors) {
const messages = Object.values(resData.errors).flat();
error = messages.join('\n');
} else {
if (resData.message === 'Verification failed.') {
if (window.turnstile) {
window.turnstile.reset();
}
}
error = resData.message || 'Registration failed. Please try again.';
}
}
setTimeout(() => {
error = '';
}, 5000);
}
}
</script>
<svelte:head>
<title>Create a Paste - Sharpbin</title>
<meta property="og:title" content="Create a Paste - Sharpbin" />
<meta property="og:description" content="Create and share your pastes easily with Sharpbin." />
<meta property="og:type" content="website" />
<meta property="og:url" content={data.url} />
<meta property="og:site_name" content="Sharpbin" />
</svelte:head>
<main
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-4xl font-bold">Create a Paste</h1>
<form class="mt-4" on:submit|preventDefault={handleSubmit}>
<input
type="text"
placeholder="Title (optional)"
class="mb-4 w-full rounded border border-neutral-700 bg-neutral-800 p-2"
spellcheck="false"
autocomplete="off"
bind:value={title}
maxlength={data.options?.maxTitleLength ?? 500}
/>
<div>
<div class="relative">
{#if previewMode}
<div
class="markdown min-h-20 w-full overflow-y-auto rounded rounded-b-none border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200"
style="height: {previewHeight}"
>
{@html renderedMarkdown}
</div>
{:else}
<textarea
placeholder="Your paste content here..."
class="min-h-20 w-full resize-none overflow-hidden rounded rounded-b-none border border-neutral-700 bg-neutral-800 p-2 transition-colors duration-200"
spellcheck="false"
autocomplete="off"
minlength="1"
bind:this={textArea}
bind:value={content}
on:input={resize}
on:change={resize}
on:focus={resize}
on:beforeinput={(e) => {
if (!data.options?.maxPasteSize) return;
const futureSize =
selectedVisibility === 2
? estimateEncryptedSize(content + (e.data ?? ''))
: new TextEncoder().encode(content + (e.data ?? '')).length;
if (
futureSize > data.options.maxPasteSize &&
(e.data?.length ?? Number.MAX_SAFE_INTEGER < content.length)
) {
e.preventDefault();
}
}}
on:dragenter={(e) => {
e.preventDefault();
isDragging = true;
}}
on:dragover={(e) => {
e.preventDefault();
isDragging = true;
}}
on:dragleave={(e) => {
e.preventDefault();
isDragging = false;
}}
on:drop={(e) => {
requestAnimationFrame(resize);
e.preventDefault();
isDragging = false;
const file = e.dataTransfer?.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const arrayBuffer = e.target?.result as ArrayBuffer;
if (isBinaryData(new Uint8Array(arrayBuffer))) {
content = '';
dragError =
'The dropped file appears to be binary and cannot be pasted as text.';
setTimeout(() => {
dragError = '';
}, 5000);
return;
}
const syntax = syntaxFromExtension(file.name.split('.').pop() || '');
if (syntax && selectedSyntax !== syntax) {
selectedSyntax = syntax;
} else if (!syntax && selectedSyntax !== 'plaintext') {
selectedSyntax = 'plaintext';
}
title = file.name;
const decoder = new TextDecoder();
content = decoder.decode(arrayBuffer);
};
reader.readAsArrayBuffer(file);
}}
></textarea>
{/if}
{#if isDragging || (dragError && dragError !== '')}
<div
class="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-md rounded-b-none border-2 border-dashed border-neutral-500 bg-neutral-800/70 text-center text-neutral-300"
transition:fade={{ duration: 150 }}
>
<div class="relative flex h-full w-full items-center justify-center">
{#if dragError && dragError !== ''}
<div
class="absolute flex flex-col items-center gap-4"
transition:fly={{ y: -20, duration: 200 }}
>
<X class="h-12 w-12 text-red-500" />
<p>{dragError}</p>
</div>
{:else}
<div
class="absolute flex flex-col items-center gap-4"
transition:fly={{ y: -20, duration: 200 }}
>
<FileUp class="h-12 w-12" />
</div>
{/if}
</div>
</div>
{/if}
</div>
<div class="mt-1 flex">
{#if selectedSyntax === 'markdown'}
<div
class="monospace mb-2 flex h-12 w-36 items-center justify-between gap-1 rounded-bl border border-neutral-700 bg-neutral-800 p-1 text-sm text-neutral-400 md:h-8"
>
<button
type="button"
class="h-full w-1/2 rounded-l transition-colors {previewMode
? 'hover:bg-neutral-700'
: 'bg-neutral-700 text-white'}"
on:click={() => togglePreview(false)}
>
Code
</button>
<button
type="button"
class="h-full w-1/2 rounded-r transition-colors {!previewMode
? 'hover:bg-neutral-700'
: 'bg-neutral-700 text-white'}"
on:click={() => togglePreview(true)}
>
Preview
</button>
</div>
{/if}
<div
class="monospace mb-2 flex h-12 items-center justify-between {selectedSyntax ===
'markdown'
? 'ml-auto w-[calc(100%-150px)] rounded-br'
: 'w-full rounded-b'} border border-neutral-700 bg-neutral-800 p-1 pr-2 pl-2 text-sm text-neutral-400 md:h-8"
>
<div class="flex flex-col md:flex-row md:gap-2">
<span>
{content.split('\n').length} line{content.split('\n').length !== 1 ? 's' : ''}
</span>
<span class="hidden text-neutral-600 md:block">•</span>
<span>{formatNumber(content.length)} char{content.length !== 1 ? 's' : ''}</span>
</div>
<div class="flex flex-col text-center md:flex-row md:gap-2">
<span
class="border-b border-neutral-600 md:border-0"
class:text-red-500={currentByteSize > (data.options?.maxPasteSize ?? 0)}
>
{formatBytes(currentByteSize)}
</span>
<span class="hidden md:block">/</span>
{formatBytes(data.options?.maxPasteSize ?? 0)}
</div>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 md:gap-2">
<Dropdown
options={syntaxOptions}
bind:value={selectedSyntax}
placeholder="Select syntax..."
searchable={true}
/>
<Dropdown
options={expiresOptions}
bind:value={expiresIn}
placeholder="Select expiration..."
/>
<Dropdown
options={visibilityOptions}
bind:value={selectedVisibility}
placeholder="Select visibility..."
/>
</div>
{#if selectedVisibility === 2}
<div class="flex w-full mb-2">
<input
type={passwordVisible ? 'text' : 'password'}
placeholder="Password for private paste"
class="w-[calc(100%-100px)] rounded-l border border-neutral-700 bg-neutral-800 p-2"
spellcheck="false"
autocomplete="off"
minlength="6"
bind:value={password}
/>
<button
type="button"
class="mr-1 ml-1 flex w-12.5 items-center justify-center border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
on:click={() => {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
password = Array.from(bytes, (b) => chars[b % chars.length]).join('');
}}
use:tooltip={'Generate Random Password'}
>
<Dices class="h-5 w-5" />
</button>
<button
type="button"
class="flex w-12.5 items-center justify-center rounded-r border border-neutral-700 bg-neutral-800 p-2 text-neutral-400 hover:bg-neutral-700 active:bg-neutral-600"
on:click={() => (passwordVisible = !passwordVisible)}
>
{#if passwordVisible}
<EyeClosed class="h-5 w-5" />
{:else}
<Eye class="h-5 w-5" />
{/if}
</button>
</div>
{/if}
{#if $user}
<label
class="mb-2 flex w-full items-center gap-2 rounded border border-neutral-700 bg-neutral-800 p-2"
>
<input
type="checkbox"
bind:checked={anonymousUpload}
class="h-4 w-4 rounded border-neutral-600 bg-neutral-700 text-neutral-500"
/>
<span>Upload anonymously</span>
</label>
{/if}
{#if data.options?.requiresVerification && data.auth?.cf_turnstile_site_key}
<div
class="mb-2 flex min-h-16.25 w-auto items-center justify-center rounded border border-neutral-700 bg-neutral-800 p-2 pb-1"
>
<div class="cf-turnstile" data-sitekey={data.auth.cf_turnstile_site_key}></div>
</div>
{/if}
<button
type="submit"
disabled={$user?.roles && $user.roles.includes(403)}
class="mb-2 w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
>Create Paste</button
>
{#if error}
<div
transition:fly={{ y: 40, duration: 300 }}
class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
>
{error}
</div>
{/if}
{#if $user?.roles && $user.roles.includes(403)}
<div
transition:fly={{ y: 40, duration: 300 }}
class="mb-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
>
You are banned from creating new pastes.
</div>
{/if}
</form>
</div>
</main>
@@ -0,0 +1,71 @@
import type { PageServerLoad } from './$types';
import type { Paste } from '$lib/types/paste';
import { getServerToken } from '$lib/utils/auth';
import { env } from '$env/dynamic/private';
import { error } from '@sveltejs/kit';
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
const apiKey =
env.NODE_ENV === 'development'
? 'cccdd42d9f2f648493e402f1da7c855ea798ad510e6bb9ea712dd7bed838e58'
: (env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '');
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent }) => {
const { id } = params;
const parentData = await parent().catch(() => null);
const token = getServerToken(cookies);
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, {
headers: {
Authorization: token ? `Bearer ${token}` : ''
}
});
if (pasteRes.status === 404) {
throw error(pasteRes.status, 'Paste not found.');
}
const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, {
method: 'POST',
headers: {
'X-Internal-API-Key': apiKey,
Authorization: token ? `Bearer ${token}` : ''
}
});
const pasteData = await pasteRes.json();
const paste = pasteData.paste as Paste;
if (viewed.status === 200) {
const viewJson = await viewed.json();
if (viewJson.success === true && viewJson.message !== 'View already recorded.') {
pasteData.views += 1;
}
} else {
console.error(
`Failed to increment view count for paste ${id}, status code ${viewed.status}: ${await viewed.text()}`
);
if (apiKey === '') {
console.error(
'The API key for internal requests is not set. Please configure it in the environment variables.'
);
}
}
const pasteContent = await fetch(`/api/paste/${id}/raw`);
const pasteOptions = await fetch('/api/paste/info');
const options = await pasteOptions.json();
const content = await pasteContent.text();
return {
paste,
content,
options,
authOptions:
parentData && typeof parentData === 'object' && parentData !== null && 'options' in parentData
? (parentData as { options?: unknown }).options
: null,
url: url.href
};
};
@@ -0,0 +1,929 @@
<script lang="ts">
import hljs from 'highlight.js';
import { onMount } from 'svelte';
import type { PageData } from './$types';
import {
File,
FileBox,
Eye,
EyeClosed,
EyeOff,
User,
CalendarDays,
CalendarOff,
Code,
Pencil,
PencilOff,
PencilLine,
Trash2,
Download,
Copy,
Check,
CalendarCog,
Flag,
ArrowUp
} from '@lucide/svelte/icons/index';
import {
formatBytes,
formatNumber,
extractDateFromUUIDv7,
dateToRelativeString,
tooltip,
isBinaryData
} from '$lib/utils/misc';
import { parseMarkdown } from '$lib/utils/markdown';
import { syntaxes } from '$lib/consts';
import { resolve } from '$app/paths';
import { decryptAES, encryptAES } from '$lib/utils/encryption';
import { fade } from 'svelte/transition';
import { getToken } from '$lib/utils/auth';
import { user } from '$lib/stores/user';
import Dropdown from '$lib/components/Dropdown.svelte';
import { openModal } from '$lib/stores/modal';
import type { Paste } from '$lib/types/paste';
export let data: PageData;
let reportSiteKey: string | null = null;
let editing = false;
let editContent: string | null = null;
let editMetadata: Paste | null = data.paste ? { ...data.paste } : null;
let editError = '';
let editLoading = false;
let isBinary = false;
let pasteContent = '';
let decryptedContent: string | null = null;
let decryptError = '';
let decryptStatus = '';
let contentRendered = false;
let downloadedPaste = false;
let copiedPaste = false;
let scrollY = 0;
let now = new Date();
$: isExpired =
data?.paste?.expiresAt && data.paste.expiresAt !== 0
? new Date(data.paste.expiresAt).getTime() <= now.getTime()
: false;
let interval: ReturnType<typeof setInterval> | null = null;
const syntaxOptions =
data.options?.syntaxes?.map((lang: string) => ({
value: lang,
label: syntaxes[lang]?.name ?? lang.charAt(0).toUpperCase() + lang.slice(1)
})) ?? [];
const expiresOptions = [
{ value: 0, label: 'Never Expire' },
{ value: 600000, label: 'Expire in 10 Minutes' },
{ value: 3600000, label: 'Expire in 1 Hour' },
{ value: 86400000, label: 'Expire in 1 Day' },
{ value: 604800000, label: 'Expire in 1 Week' },
{ value: 1209600000, label: 'Expire in 2 Weeks' },
{ value: 2592000000, label: 'Expire in 1 Month' },
{ value: 7776000000, label: 'Expire in 3 Months' },
{ value: 15552000000, label: 'Expire in 6 Months' },
{ value: 31536000000, label: 'Expire in 1 Year' },
{ value: 63072000000, label: 'Expire in 2 Years' },
{ value: 157680000000, label: 'Expire in 5 Years' },
{ value: 315360000000, label: 'Expire in 10 Years' }
];
const visibilityOptions =
data.options?.visibilities?.map((visibility: { value: number; displayName: string }) => ({
value: visibility.value,
label: visibility.displayName
})) ?? [];
const modalTitleMap = {
decrypt: 'Decrypt Paste',
encrypt: 'Encrypt Paste',
confirm: 'Are you sure you want to delete this paste?',
report: 'Report Paste'
};
onMount(() => {
interval = setInterval(() => {
now = new Date();
}, 1000);
return () => {
if (interval) clearInterval(interval);
};
});
function addLineNumbers(html: string): string {
const match = html.match(/<pre.*?>[\s\S]*?<code.*?>([\s\S]*?)<\/code><\/pre>/);
if (!match) return html;
const code = match[1];
const lines = code.split(/\n/);
const digits = String(lines.length).length;
const numbered = lines
.map(
(line, i) =>
`<div class="code-row"><span class="line-number" style="width:${digits}ch">${i + 1}</span><span class="code-line">${line}</span></div>`
)
.join('');
return html.replace(code, numbered);
}
async function renderCode(content: string | null = null) {
if (!data?.paste) return;
let code = content ?? decryptedContent ?? data.content ?? '';
const encoder = new TextEncoder();
const buffer = encoder.encode(code).buffer;
isBinary = isBinaryData(buffer);
if (isBinary) {
contentRendered = true;
decryptStatus = '';
return;
}
const lang = (data.paste.syntax ?? '').toLowerCase();
if (lang === 'markdown') {
pasteContent = await parseMarkdown(code);
contentRendered = true;
decryptStatus = '';
return;
}
let highlighted = '';
try {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else if (lang && hljs.getLanguage && hljs.getLanguage(lang)) {
highlighted = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
} else {
highlighted = hljs.highlightAuto(code).value;
}
} catch {
if (lang === 'plaintext') {
const escapeHtml = (s: string) =>
s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
highlighted = escapeHtml(code);
} else {
highlighted = hljs.highlightAuto(code).value;
}
}
const wrapped = `<pre><code class="hljs">${highlighted}</code></pre>`;
pasteContent = addLineNumbers(wrapped);
contentRendered = true;
decryptStatus = '';
}
async function updatePaste(content: string | null, metadata: Paste | null) {
editError = '';
editLoading = true;
try {
if (!data?.paste) {
editError = 'Paste data is missing.';
editLoading = false;
return;
}
const token = getToken();
if (!token) {
editError = 'Not authenticated.';
editLoading = false;
return;
}
if (
(content !== (decryptedContent ?? data.content) ||
metadata?.visibility === 2 ||
data.paste.visibility === 2) &&
content !== null
) {
let rawContent = content;
if (metadata?.visibility === 2 || data.paste.visibility === 2) {
const password = await promptUser('encrypt');
if (!password) {
editError = 'Password required for encryption.';
editLoading = false;
return;
}
const encrypted = await encryptAES(content, password);
content = encrypted;
}
const res = await fetch(`/api/paste/${data.paste.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: content
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
editError = err?.message || 'Failed to update paste content.';
editLoading = false;
return;
}
data.content = rawContent;
decryptedContent = rawContent;
await renderCode(rawContent);
}
if (
(metadata?.syntax !== data.paste.syntax ||
metadata?.expiresAt !== data.paste.expiresAt ||
metadata?.visibility !== data.paste.visibility ||
metadata?.title !== data.paste.title) &&
metadata !== null
) {
const res = await fetch(`/api/paste/${data.paste.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
syntax: metadata.syntax,
expiresAt: metadata.expiresAt === 0 ? 0 : Date.now() + (metadata.expiresAt ?? 0),
visibility: metadata.visibility,
title: metadata.title
})
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
editError = err?.message || 'Failed to update paste metadata.';
editLoading = false;
return;
}
const resJson = await res.json();
data.paste.syntax = resJson.paste.syntax ?? data.paste.syntax;
data.paste.expiresAt = resJson.paste.expiresAt ?? data.paste.expiresAt;
data.paste.visibility = resJson.paste.visibility ?? data.paste.visibility;
data.paste.title = resJson.paste.title ?? data.paste.title;
}
} catch {
editError = 'An error occurred while updating.';
} finally {
editLoading = false;
editing = false;
editContent = null;
}
}
async function promptUser(mode: 'decrypt' | 'encrypt' | 'confirm' | 'report' = 'decrypt') {
const title = modalTitleMap[mode];
if (mode === 'confirm') {
const ok = await openModal<boolean>({ mode, title, cancelValue: false });
return ok ? 'true' : '';
}
if (mode === 'report') {
await openModal({
mode,
title,
reportTarget: 'paste',
reportTargetId: data.paste?.id ?? null,
reportSiteKey,
cancelValue: ''
});
return '';
}
const value = await openModal<string>({ mode, title, error: decryptError, cancelValue: '' });
decryptError = '';
return value;
}
function handleMarkdownClick(event: MouseEvent) {
const target = event.target as HTMLElement;
const placeholder = target.closest('.media-placeholder') as HTMLElement;
if (placeholder) {
event.preventDefault();
event.stopPropagation();
if (target.classList.contains('load-media-btn')) {
const src = target.getAttribute('data-src');
const tag = target.getAttribute('data-tag');
if (!src || !tag) return;
const element = document.createElement(tag);
if (tag === 'img') {
element.setAttribute('alt', target.getAttribute('data-alt') || '');
element.setAttribute('style', 'max-width:100%; height:auto; border-radius:0.375rem;');
element.onload = () => {
const href = target.getAttribute('data-href');
if (href) {
const anchor = document.createElement('a');
anchor.setAttribute('href', href);
const targetAttr = target.getAttribute('data-target');
if (targetAttr) anchor.setAttribute('target', targetAttr);
anchor.appendChild(element);
placeholder.replaceWith(anchor);
} else {
placeholder.replaceWith(element);
}
};
element.onerror = () => {
target.textContent = 'Error loading image';
target.style.backgroundColor = '#7f1d1d';
target.style.opacity = '1';
};
} else {
if (tag === 'video' || tag === 'audio') {
element.setAttribute('controls', '');
element.setAttribute('style', 'max-width:100%;');
} else if (tag === 'iframe') {
element.setAttribute('style', 'width:100%; min-height:400px; border:none;');
}
const href = target.getAttribute('data-href');
if (href) {
const anchor = document.createElement('a');
anchor.setAttribute('href', href);
const targetAttr = target.getAttribute('data-target');
if (targetAttr) anchor.setAttribute('target', targetAttr);
anchor.appendChild(element);
placeholder.replaceWith(anchor);
} else {
placeholder.replaceWith(element);
}
}
['width', 'height', 'title'].forEach((attr) => {
const val = target.getAttribute(`data-${attr}`);
if (val) element.setAttribute(attr, val);
});
target.textContent = 'Loading...';
target.style.opacity = '0.5';
target.style.cursor = 'wait';
element.setAttribute('src', src);
}
}
}
onMount(async () => {
try {
if (data?.paste && data.paste.visibility === 2) {
contentRendered = false;
decryptStatus = 'Preparing decryption...';
const urlHash = window.location.hash.slice(1);
if (urlHash) {
const passwordFromUrl = atob(urlHash);
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, passwordFromUrl);
if (decryptedContent === null) {
decryptStatus = 'Waiting for password...';
const password = await promptUser('decrypt');
if (password) {
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, password);
if (decryptedContent === null) {
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
} else {
await renderCode();
history.replaceState(null, '', window.location.pathname + window.location.search);
}
} else {
decryptStatus = 'Decryption canceled.';
}
} else {
await renderCode();
}
return;
}
decryptStatus = 'Waiting for password...';
const password = await promptUser('decrypt');
if (password) {
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, password);
if (decryptedContent === null) {
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
} else {
await renderCode();
}
} else {
decryptStatus = 'Decryption canceled.';
}
} else {
decryptStatus = 'Rendering content...';
await renderCode();
}
} catch {
decryptStatus = 'Rendering content...';
await renderCode();
}
});
$: if (data?.paste && (data.paste.visibility !== 2 || decryptedContent !== null)) renderCode();
$: reportSiteKey =
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
?.cf_turnstile_site_key ?? null;
</script>
<svelte:window bind:scrollY />
<svelte:head>
<title
>{data.paste
? (data.paste.title || 'Untitled Paste') + ' - Sharpbin'
: 'Paste Not Found - Sharpbin'}</title
>
{#if data.paste}
<meta property="og:title" content={data.paste.title || 'Untitled Paste'} />
<meta
property="og:description"
content={`A ${data.paste.syntax} paste on Sharpbin created by ${
data.paste.author ? data.paste.author.username : 'Anonymous'
}, created on ${
extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'
} with ${data.paste.views} view${data.paste.views !== 1 ? 's' : ''}.`}
/>
<meta property="og:type" content="article" />
<meta property="og:url" content={data.url} />
<meta property="og:site_name" content="Sharpbin" />
<meta
property="og:article:published_time"
content={extractDateFromUUIDv7(data.paste.uuid)?.toISOString() ?? ''}
/>
{#if data.paste.editedAt}
<meta
property="og:article:modified_time"
content={new Date(data.paste.editedAt).toISOString()}
/>
{/if}
{#if data.paste.author}
<meta property="og:article:author" content={data.paste.author.username} />
{/if}
{/if}
</svelte:head>
<main
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4">
{#if data.paste}
<div class="mb-4 w-full text-center">
<h1
class="mx-auto max-w-[90%] min-w-0 truncate text-3xl leading-tight font-bold sm:text-4xl"
use:tooltip={data.paste.title && data.paste.title.length > 40 ? data.paste.title : ''}
>
{#if !editing}
{data.paste.title || 'Untitled Paste'}
{:else if editMetadata}
<input
type="text"
bind:value={editMetadata.title}
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
placeholder="Untitled Paste"
maxlength={data.options?.maxTitleLength ?? 500}
/>
{/if}
</h1>
<div class="flex items-center justify-center gap-2 text-sm text-neutral-400">
<User class="inline-block h-4 w-4 text-neutral-400" />
{#if data.paste.author}
<a
href={resolve(`/user/${data.paste.author.username}`)}
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
>{data.paste.author.username}</a
>
{:else}
<span class="text-neutral-400">Anonymous</span>
{/if}
</div>
</div>
<div class="mb-2">
<div class="flex flex-wrap items-center justify-center gap-4">
<div class="relative flex shrink-0 items-center">
<div
class="flex"
use:tooltip={data.paste.isCompressed
? `Compressed Size: ${formatBytes(data.paste.size)}`
: `This paste is not compressed.`}
>
<FileBox class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{formatBytes(data.paste.trueSize)}</span>
</div>
</div>
<div class="flex shrink-0 items-center">
<Eye class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400"
>{data.paste.views} view{data.paste.views !== 1 ? 's' : ''}</span
>
</div>
{#if data.paste.reportCount !== null && data.paste.reportCount > 0}
<div class="flex shrink-0 items-center">
<Flag class="mr-2 h-6 w-6 text-neutral-400" />
<a
class="text-neutral-400 hover:text-neutral-200 hover:underline"
href={resolve(`/reports?target=pastes&pasteId=${data.paste.id}`)}
>{data.paste.reportCount} report{data.paste.reportCount !== 1 ? 's' : ''}</a
>
</div>
{/if}
<div class="flex shrink-0 items-center">
<CalendarDays class="mr-2 h-6 w-6 text-neutral-400" />
<span
class="text-neutral-400"
use:tooltip={`Created on ${
extractDateFromUUIDv7(data.paste.uuid)?.toLocaleString() ?? 'Unknown Date'
} • ${dateToRelativeString(extractDateFromUUIDv7(data.paste.uuid) ?? new Date(), true, true, now, 3)}`}
>
{extractDateFromUUIDv7(data.paste.uuid)?.toLocaleDateString() ?? 'Unknown Date'}
</span>
</div>
{#if data.paste.editedAt}
<div class="flex shrink-0 items-center">
<CalendarCog class="mr-2 h-6 w-6 text-neutral-400" />
<span
class="text-neutral-400"
use:tooltip={`Edited on ${new Date(data.paste.editedAt).toLocaleString()} • ${dateToRelativeString(new Date(data.paste.editedAt), true, true, now, 3)}`}
>
{#if new Date(data.paste.editedAt).getTime() > new Date().getTime() - 86400000}
Edited {dateToRelativeString(new Date(data.paste.editedAt), false, false, now)} ago
{:else}
{new Date(data.paste.editedAt).toLocaleDateString()}
{/if}
</span>
</div>
{/if}
{#if data.paste.expiresAt !== 0 || editing}
<div class="flex shrink-0 items-center">
<CalendarOff class="mr-2 h-6 w-6 text-neutral-400" />
{#if !editing}
<span
class="text-neutral-400"
use:tooltip={`Expires on ${new Date(data.paste.expiresAt).toLocaleString()} • ${dateToRelativeString(new Date(data.paste.expiresAt), true, true, now, 3)}`}
>
{isExpired ? 'Expired' : 'Expires in'}
{dateToRelativeString(new Date(data.paste.expiresAt), false, false, now)}
{isExpired ? 'ago' : ''}
</span>
{:else if editMetadata}
<Dropdown
options={expiresOptions}
bind:value={editMetadata.expiresAt}
placeholder="Select expiration..."
variant="sm"
displayValue={(val) => {
const option = expiresOptions.find((opt) => opt.value === val);
return option ? option.label : 'Select expiration...';
}}
/>
{/if}
</div>
{/if}
<div class="flex shrink-0 items-center">
<Code class="mr-2 h-6 w-6 text-neutral-400" />
{#if !editing}
<span class="text-neutral-400">
{syntaxes[data.paste.syntax]?.name ??
data.paste.syntax.charAt(0).toUpperCase() + data.paste.syntax.slice(1)}
</span>
{:else if editMetadata && syntaxOptions}
<Dropdown
options={syntaxOptions}
bind:value={editMetadata.syntax}
placeholder="Select syntax..."
searchable={true}
variant="sm"
/>
{/if}
</div>
<div>
<div class="flex shrink-0 items-center">
{#if data.paste.visibility === 0}
<Eye class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{editing ? '' : 'Public'}</span>
{:else if data.paste.visibility === 1}
<EyeClosed class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{editing ? '' : 'Unlisted'}</span>
{:else if data.paste.visibility === 2}
<EyeOff class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">{editing ? '' : 'Private'}</span>
{/if}
{#if editing && editMetadata}
<Dropdown
options={visibilityOptions}
bind:value={editMetadata.visibility}
placeholder="Select visibility..."
variant="sm"
/>
{/if}
</div>
</div>
</div>
</div>
<div
class="sticky top-0 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row"
>
{#if !isBinary}
<div class="flex items-center gap-2 text-sm text-neutral-300">
<span class="font-medium text-neutral-100"
>{formatNumber((editContent ?? decryptedContent ?? data.content).length)}</span
>
<span class="text-neutral-400">chars</span>
<span class="text-neutral-600">•</span>
<span class="font-medium text-neutral-100"
>{formatNumber(
(editing ? (editContent ?? '') : (decryptedContent ?? data.content)).split('\n')
.length
)}</span
>
<span class="text-neutral-400"
>line{(editing ? (editContent ?? '') : (decryptedContent ?? data.content)).split('\n')
.length !== 1
? 's'
: ''}</span
>
</div>
{:else}
<div></div>
{/if}
<div class="flex shrink-0 flex-wrap items-center gap-2 sm:flex-nowrap">
{#if !isBinary}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => {
navigator.clipboard.writeText(decryptedContent ?? data.content);
copiedPaste = true;
setTimeout(() => (copiedPaste = false), 1000);
}}
>
<div class="relative mr-1 h-5 w-5">
{#if copiedPaste}
<span
transition:fade={{ duration: 200 }}
class="absolute inset-0 flex items-center justify-center"
><Check class="h-5 w-5 text-green-400" /></span
>
{:else}
<span
transition:fade={{ duration: 200 }}
class="absolute inset-0 flex items-center justify-center"
><Copy class="h-5 w-5 text-neutral-400" /></span
>
{/if}
</div>
<span class="text-neutral-300">Copy</span>
</button>
{/if}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => {
const blob = new Blob([decryptedContent ?? data.content], {
type: 'text/plain'
});
const syntax = syntaxes[data.paste?.syntax ?? 'plaintext'];
let extension = '.txt';
if (syntax && syntax.extension) {
if (data.paste?.title?.endsWith(syntax.extension)) {
extension = '';
} else {
extension = syntax.extension;
}
}
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = data.paste?.title
? data.paste.title.slice(0, 100) + extension
: `paste_${data.paste?.id}${extension}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
downloadedPaste = true;
setTimeout(() => (downloadedPaste = false), 1000);
}}
>
<div class="relative mr-1 h-5 w-5">
{#if downloadedPaste}
<span
transition:fade={{ duration: 200 }}
class="absolute inset-0 flex items-center justify-center"
><Check class="h-5 w-5 text-green-400" /></span
>
{:else}
<span
transition:fade={{ duration: 200 }}
class="absolute inset-0 flex items-center justify-center"
><Download class="h-5 w-5 text-neutral-400" /></span
>
{/if}
</div>
<span class="text-neutral-300">Download</span>
</button>
<a
href={resolve(`/raw/${data.paste.id}`)}
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
>
<File class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">View Raw</span>
</a>
{#if $user !== null && $user.uuid !== data.paste?.author?.uuid}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-amber-600/50"
on:click={() => {
promptUser('report');
}}
>
<Flag class="mr-1 h-5 w-5 text-amber-400" />
<span class="text-amber-300">Report</span>
</button>
{/if}
{#if $user && ($user.uuid === data.paste?.author?.uuid || $user.roles.some((r) => r === 1 || r === 255))}
{#if !editing}
{#if !isBinary}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => {
editContent = decryptedContent ?? data.content;
editError = '';
editing = true;
}}
>
<Pencil class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">Edit</span>
</button>
{/if}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-red-900"
on:click={() => {
promptUser('confirm').then(async (value) => {
if (value) {
const token = getToken();
if (!token) {
return;
}
const res = await fetch(`/api/paste/${data.paste?.id}`, {
method: 'DELETE',
headers: {
Authorization: `Bearer ${token}`
}
});
if (res.ok) {
window.location.href = resolve('/');
} else {
alert('Failed to delete paste.');
}
}
});
}}
>
<Trash2 class="mr-1 h-5 w-5 text-red-400" />
<span class="text-red-300">Delete</span>
</button>
{:else}
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={async () => {
if (editContent !== null || editMetadata !== null) {
await updatePaste(editContent, editMetadata);
}
}}
disabled={editLoading}
>
<PencilLine class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">{editLoading ? 'Saving...' : 'Save Edits'}</span>
</button>
<button
type="button"
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => {
editing = false;
editError = '';
}}
>
<PencilOff class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">Cancel Edit</span>
</button>
{/if}
{/if}
{#if scrollY > 400 && contentRendered && !editing}
<button
transition:fade={{ duration: 200 }}
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
on:click={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
aria-label="Scroll to top"
>
<ArrowUp class="mr-1 h-5 w-5 text-neutral-400" />
<span class="text-neutral-300">Scroll to top</span>
</button>
{/if}
</div>
</div>
{#if isBinary}
<div
class="flex h-16 w-full flex-col items-center justify-center rounded-b bg-neutral-800 p-4 text-neutral-400"
>
<p>We cannot display this paste because it is not text</p>
</div>
{:else if editing}
<textarea
class="mb-3 max-h-[40vh] min-h-10 w-full rounded-b bg-neutral-800 p-2 font-mono"
rows="14"
placeholder="Paste content"
bind:value={editContent}
></textarea>
{#if editError}
<div class="mb-3 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
{editError}
</div>
{/if}
{:else}
<div
class="flex h-20 w-full items-center justify-center rounded-b bg-neutral-800 text-sm text-neutral-400"
class:hidden={contentRendered && !editing}
>
<span class="monospace">{decryptStatus || 'Loading...'}</span>
</div>
<div
class={data.paste.syntax === 'markdown'
? 'markdown rounded-b-md bg-neutral-800 p-4'
: 'codeblock-with-lines overflow-x-auto overflow-y-auto'}
class:hidden={!contentRendered}
on:click={handleMarkdownClick}
role="presentation"
>
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html pasteContent}
</div>
{/if}
{:else}
<h1 class="mb-4 text-center text-4xl font-bold">Paste not found</h1>
<h2 class="mt-2 text-center text-xl">The paste you are looking for does not exist.</h2>
{/if}
</div>
<style>
.hljs {
background-color: var(--color-neutral-800) !important;
}
.codeblock-with-lines {
display: block;
width: 100%;
max-width: 100%;
overflow: hidden;
flex: 1 1 auto;
}
.codeblock-with-lines pre {
display: block;
position: relative;
margin: 0;
background: none;
border-bottom-left-radius: 0.25rem;
border-bottom-right-radius: 0.25rem;
background-color: var(--color-neutral-800) !important;
overflow-y: auto;
overflow-x: hidden;
box-sizing: border-box;
min-width: 0;
width: 100%;
}
.code-row {
display: flex;
align-items: flex-start;
min-width: 0;
padding: 0.1em 0;
border-radius: 0.15em;
}
.code-row:hover {
background-color: rgba(255, 255, 255, 0.05);
}
.line-number {
flex-shrink: 0;
text-align: right;
color: #888;
user-select: none;
margin-right: 1em;
font-variant-numeric: tabular-nums;
padding-right: 0.5em;
padding-left: 0.25em;
background: none;
}
.code-line {
display: block;
white-space: pre-wrap;
word-break: break-word;
overflow-wrap: anywhere;
padding-left: 0.25em;
min-width: 0;
}
</style>
</main>
@@ -0,0 +1,5 @@
import { json } from '@sveltejs/kit';
export const GET = () => {
return json({ status: 'ok' });
};
+121
View File
@@ -0,0 +1,121 @@
@import 'tailwindcss';
@import 'highlight.js/styles/github-dark.css';
* {
box-sizing: border-box;
}
body {
background-color: var(--color-neutral-950);
}
body,
h1,
h2,
h3,
p,
.sans-serif {
font-family: 'IBM Plex Sans', sans-serif;
}
pre,
code,
textarea,
option,
select,
.monospace {
font-family: 'Fira Code', monospace;
}
input[type='text'],
input[type='email'],
input[type='password'],
textarea,
select {
outline: none;
}
.markdown > :first-child {
margin-top: 0 !important;
padding-top: 0 !important;
}
.markdown h1 {
font-size: 2.25rem;
font-weight: 700;
margin-top: 1.5rem;
margin-bottom: 1rem;
border-bottom: 1px solid var(--color-neutral-700);
padding-bottom: 0.3rem;
}
.markdown h2 {
font-size: 1.875rem;
font-weight: 600;
margin-top: 1.25rem;
margin-bottom: 0.75rem;
border-bottom: 1px solid var(--color-neutral-700);
padding-bottom: 0.2rem;
}
.markdown h3 {
font-size: 1.5rem;
font-weight: 600;
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.markdown p {
margin-bottom: 1rem;
line-height: 1.6;
}
.markdown ul {
list-style-type: disc;
margin-left: 1.5rem;
margin-bottom: 1rem;
}
.markdown ol {
list-style-type: decimal;
margin-left: 1.5rem;
margin-bottom: 1rem;
}
.markdown li {
margin-bottom: 0.25rem;
}
.markdown a {
color: #3b82f6;
text-decoration: underline;
}
.markdown .load-media-btn:hover {
background-color: #525252 !important;
}
.markdown pre {
background-color: #1a1a1a;
padding: 1rem;
border-radius: 0.375rem;
margin-bottom: 1rem;
overflow-x: auto;
}
.markdown code {
background-color: #1a1a1a;
padding: 0.2rem 0.4rem;
border-radius: 0.25rem;
font-family: monospace;
}
.markdown blockquote {
border-left: 4px solid #404040;
padding-left: 1rem;
color: #a3a3a3;
font-style: italic;
margin-bottom: 1rem;
}
.markdown table {
width: 100%;
border-collapse: collapse;
margin-bottom: 1rem;
}
.markdown th,
.markdown td {
border: 1px solid #404040;
padding: 0.5rem;
text-align: left;
}
.markdown th {
background-color: #2a2a2a;
}
@@ -0,0 +1,158 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
import { extractError } from '$lib/utils/misc';
import { onMount } from 'svelte';
import type { PageData } from './$types';
let username = '';
let password = '';
let error = '';
let totpEnabled = false;
let totpCode = '';
export let data: PageData;
onMount(() => {
const render = () => {
if (window.turnstile && data.options?.cf_turnstile_site_key) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.options.cf_turnstile_site_key,
theme: 'dark'
});
}
};
if (window.turnstile) {
render();
} else {
window.addEventListener('turnstile:loaded', render, { once: true });
}
return () => {
window.removeEventListener('turnstile:loaded', render);
};
});
async function login() {
const body: { username: string; password: string; token?: string; totpcode?: string } = {
username,
password
};
if (data.options?.cf_turnstile_site_key && window.turnstile) {
const token = window.turnstile.getResponse();
if (token) {
body.token = token;
}
}
if (totpEnabled && totpCode) {
body.totpcode = totpCode;
}
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (res.ok) {
const data = await res.json();
if (data.token && data.refreshToken) {
setTokens(data.token, data.refreshToken);
startTokenRefreshInterval();
}
const urlParams = new URLSearchParams(window.location.search);
const returnUrl = urlParams.get('return');
if (returnUrl) {
window.location.href = returnUrl;
return;
}
window.location.href = '/';
} else {
const resData = await res.json();
if (window.turnstile) {
window.turnstile.reset();
}
error = extractError(resData) || 'Login failed. Please try again.';
if (error === 'TOTP code is required.') {
totpEnabled = true;
}
}
}
</script>
<svelte:head>
<title>Login - Sharpbin</title>
<meta
name="description"
content="Login to your Sharpbin account to manage your pastes and settings."
/>
</svelte:head>
<main
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Login</h1>
<form on:submit|preventDefault={login} class="space-y-4">
<input
type="text"
placeholder="Username"
bind:value={username}
autocomplete="username"
required
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
<input
type="password"
placeholder="Password"
bind:value={password}
required
autocomplete="current-password"
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
{#if totpEnabled}
<input
type="text"
placeholder="TOTP Code"
bind:value={totpCode}
maxlength="6"
inputmode="numeric"
pattern="[0-9]*"
required
on:input={(e) => {
if (e.target instanceof HTMLInputElement) {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
totpCode = e.target.value;
}
}}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
{/if}
{#if data.options?.cf_turnstile_site_key}
<div class="flex w-full justify-center">
<div class="cf-turnstile"></div>
</div>
{/if}
<button
type="submit"
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900"
>
Login
</button>
{#if error}
<div
class="rounded border border-red-900 bg-red-950 p-2 text-sm whitespace-pre-line text-red-200"
>
{error}
</div>
{/if}
</form>
<p class="mt-4 text-center text-sm text-neutral-400">
Don't have an account? <a
href={resolve('/register')}
class="text-neutral-200 transition-colors duration-200 hover:text-white">Register</a
>
</p>
</div>
</main>
@@ -0,0 +1,19 @@
import type { RequestHandler } from '@sveltejs/kit';
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
export const GET: RequestHandler = async ({ params }) => {
const { id } = params;
const res = await fetch(`${apiUrl}/api/paste/${id}/raw`);
if (res.status === 404) {
return new Response('Paste not found', { status: 404 });
}
const content = await res.text();
return new Response(content, {
headers: {
'Content-Type': 'text/plain; charset=utf-8'
}
});
};
@@ -0,0 +1,19 @@
import type { PageServerLoad } from './$types';
import type { Paste } from '$lib/types/paste';
import { extractError } from '$lib/utils/misc';
import { error } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ fetch }) => {
try {
const res = await fetch('/api/paste/recent');
if (!res.ok) {
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
throw error(res.status, errorMsg);
}
const recentPastes: Paste[] = await res.json();
return { recentPastes };
} catch (error) {
console.error(error);
return { recentPastes: [] };
}
};
@@ -0,0 +1,39 @@
<script lang="ts">
import type { PageData } from './$types';
import { onMount } from 'svelte';
import Paste from '$lib/components/Paste.svelte';
export let data: PageData;
let now = new Date();
onMount(() => {
const interval = setInterval(() => {
now = new Date();
}, 1000);
return () => clearInterval(interval);
});
</script>
<svelte:head>
<title>Recent Pastes - Sharpbin</title>
<meta name="description" content="Browse the most recent pastes shared on Sharpbin." />
</svelte:head>
<main
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
{#if data.recentPastes.length === 0}
<p class="text-lg">No recent pastes available.</p>
{:else}
<h1 class="mb-4 text-3xl font-bold">Recent Pastes</h1>
<div class="grid grid-cols-1 gap-4">
{#each data.recentPastes as paste (paste.uuid)}
<Paste {paste} {now} />
{/each}
</div>
{/if}
</div>
</main>
@@ -0,0 +1,292 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { setTokens, startTokenRefreshInterval } from '$lib/utils/auth';
import { extractError } from '$lib/utils/misc';
import { Check, X } from '@lucide/svelte';
import { slide, fade } from 'svelte/transition';
import { resolve } from '$app/paths';
import { onMount } from 'svelte';
import type { PageData } from './$types';
let username = '';
let password = '';
let confirmPassword = '';
let email = '';
let displayName = '';
let error = '';
let passwordFocused = false;
let passwordChecks = {
length: false,
upper: false,
lower: false,
number: false
};
let passwordValid = false;
let loading = false;
export let data: PageData;
onMount(() => {
const render = () => {
if (
window.turnstile &&
data.options?.cf_turnstile_site_key &&
data.options?.registration_enabled
) {
window.turnstile.render('.cf-turnstile', {
sitekey: data.options.cf_turnstile_site_key,
theme: 'dark'
});
}
};
if (window.turnstile) {
render();
} else {
window.addEventListener('turnstile:loaded', render, { once: true });
}
return () => {
window.removeEventListener('turnstile:loaded', render);
};
});
function validatePassword(pw: string) {
passwordChecks.length = pw.length >= 8;
passwordChecks.upper = /[A-Z]/.test(pw);
passwordChecks.lower = /[a-z]/.test(pw);
passwordChecks.number = /[0-9]/.test(pw);
passwordValid =
passwordChecks.length &&
passwordChecks.upper &&
passwordChecks.lower &&
passwordChecks.number;
}
$: validatePassword(password);
async function register() {
if (!passwordValid || password !== confirmPassword) return;
loading = true;
error = '';
const body: Record<string, unknown> = { username, password, email, displayName };
if (data.options?.cf_turnstile_site_key && window.turnstile) {
const token = window.turnstile.getResponse();
if (token) body.token = token;
}
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (res.ok) {
const data = await res.json();
if (data.token && data.refreshToken) {
setTokens(data.token, data.refreshToken);
startTokenRefreshInterval();
goto(resolve('/'));
} else {
const urlParams = new URLSearchParams(window.location.search);
const returnUrl = urlParams.get('return');
if (returnUrl) {
goto(resolve(`/login?return=${encodeURIComponent(returnUrl)}`));
} else {
goto(resolve('/login'));
}
}
} else {
const resData = await res.json();
if (window.turnstile) {
window.turnstile.reset();
}
if (resData.errors) {
const messages = Object.values(resData.errors).flat();
error = messages.join('\n');
} else {
error = extractError(resData) || 'Registration failed. Please try again.';
if (error === 'Verification failed.') {
if (window.turnstile) {
window.turnstile.reset();
}
}
}
}
loading = false;
}
</script>
<svelte:head>
<title>Register - Sharpbin</title>
<meta
name="description"
content="Create a new Sharpbin account to manage your pastes and settings."
/>
</svelte:head>
<main
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="w-full max-w-md rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Register</h1>
{#if data.options?.registration_enabled === false}
<div
class="mb-4 rounded border border-yellow-600/80 bg-yellow-600/40 p-2 text-sm text-yellow-200"
>
Registration is currently disabled.
</div>
{/if}
<form on:submit|preventDefault={register} class="space-y-4">
<input
type="text"
placeholder="Username"
bind:value={username}
autocomplete="username"
required
disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
<div>
<input
type="email"
placeholder="Email (optional)"
bind:value={email}
autocomplete="email"
disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
</div>
<div>
<input
type="text"
placeholder="Display Name (optional)"
bind:value={displayName}
autocomplete="name"
disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
</div>
<input
type="password"
placeholder="Password"
bind:value={password}
required
on:focus={() => (passwordFocused = true)}
on:blur={() => (passwordFocused = false)}
autocomplete="new-password"
disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
{#if passwordFocused}
<ul
transition:slide
class="space-y-2 rounded border border-neutral-700 bg-neutral-800 p-3 text-sm"
>
<li
class="flex items-center gap-2 {passwordChecks.length
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.length}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least 8 characters
</li>
<li
class="flex items-center gap-2 {passwordChecks.upper
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.upper}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least one uppercase letter
</li>
<li
class="flex items-center gap-2 {passwordChecks.lower
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.lower}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least one lowercase letter
</li>
<li
class="flex items-center gap-2 {passwordChecks.number
? 'text-green-400'
: 'text-red-400'}"
>
{#if passwordChecks.number}
<Check class="h-4 w-4" />
{:else}
<X class="h-4 w-4" />
{/if}
At least one number
</li>
</ul>
{/if}
<input
type="password"
placeholder="Confirm Password"
bind:value={confirmPassword}
required
autocomplete="new-password"
disabled={loading || !data.options?.registration_enabled}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
{#if confirmPassword && password !== confirmPassword}
<div
transition:fade
class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
>
Passwords do not match.
</div>
{/if}
{#if data.options?.cf_turnstile_site_key && data.options?.registration_enabled}
<div class="flex w-full justify-center">
<div class="cf-turnstile"></div>
</div>
{/if}
<button
type="submit"
disabled={!passwordValid ||
password !== confirmPassword ||
loading ||
!data.options?.registration_enabled}
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900"
>
{loading ? 'Registering...' : 'Register'}
</button>
{#if error}
<div class="rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
{error}
</div>
{/if}
</form>
<p class="mt-4 text-center text-sm text-neutral-400">
Already have an account? <a
href={resolve('/login')}
class="text-neutral-200 transition-colors duration-200 hover:text-white">Login</a
>
</p>
</div>
</main>
<style>
*:disabled {
cursor: not-allowed;
background-color: var(--color-neutral-800);
color: var(--color-neutral-600) !important;
border: none;
}
*:disabled::placeholder {
color: var(--color-neutral-600) !important;
}
</style>
@@ -0,0 +1,43 @@
import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import { getServerToken } from '$lib/utils/auth';
import type { Report } from '$lib/types/report';
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
function decodeJwtRoles(token?: string | null): number[] {
try {
if (!token) return [];
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString());
const roles = payload?.role;
if (Array.isArray(roles)) {
return roles.map((r: string) => parseInt(r, 10)).filter((r: number) => !isNaN(r));
}
return [];
} catch {
return [];
}
}
export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
const token = getServerToken(cookies);
if (!token) throw error(401, 'Login required');
const roles = decodeJwtRoles(token);
const canEdit = roles.includes(1) || roles.includes(255);
const res = await fetch(`${API_URL}/api/report/${params.reportId}`, {
headers: { Authorization: `Bearer ${token}` }
});
if (!res.ok) {
const { message } = await res.json().catch(() => ({}));
throw error(res.status, message ?? 'Request failed');
}
const report = (await res.json()) as Report;
const optionsRes = await fetch(`${API_URL}/api/report/options`);
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
return { report, url: url.href, canEdit, options };
};
@@ -0,0 +1,165 @@
<script lang="ts">
import type { PageData } from './$types';
import { resolve } from '$app/paths';
import { reportStatusLabels, reportTargetLabels, reportTypeLabels } from '$lib/types/report';
import { tooltip } from '$lib/utils/misc';
import { getToken } from '$lib/utils/auth';
export let data: PageData;
const report = data.report;
let saving = false;
let saveError = '';
const statusOptions = data.options?.statuses ?? [];
const typeOptions = data.options?.types ?? [];
let statusValue = reportStatusLabels[report.status] ?? '';
let typeValue = reportTypeLabels[report.type] ?? '';
async function updateReport() {
saveError = '';
saving = true;
const token = getToken();
const res = await fetch(`/api/report/${report.reportID}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {})
},
body: JSON.stringify({ status: statusValue, type: typeValue })
});
if (!res.ok) {
const { message } = await res.json().catch(() => ({}));
saveError = message ?? 'Failed to update report.';
saving = false;
return;
}
const updated = await res.json();
report.status = updated.status ?? report.status;
report.type = updated.type ?? report.type;
report.updatedAt = updated.updatedAt ?? report.updatedAt;
report.description = updated.description ?? report.description;
saving = false;
}
</script>
<svelte:head>
<title>Report #{report.reportID} - Sharpbin</title>
</svelte:head>
<main
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
>
<div class="mx-auto w-[95%] max-w-4xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
<h1 class="mb-6 text-center text-3xl font-bold">Report #{report.reportID}</h1>
<div class="space-y-4">
<div class="flex flex-wrap items-center gap-3 text-neutral-300">
<span class="rounded bg-neutral-800 px-3 py-1">
{reportTypeLabels[report.type] ?? 'Other'}
</span>
<span class="rounded bg-neutral-800 px-3 py-1">
{reportStatusLabels[report.status] ?? 'Open'}
</span>
<span class="rounded bg-neutral-800 px-3 py-1">
{reportTargetLabels[report.targetType] ?? 'Unknown'}
</span>
</div>
<div class="space-y-2 text-sm text-neutral-400">
<div>
Reporter:
{#if report.reporterUsername}
<a
class="text-neutral-200 hover:text-white hover:underline"
href={resolve(`/user/${report.reporterUsername}`)}
use:tooltip={report.reporterUUID}
>
{report.reporterDisplayName || report.reporterUsername}
</a>
{:else}
<span>{report.reporterUUID}</span>
{/if}
</div>
{#if report.pasteId}
<div>
Target Paste:
<a
class="text-neutral-200 hover:text-white hover:underline"
href={resolve(`/${report.pasteId}`)}
>
{report.pasteTitle !== '' ? report.pasteTitle : report.pasteId}
</a>
</div>
{/if}
{#if report.userUUID}
<div>
Target User:
{#if report.targetUsername}
<a
class="text-neutral-200 hover:text-white hover:underline"
href={resolve(`/user/${report.targetUsername}`)}
use:tooltip={report.userUUID}
>
{report.targetDisplayName || report.targetUsername}
</a>
{:else}
<span>{report.userUUID}</span>
{/if}
</div>
{/if}
<div>Created: {new Date(report.createdAt * 1000).toLocaleString()}</div>
{#if report.updatedAt}
<div>Updated: {new Date(report.updatedAt * 1000).toLocaleString()}</div>
{/if}
</div>
{#if data.canEdit}
<div class="mt-4 space-y-3">
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<div class="flex flex-col gap-2">
<label class="text-sm text-neutral-400" for="report-update-type">Type</label>
<select
id="report-update-type"
class="rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={typeValue}
>
{#each typeOptions as t (t)}
<option value={t}>{t}</option>
{/each}
</select>
</div>
<div class="flex flex-col gap-2">
<label class="text-sm text-neutral-400" for="report-update-status">Status</label>
<select
id="report-update-status"
class="rounded border border-neutral-700 bg-neutral-800 p-2"
bind:value={statusValue}
>
{#each statusOptions as s (s)}
<option value={s}>{s}</option>
{/each}
</select>
</div>
</div>
<div class="flex items-center gap-3">
<button
class="rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600 disabled:opacity-60"
on:click={updateReport}
disabled={saving}
>
{saving ? 'Saving...' : 'Update Report'}
</button>
{#if saveError}
<span class="text-sm text-red-300">{saveError}</span>
{/if}
</div>
</div>
{/if}
{#if report.description}
<div class="rounded border border-neutral-700 bg-neutral-800 p-4 text-neutral-200">
{report.description}
</div>
{/if}
</div>
</div>
</main>

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