mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-06 02:48:43 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec4bbad1d7
|
||
|
|
3b53cfbddf
|
||
|
|
6d99a06c17
|
||
|
|
094c8e5e08
|
||
|
|
801426f93e
|
||
|
|
abacbf14af
|
||
|
|
62d80597dc
|
||
|
|
ccb5db14d2 | ||
|
|
da423eb1c8 | ||
|
|
08c4bf4367 | ||
|
|
0aa9176835 | ||
|
|
e8eb677ba7
|
||
|
|
322af06832
|
||
|
|
d78baae19e
|
||
|
|
e102c91d79
|
||
|
|
6a59b72d08
|
||
|
|
27093acadf
|
||
|
|
4e02399d9f
|
||
|
|
b7ce54d5a0
|
||
|
|
8eede40000
|
||
|
|
c98aca92b6
|
||
|
|
5296efa9db
|
||
|
|
9486840f05
|
||
|
|
6047d48da2
|
||
|
|
73f73d88dc
|
||
|
|
1496a02b76
|
||
|
|
059d32e42c
|
||
|
|
797747f718
|
||
|
|
f70328c93d
|
||
|
|
8b8c0bbf7a
|
||
|
|
6eb4f699b5
|
||
|
|
e0c9f1bbc1
|
||
|
|
bf1c647d10
|
||
|
|
873b1778ee
|
||
|
|
44d7ae8cd3
|
||
|
|
0564d55396
|
||
|
|
5f11ee4350
|
||
|
|
4c071fcc39
|
||
|
|
e7cd3723a7
|
||
|
|
d4e2cf25d3
|
||
|
|
fbec598ee2
|
||
|
|
cb7f94fd5c
|
||
|
|
0c9a747935
|
||
|
|
38c8af1c57
|
||
|
|
ec0635dd3b
|
||
|
|
49e73cde9c
|
||
|
|
12f716eb83
|
||
|
|
c986a73ef4
|
||
|
|
b9cff6a0bd
|
||
|
|
2302ebdffc
|
||
|
|
2b66cb2762
|
||
|
|
32c46b8c2b
|
||
|
|
e329e1f8ea
|
||
|
|
2c794b833a
|
||
|
|
5420d94595
|
||
|
|
95da3f9543
|
||
|
|
d21265f443
|
||
|
|
7dbbcb65ac | ||
|
|
980cbfa989 | ||
|
|
528456c168
|
||
|
|
b54c12ba10
|
||
|
|
eef98030d6
|
||
|
|
00233280d4
|
||
|
|
4e8d71b8c6 | ||
|
|
73a1edcc85 | ||
|
|
f1aef1cc3c | ||
|
|
7d87e2be13 | ||
|
|
51c6ea5f98 | ||
|
|
3c346353aa | ||
|
|
ac2f0a3dcf
|
||
|
|
75ecfbe7e7
|
||
|
|
2c3f8c95ac
|
||
|
|
f64584602e
|
||
|
|
5eebea314e
|
||
|
|
f786117cad
|
||
|
|
3ba63f692c
|
+3
-1
@@ -323,4 +323,6 @@ FodyWeavers.xsd
|
||||
|
||||
Data
|
||||
!SharpbinV3.Server/Data
|
||||
.idea
|
||||
.idea
|
||||
|
||||
**/.env
|
||||
@@ -1,3 +1,55 @@
|
||||
## [3.0.5](https://github.com/whoswhip/Sharpbin/compare/v3.0.4...v3.0.5) (2026-03-31)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add back CSV syntax support in consts and appsettings ([3ba63f6](https://github.com/whoswhip/Sharpbin/commit/3ba63f692c25e016f226fccc9120a3649c7150d9))
|
||||
* **auth:** replace HMAC token generation with SHA256 for email verification ([49e73cd](https://github.com/whoswhip/Sharpbin/commit/49e73cde9c856bee9f36e2cedb9742bd6a3e9942))
|
||||
* **backend:paste:** check expiration before returning paste data or recording views; prevent paste authors from adding views to their own paste ([ec0635d](https://github.com/whoswhip/Sharpbin/commit/ec0635dd3b6401679e1a4a923302de5dcdbecda8))
|
||||
* **cache:** ensure pasteExpiresAt is valid before cache deletion ([c98aca9](https://github.com/whoswhip/Sharpbin/commit/c98aca92b68a761056b5610d893c7be17da06d96))
|
||||
* **controller:** only return paste not found if null or expired ([f70328c](https://github.com/whoswhip/Sharpbin/commit/f70328c93d8b008f6015ec239cc984bbcc0b57e3))
|
||||
* **controller:** update paste expiration check to handle zero expiration case ([797747f](https://github.com/whoswhip/Sharpbin/commit/797747f718913f1b52d0d17caf7fc1f720bde59b))
|
||||
* correct expiration time for 'Expire in 5 Minutes' option ([f786117](https://github.com/whoswhip/Sharpbin/commit/f786117cad468d0c0cacae10bbfe82c8d647353b))
|
||||
* **docker-compose:** add back VITE_API_URL environment variable to frontend ([d4e2cf2](https://github.com/whoswhip/Sharpbin/commit/d4e2cf25d3c4eb4c414b59ce6b5655cd9a3ba8a7))
|
||||
* **docker-compose:** add env_file entries for backend and frontend services ([c986a73](https://github.com/whoswhip/Sharpbin/commit/c986a73ef44df90c2e47f3a2dc60900b2271d230))
|
||||
* **docker:** correct environment variable syntax for backend service ([e0c9f1b](https://github.com/whoswhip/Sharpbin/commit/e0c9f1bbc1fc150d139043bbfb84ff16a86b20be))
|
||||
* **dotenv:** skip empty lines and comments when loading environment variables ([2302ebd](https://github.com/whoswhip/Sharpbin/commit/2302ebdffc74dbd5023803919730ac5bb8243abf))
|
||||
* **email:** ensure all email settings are validated before sending; allow nullable From property ([b9cff6a](https://github.com/whoswhip/Sharpbin/commit/b9cff6a0bd5899e3aaa3775981ae0782d621fa97))
|
||||
* **email:** validate settings before sending; use hmac for tokens ([2b66cb2](https://github.com/whoswhip/Sharpbin/commit/2b66cb27629726480c00ffae4775810a35ee4fcf))
|
||||
* **encryption:** improve encryption security: adjust salt size and memory parameters for AES encryption ([b54c12b](https://github.com/whoswhip/Sharpbin/commit/b54c12ba10c3f6607a6345caaa4d528e90f1ce0a))
|
||||
* forward headers during requests where needed ([3b53cfb](https://github.com/whoswhip/Sharpbin/commit/3b53cfbddf0397c8b040641d784dce8b070c9753))
|
||||
* forward the request header when viewing on the /[id] server route ([62d8059](https://github.com/whoswhip/Sharpbin/commit/62d80597dc51428fc3be810fb268b4bfd4cd6098))
|
||||
* **frontend:paste:** increase paste views only if api returns 'Paste view recorded.' ([4c071fc](https://github.com/whoswhip/Sharpbin/commit/4c071fcc3965f1164d95d0c2dfd729059ee7cfad))
|
||||
* **frontend:user:** resolve lint error ([2c3f8c9](https://github.com/whoswhip/Sharpbin/commit/2c3f8c95ac55a891caeaebacadad808bfc7180d2))
|
||||
* **frontend:** use darker version of tooltip on generate random password ([eef9803](https://github.com/whoswhip/Sharpbin/commit/eef98030d6daf6c223d5e12e7ad024211e411d13))
|
||||
* improve header handling and error checking in paste loading ([6d99a06](https://github.com/whoswhip/Sharpbin/commit/6d99a06c17b7365c26d4dd48405f2963f5826f1f))
|
||||
* improve icon consistency ([e102c91](https://github.com/whoswhip/Sharpbin/commit/e102c91d79618b87b71653e23df7a6511a6c09ba))
|
||||
* make syntax extension comparison case insensitive and remove '.' ([801426f](https://github.com/whoswhip/Sharpbin/commit/801426f93e08fdce0d548f8c539c5f7dc06fea93))
|
||||
* remove rate limiting on {id}/raw and {id} ([094c8e5](https://github.com/whoswhip/Sharpbin/commit/094c8e5e08dcbef33d4f0e4d965ac467d8d4d6d4))
|
||||
* **routes:** /raw/{pasteId} no longer returns a body on error ([38c8af1](https://github.com/whoswhip/Sharpbin/commit/38c8af1c5713defe06077842bacbf69ef47eff00))
|
||||
* set default value for AuthSettings__First_User_Admin and pass GIT_COMMIT_HASH as build argument ([f645846](https://github.com/whoswhip/Sharpbin/commit/f64584602eb7b29a7854923420c25811a2a64946))
|
||||
* switch to better sqlite-3 instead of experimental node api ([5296efa](https://github.com/whoswhip/Sharpbin/commit/5296efa9dbf4bfd6f6613cdee4806d170de9ba6d))
|
||||
* **types:** add missing createdAt field to Paste interface ([6047d48](https://github.com/whoswhip/Sharpbin/commit/6047d48da2d5920e9e79b4e12b48a142ec9e2646))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* /user/{uuid} redirects to /user/{username} based off uuid ([059d32e](https://github.com/whoswhip/Sharpbin/commit/059d32e42c93fa0113e0bf253ab8bb432b3fa0b2))
|
||||
* add GIT_COMMIT_HASH support for versioning in Dockerfile and footer ([5eebea3](https://github.com/whoswhip/Sharpbin/commit/5eebea314e6c475e012d0378aa4d6147485210f4))
|
||||
* add HatGlasses icon for anonymous users in Paste component ([b7ce54d](https://github.com/whoswhip/Sharpbin/commit/b7ce54d5a0e00ee27e53e492b71a973d63e94bef))
|
||||
* **auth:** add JWT user parsing from token ([d78baae](https://github.com/whoswhip/Sharpbin/commit/d78baae19e2508cac2205fcc9b3b09ee600d95fe))
|
||||
* **auth:** improve token refreshing ([75ecfbe](https://github.com/whoswhip/Sharpbin/commit/75ecfbe7e7724addf71f2a9d1de41f28132602a1))
|
||||
* **backend:** add DotEnv class for loading environment variables from .env file ([0023328](https://github.com/whoswhip/Sharpbin/commit/00233280d45a2fa87c4c01b9086620606be210e1))
|
||||
* email verification via smtp ([95da3f9](https://github.com/whoswhip/Sharpbin/commit/95da3f95435709692de347272fae01dff13ddf7c))
|
||||
* **email:** add email verification html templates ([0564d55](https://github.com/whoswhip/Sharpbin/commit/0564d55396da1f811aa7fa624a8f42392aeb49b9))
|
||||
* **email:** implement email queue management ([5420d94](https://github.com/whoswhip/Sharpbin/commit/5420d94595bba2731409677631551b7bc265ad3c))
|
||||
* guest param in user page ([8eede40](https://github.com/whoswhip/Sharpbin/commit/8eede40000f6a541188c95370073e76113d152d8))
|
||||
* **markdown:** add dont warn again feature ([e7cd372](https://github.com/whoswhip/Sharpbin/commit/e7cd3723a7c60e3f058de990e1b7ac2efb414683))
|
||||
* open graph embed image generation ([9486840](https://github.com/whoswhip/Sharpbin/commit/9486840f05fadac604f1ccd3a838f3f0d1a71f51))
|
||||
* **roles, visibility:** refactor user roles to use flags and introduce visibility enum ([44d7ae8](https://github.com/whoswhip/Sharpbin/commit/44d7ae8cd3ead498f7975a20b5269ee311553d23))
|
||||
|
||||
|
||||
|
||||
## [3.0.4](https://github.com/whoswhip/Sharpbin/compare/v3.0.3...v3.0.4) (2026-02-14)
|
||||
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ You can configure Sharpbin using environment variables or `appsettings.json`. Wh
|
||||
|
||||
#### Backend (SharpbinV3.Server)
|
||||
|
||||
- `Domain`: The domain your instance of Sharpbin will be hosted at (e.g., example.com)
|
||||
- `Https`: Whether or not your instance is behind https. Used when sendings emails.
|
||||
- `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.
|
||||
@@ -64,7 +66,7 @@ You can configure Sharpbin using environment variables or `appsettings.json`. Wh
|
||||
#### 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`)
|
||||
- `VITE_ALLOWED_HOSTS`: A comma separated list of allowed hosts (e.g., `localhost,sharpbin.cc`)
|
||||
- `VIEW_INTERNAL_API_KEY`: Enforces views to be counted/recorded only by the frontend, if set it needs to be the same for both backend and frontend.
|
||||
|
||||
The frontend will be accessible at http://localhost:5173.
|
||||
|
||||
@@ -7,6 +7,7 @@ node_modules
|
||||
.wrangler
|
||||
/.svelte-kit
|
||||
/build
|
||||
.cache
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM node:20-alpine as build
|
||||
ARG GIT_COMMIT_HASH
|
||||
ENV GIT_COMMIT_HASH=${GIT_COMMIT_HASH}
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
Generated
+1572
-133
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "sharpbinv3.client",
|
||||
"private": true,
|
||||
"version": "3.0.4",
|
||||
"version": "3.0.5",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
@@ -21,6 +21,7 @@
|
||||
"@sveltejs/kit": "^2.50.0",
|
||||
"@sveltejs/vite-plugin-svelte": "^6.2.1",
|
||||
"@tailwindcss/vite": "^4.1.17",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/jsdom": "^27.0.0",
|
||||
"@types/node": "^22",
|
||||
"@types/papaparse": "^5.5.2",
|
||||
@@ -34,7 +35,7 @@
|
||||
"prettier": "^3.7.4",
|
||||
"prettier-plugin-svelte": "^3.4.0",
|
||||
"prettier-plugin-tailwindcss": "^0.7.2",
|
||||
"svelte": "^5.48.3",
|
||||
"svelte": "^5.53.5",
|
||||
"svelte-check": "^4.3.4",
|
||||
"tailwind-scrollbar": "^4.0.2",
|
||||
"tailwindcss": "^4.1.17",
|
||||
@@ -43,14 +44,21 @@
|
||||
"vite": "^7.2.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.2.8",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@lucide/svelte": "^0.562.0",
|
||||
"@resvg/resvg-js": "^2.6.2",
|
||||
"@sveltejs/adapter-node": "^5.4.0",
|
||||
"dompurify": "^3.3.1",
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"dompurify": "^3.3.2",
|
||||
"hash-wasm": "^4.12.0",
|
||||
"highlight.js": "^11.8.0",
|
||||
"jsdom": "^27.4.0",
|
||||
"marked": "^17.0.1",
|
||||
"papaparse": "^5.5.3",
|
||||
"qrcode": "^1.5.4"
|
||||
"qrcode": "^1.5.4",
|
||||
"satori": "^0.26.0",
|
||||
"satori-html": "^0.3.2",
|
||||
"sharp": "^0.34.5"
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+1
@@ -27,6 +27,7 @@ declare global {
|
||||
| undefined;
|
||||
var turnstileLoaded: (() => void) | undefined;
|
||||
declare const __APP_VERSION__: string;
|
||||
declare const COMMIT_HASH: string;
|
||||
}
|
||||
|
||||
export {};
|
||||
|
||||
@@ -19,4 +19,13 @@
|
||||
>
|
||||
<span class="mx-1">•</span>
|
||||
v{__APP_VERSION__}
|
||||
<a
|
||||
href="https://github.com/whoswhip/Sharpbin/commit/{COMMIT_HASH}"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-neutral-400 underline hover:text-neutral-200"
|
||||
>{(COMMIT_HASH?.length ?? 0) >= 7 && COMMIT_HASH !== 'unknown'
|
||||
? `(${COMMIT_HASH.slice(0, 7)})`
|
||||
: ''}</a
|
||||
>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { user } from '$lib/stores/user';
|
||||
import { resolve } from '$app/paths';
|
||||
import { page } from '$app/state';
|
||||
import { clearTokens } from '$lib/utils/auth';
|
||||
import { clearTokens, hasRole } from '$lib/utils/auth';
|
||||
import logo from '$lib/assets/favicon.svg';
|
||||
import type { PageData } from '../../routes/$types';
|
||||
import { slide } from 'svelte/transition';
|
||||
@@ -41,28 +41,40 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="top-0 left-0 z-100 h-15 w-full bg-neutral-900" id="navbar">
|
||||
<div
|
||||
class="sticky top-0 left-0 z-100 h-15 w-full border-b border-neutral-800 bg-neutral-900 shadow-md"
|
||||
id="navbar"
|
||||
>
|
||||
<div class="mx-auto hidden h-15 w-[95%] max-w-7xl items-center py-2 md:flex">
|
||||
<div>
|
||||
<a href={resolve('/')} class="text-xl font-bold text-white hover:text-neutral-300">Sharpbin</a
|
||||
<div class="flex items-center gap-6">
|
||||
<a href={resolve('/')} class="group flex items-center gap-2">
|
||||
<img src={logo} alt="Sharpbin Logo" class="h-7 w-7 group-hover:opacity-80" />
|
||||
<span class="text-xl font-bold text-white group-hover:text-neutral-300">Sharpbin</span>
|
||||
</a>
|
||||
<div class="h-5 w-px bg-neutral-700"></div>
|
||||
<a
|
||||
href={resolve('/recent')}
|
||||
class="relative text-neutral-300 after:absolute after:-bottom-0.5 after:left-0 after:h-px after:w-0 after:bg-white after:transition-all hover:text-white hover:after:w-full"
|
||||
>Recent Pastes</a
|
||||
>
|
||||
<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)}
|
||||
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
|
||||
<a
|
||||
href={resolve('/reports')}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Reports</a
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||
>Reports</a
|
||||
>
|
||||
{/if}
|
||||
<a
|
||||
href={resolve(`/user/${$user.username}`)}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800">Profile</a
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||
>Profile</a
|
||||
>
|
||||
<button
|
||||
on:click={logout}
|
||||
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800"
|
||||
class="cursor-pointer rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||
>Logout</button
|
||||
>
|
||||
</div>
|
||||
@@ -70,13 +82,14 @@
|
||||
<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
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600"
|
||||
>Login</a
|
||||
>
|
||||
<!-- eslint-disable svelte/no-navigation-without-resolve -->
|
||||
<a
|
||||
href={data.options?.registration_enabled ? resolve(`/register${returnParam}`) : '#'}
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white hover:bg-neutral-800 {data.options
|
||||
?.registration_enabled
|
||||
class="rounded bg-neutral-700 px-3 py-1 text-white transition-colors hover:bg-neutral-600 {data
|
||||
.options?.registration_enabled
|
||||
? ''
|
||||
: 'cursor-not-allowed bg-neutral-800 text-neutral-500!'}">Register</a
|
||||
>
|
||||
@@ -116,7 +129,7 @@
|
||||
on:click={() => (menuOpen = false)}>Recent Pastes</a
|
||||
>
|
||||
{#if $user}
|
||||
{#if $user.roles.includes(1) || $user.roles.includes(255)}
|
||||
{#if hasRole($user.roles, 2) || hasRole($user.roles, 4)}
|
||||
<a
|
||||
href={resolve('/reports')}
|
||||
class="mt-1 block w-full rounded bg-neutral-800 px-3 py-2 text-center text-neutral-100 transition-colors hover:bg-neutral-700"
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
<script lang="ts">
|
||||
import {
|
||||
tooltip,
|
||||
dateToRelativeString,
|
||||
extractDateFromUUIDv7,
|
||||
formatNumber,
|
||||
formatBytes
|
||||
} from '$lib/utils/misc';
|
||||
import { tooltip, dateToRelativeString, formatNumber, formatBytes } from '$lib/utils/misc';
|
||||
import { resolve } from '$app/paths';
|
||||
import {
|
||||
Eye,
|
||||
@@ -13,11 +7,12 @@
|
||||
Code,
|
||||
User,
|
||||
History,
|
||||
Calendar,
|
||||
Timer,
|
||||
CalendarDays,
|
||||
CalendarOff,
|
||||
Lock,
|
||||
EyeOff,
|
||||
Globe
|
||||
Globe,
|
||||
HatGlasses
|
||||
} from '@lucide/svelte';
|
||||
import { syntaxes } from '$lib/consts';
|
||||
import type { Paste } from '$lib/types/paste';
|
||||
@@ -27,7 +22,6 @@
|
||||
export let showUser: boolean = true;
|
||||
export let compact: boolean = false;
|
||||
|
||||
const createdAt = extractDateFromUUIDv7(paste.uuid);
|
||||
const syntax = syntaxes[paste.syntax] ?? syntaxes['plaintext'];
|
||||
</script>
|
||||
|
||||
@@ -45,14 +39,14 @@
|
||||
</span>
|
||||
<div
|
||||
class="flex items-center gap-2 text-sm text-neutral-400"
|
||||
use:tooltip={`${createdAt?.toLocaleString()} • ${dateToRelativeString(createdAt ?? new Date(), true, false, now)}`}
|
||||
use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
|
||||
>
|
||||
<Calendar class="h-4 w-4" />
|
||||
{#if createdAt}
|
||||
{#if createdAt.getTime() > Date.now() - 86_400_000}
|
||||
Created {dateToRelativeString(createdAt, true, false, now)}
|
||||
<CalendarDays class="h-4 w-4" />
|
||||
{#if paste.createdAt}
|
||||
{#if paste.createdAt > Date.now() - 86_400_000}
|
||||
Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
|
||||
{:else}
|
||||
Created on {createdAt.toLocaleDateString()}
|
||||
Created on {new Date(paste.createdAt).toLocaleDateString()}
|
||||
{/if}
|
||||
{:else}
|
||||
Creation date unknown
|
||||
@@ -64,7 +58,11 @@
|
||||
<div>
|
||||
{#if showUser}
|
||||
<div class="flex items-center gap-2">
|
||||
<User class="h-4 w-4" />
|
||||
{#if paste.author}
|
||||
<User class="h-4 w-4" />
|
||||
{:else}
|
||||
<HatGlasses class="h-4 w-4" />
|
||||
{/if}
|
||||
{paste.author?.username ?? 'Anonymous'}
|
||||
</div>
|
||||
{:else}
|
||||
@@ -117,15 +115,15 @@
|
||||
<div>
|
||||
<div
|
||||
class="flex items-center gap-2 text-sm text-neutral-400"
|
||||
use:tooltip={`${createdAt?.toLocaleString()} • ${dateToRelativeString(createdAt ?? new Date(), true, false, now)}`}
|
||||
use:tooltip={`${new Date(paste.createdAt).toLocaleString()} • ${dateToRelativeString(new Date(paste.createdAt), true, false, now)}`}
|
||||
>
|
||||
<Calendar class="h-4 w-4" />
|
||||
<CalendarDays class="h-4 w-4" />
|
||||
<span>
|
||||
{#if createdAt}
|
||||
{#if createdAt.getTime() > Date.now() - 86_400_000}
|
||||
Created {dateToRelativeString(createdAt, true, false, now)}
|
||||
{#if paste.createdAt}
|
||||
{#if paste.createdAt > Date.now() - 86_400_000}
|
||||
Created {dateToRelativeString(new Date(paste.createdAt), true, false, now)}
|
||||
{:else}
|
||||
Created on {createdAt.toLocaleDateString()}
|
||||
Created on {new Date(paste.createdAt).toLocaleDateString()}
|
||||
{/if}
|
||||
{:else}
|
||||
Creation date unknown
|
||||
@@ -146,7 +144,7 @@
|
||||
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" />
|
||||
<CalendarOff class="h-4 w-4" />
|
||||
<span>
|
||||
{paste.expiresAt > 0 && paste.expiresAt < Date.now()
|
||||
? `Expired ${dateToRelativeString(new Date(paste.expiresAt), true, false, now)}`
|
||||
@@ -156,7 +154,11 @@
|
||||
{/if}
|
||||
{#if showUser}
|
||||
<div class="mt-1 flex items-center gap-2 text-sm text-neutral-400">
|
||||
<User class="h-4 w-4" />
|
||||
{#if paste.author}
|
||||
<User class="h-4 w-4" />
|
||||
{:else}
|
||||
<HatGlasses class="h-4 w-4" />
|
||||
{/if}
|
||||
<span>{paste.author?.username ?? 'Anonymous'}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -41,6 +41,7 @@ export const syntaxes: Record<string, Syntax> = {
|
||||
crystal: { name: 'Crystal', extension: 'cr' },
|
||||
csp: { name: 'CSP', extension: 'csp' },
|
||||
css: { name: 'CSS', extension: 'css' },
|
||||
csv: { name: 'CSV', extension: 'csv' },
|
||||
d: { name: 'D', extension: 'd' },
|
||||
dart: { name: 'Dart', extension: 'dart' },
|
||||
deplhi: { name: 'Delphi', extension: 'pas' },
|
||||
@@ -192,7 +193,7 @@ export const syntaxes: Record<string, Syntax> = {
|
||||
|
||||
export const expiresOptions = [
|
||||
{ value: 0, label: 'Never Expire' },
|
||||
{ value: 30000, label: 'Expire in 5 Minutes' },
|
||||
{ value: 300000, label: 'Expire in 5 Minutes' },
|
||||
{ value: 600000, label: 'Expire in 10 Minutes' },
|
||||
{ value: 1800000, label: 'Expire in 30 Minutes' },
|
||||
{ value: 3600000, label: 'Expire in 1 Hour' },
|
||||
@@ -210,13 +211,6 @@ export const expiresOptions = [
|
||||
{ value: 315360000000, label: 'Expire in 10 Years' }
|
||||
];
|
||||
|
||||
export const roles = {
|
||||
0: 'User',
|
||||
1: 'Moderator',
|
||||
255: 'Administrator',
|
||||
403: 'Banned'
|
||||
};
|
||||
|
||||
export const trustedDomains = [
|
||||
'img.youtube.com',
|
||||
'i.ytimg.com',
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { env } from '$env/dynamic/private';
|
||||
|
||||
export const apiUrl = env.VITE_API_URL ?? 'http://localhost:5050';
|
||||
export const viewInternalApiKey =
|
||||
env.NODE_ENV === 'development'
|
||||
? 'cccdd42d9f2f648493e402f1da7c855ea798ad510e6bb9ea712dd7bed838e58'
|
||||
: (env.VIEW_INTERNAL_API_KEY ?? env.View_HMAC_Internal_API_Key ?? '');
|
||||
@@ -0,0 +1,114 @@
|
||||
<script lang="ts">
|
||||
import CalendarDays from '@lucide/svelte/icons/calendar-days';
|
||||
import CalendarOff from '@lucide/svelte/icons/calendar-off';
|
||||
import Code from '@lucide/svelte/icons/code';
|
||||
import Eye from '@lucide/svelte/icons/eye';
|
||||
import EyeOff from '@lucide/svelte/icons/eye-off';
|
||||
import FileBox from '@lucide/svelte/icons/file-box';
|
||||
import Globe from '@lucide/svelte/icons/globe';
|
||||
import Lock from '@lucide/svelte/icons/lock';
|
||||
import User from '@lucide/svelte/icons/user';
|
||||
import type { PasteEmbedProps } from './pasteEmbed';
|
||||
|
||||
export let title: PasteEmbedProps['title'];
|
||||
export let uploader: PasteEmbedProps['uploader'];
|
||||
export let metadata: PasteEmbedProps['metadata'];
|
||||
export let previewLines: PasteEmbedProps['previewLines'];
|
||||
export let isEncrypted: PasteEmbedProps['isEncrypted'];
|
||||
|
||||
const metadataIcons = {
|
||||
size: FileBox,
|
||||
views: Eye,
|
||||
created: CalendarDays,
|
||||
expires: CalendarOff,
|
||||
syntax: Code,
|
||||
'visibility-0': Globe,
|
||||
'visibility-1': EyeOff,
|
||||
'visibility-2': Lock
|
||||
} as const;
|
||||
</script>
|
||||
|
||||
<!--
|
||||
the following tailwindcss styles fail to parse, so they are applied inline:
|
||||
neutral-950
|
||||
gap-1.5
|
||||
truncate
|
||||
whitespace-nowrap
|
||||
gap-2
|
||||
gap-x-6.5
|
||||
gap-y-3
|
||||
gap-0.75
|
||||
gap-3
|
||||
whitespace-pre
|
||||
-->
|
||||
<!-- 630px by 1200px -->
|
||||
<div class="flex h-157.5 w-300 p-6" style="font-family:'Inter'; background-color: #0a0a0a;">
|
||||
<div
|
||||
class="flex h-full w-full flex-col rounded-lg border-2 border-neutral-800 bg-neutral-900 p-4"
|
||||
>
|
||||
<div class="mb-3.5 flex flex-col items-center justify-center" style="gap: 6px;">
|
||||
<div
|
||||
class="max-w-250 text-[54px] leading-[1.1] font-bold text-white"
|
||||
style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
|
||||
>
|
||||
{title}
|
||||
</div>
|
||||
<div class="flex items-center text-[20px] text-neutral-400" style="gap: 8px;">
|
||||
<User class="h-4.5 w-4.5 text-neutral-400" />
|
||||
<div>{uploader}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-3 flex flex-wrap items-center justify-center" style="gap: 12px;">
|
||||
{#each metadata as item (item.value)}
|
||||
{@const Icon = metadataIcons[item.icon]}
|
||||
<div class="flex items-center text-[24px] leading-none text-neutral-400">
|
||||
<Icon class="mr-2 h-5.5 w-5.5 text-neutral-400" />
|
||||
<div class="text-[24px] text-neutral-400">{item.value}</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#if isEncrypted}
|
||||
<div
|
||||
class="flex flex-1 items-center justify-center overflow-hidden rounded-lg bg-neutral-800"
|
||||
>
|
||||
<div class="flex flex-col items-center justify-center gap-3.5 p-6">
|
||||
<Lock class="h-16 w-16 text-neutral-400" />
|
||||
<div class="text-[36px] leading-[1.1] font-bold text-neutral-100">Encrypted Paste</div>
|
||||
<div class="max-w-195 text-center text-[20px] leading-[1.3] text-neutral-400">
|
||||
Preview is hidden for private encrypted pastes. Open the paste page and decrypt with the
|
||||
password to view content.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="relative flex flex-1 overflow-hidden rounded-lg bg-neutral-800">
|
||||
<div class="flex w-full flex-col pt-3" style="gap: 3px;">
|
||||
{#each previewLines as line, index (index)}
|
||||
<!-- emulates whitespace for indentation since satori doesnt seem to render it properly -->
|
||||
{@const leadingSpaceCount = line.length - line.trimStart().length}
|
||||
{@const contentWithoutIndent = line.trimStart()}
|
||||
<div class="flex items-center px-3.5" style="gap: 12px;">
|
||||
<div
|
||||
class="w-7.5 text-right text-[20px] text-neutral-500"
|
||||
style="font-family:'JetBrains Mono'; white-space: pre;"
|
||||
>
|
||||
{String(index + 1).padStart(3, ' ')}
|
||||
</div>
|
||||
<div
|
||||
class="flex items-center text-[20px] text-neutral-100"
|
||||
style="font-family:'JetBrains Mono'; white-space: pre;"
|
||||
>
|
||||
<div style={`width: ${leadingSpaceCount * 12}px;`}></div>
|
||||
<div>{contentWithoutIndent}</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div
|
||||
class="absolute right-0 bottom-0 left-0"
|
||||
style="height: 58px; background: linear-gradient(to bottom, rgba(38, 38, 38, 0), rgba(38, 38, 38, 1));"
|
||||
></div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,210 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
||||
import { mkdirSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import BetterSqlite3 from 'better-sqlite3';
|
||||
import type { Database } from 'better-sqlite3';
|
||||
|
||||
const CACHE_DIR = '.cache/og-images';
|
||||
const CACHE_DB_PATH = join(CACHE_DIR, 'index.db');
|
||||
const CACHE_EXPIRY_MS = 24 * 60 * 60 * 1000;
|
||||
const CACHE_CLEAN_INTERVAL_MS = 60 * 60 * 1000;
|
||||
const CACHE_STALE_WHILE_REVALIDATE_SECONDS = 300;
|
||||
const PURGE_BATCH_SIZE = 200;
|
||||
|
||||
type CacheRow = {
|
||||
relativePath: string;
|
||||
pasteExpiresAt: number | null;
|
||||
cacheExpiresAt: number;
|
||||
};
|
||||
|
||||
type ExpiredCacheRow = {
|
||||
pasteId: string;
|
||||
relativePath: string;
|
||||
};
|
||||
|
||||
export type CachedOgImage = {
|
||||
jpg: Buffer;
|
||||
ttlSeconds: number;
|
||||
};
|
||||
|
||||
export type StoreCachedOgImageInput = {
|
||||
id: string;
|
||||
jpg: Buffer;
|
||||
pasteExpiresAt?: number | null;
|
||||
};
|
||||
|
||||
let database: Database | null = null;
|
||||
let lastPurgeAt = 0;
|
||||
let purgeInFlight: Promise<void> | null = null;
|
||||
|
||||
function getDatabase(): Database {
|
||||
if (database) return database;
|
||||
|
||||
mkdirSync(CACHE_DIR, { recursive: true });
|
||||
const nextDatabase = new BetterSqlite3(CACHE_DB_PATH);
|
||||
nextDatabase.exec('PRAGMA journal_mode = WAL');
|
||||
nextDatabase.exec('PRAGMA synchronous = NORMAL');
|
||||
nextDatabase.exec(`
|
||||
CREATE TABLE IF NOT EXISTS og_image_cache (
|
||||
paste_id TEXT PRIMARY KEY,
|
||||
relative_path TEXT NOT NULL,
|
||||
paste_expires_at INTEGER,
|
||||
cache_expires_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_og_image_cache_cache_expires_at
|
||||
ON og_image_cache (cache_expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_og_image_cache_paste_expires_at
|
||||
ON og_image_cache (paste_expires_at);
|
||||
`);
|
||||
database = nextDatabase;
|
||||
return nextDatabase;
|
||||
}
|
||||
|
||||
function getCacheTtlExpiry(pasteExpiresAt?: number | null): number {
|
||||
const cacheExpiresAt = Date.now() + CACHE_EXPIRY_MS;
|
||||
if (!pasteExpiresAt) return cacheExpiresAt;
|
||||
return Math.min(cacheExpiresAt, pasteExpiresAt);
|
||||
}
|
||||
|
||||
export function getCacheTtlSeconds(expiresAt?: number | null): number {
|
||||
if (!expiresAt) return CACHE_EXPIRY_MS / 1000;
|
||||
const secondsUntilExpiry = Math.floor((expiresAt - Date.now()) / 1000);
|
||||
if (secondsUntilExpiry <= 0) return 0;
|
||||
return Math.min(secondsUntilExpiry, CACHE_EXPIRY_MS / 1000);
|
||||
}
|
||||
|
||||
export function getCacheControlHeader(ttlSeconds: number): string {
|
||||
return ttlSeconds > 0
|
||||
? `private, max-age=${ttlSeconds}, stale-while-revalidate=${CACHE_STALE_WHILE_REVALIDATE_SECONDS}`
|
||||
: 'no-store, max-age=0';
|
||||
}
|
||||
|
||||
function getShardRelativePath(id: string): string {
|
||||
const hash = createHash('sha256').update(id).digest('hex');
|
||||
return join(hash.slice(0, 2), hash.slice(2, 4), `${id}.jpg`);
|
||||
}
|
||||
|
||||
function getAbsolutePath(relativePath: string): string {
|
||||
return join(CACHE_DIR, relativePath);
|
||||
}
|
||||
|
||||
async function deleteCacheFile(relativePath: string): Promise<void> {
|
||||
await unlink(getAbsolutePath(relativePath)).catch(() => undefined);
|
||||
}
|
||||
|
||||
async function deleteCacheEntry(id: string, relativePath?: string): Promise<void> {
|
||||
const db = getDatabase();
|
||||
const resolvedPath =
|
||||
relativePath ??
|
||||
(
|
||||
db
|
||||
.prepare('SELECT relative_path AS relativePath FROM og_image_cache WHERE paste_id = ?')
|
||||
.get(id) as { relativePath: string } | undefined
|
||||
)?.relativePath ??
|
||||
null;
|
||||
|
||||
db.prepare('DELETE FROM og_image_cache WHERE paste_id = ?').run(id);
|
||||
if (resolvedPath) {
|
||||
await deleteCacheFile(resolvedPath);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCachedOgImage(id: string): Promise<CachedOgImage | null> {
|
||||
const db = getDatabase();
|
||||
const row = db
|
||||
.prepare(
|
||||
'SELECT relative_path AS relativePath, paste_expires_at AS pasteExpiresAt, cache_expires_at AS cacheExpiresAt FROM og_image_cache WHERE paste_id = ?'
|
||||
)
|
||||
.get(id) as CacheRow | undefined;
|
||||
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const ttlSeconds = getCacheTtlSeconds(row.cacheExpiresAt);
|
||||
if (ttlSeconds <= 0) {
|
||||
await deleteCacheEntry(id, row.relativePath);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof row.pasteExpiresAt === 'number' &&
|
||||
row.pasteExpiresAt > 0 &&
|
||||
row.pasteExpiresAt <= Date.now()
|
||||
) {
|
||||
await deleteCacheEntry(id, row.relativePath);
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const jpg = await readFile(getAbsolutePath(row.relativePath));
|
||||
return { jpg, ttlSeconds };
|
||||
} catch {
|
||||
await deleteCacheEntry(id, row.relativePath);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function storeCachedOgImage({
|
||||
id,
|
||||
jpg,
|
||||
pasteExpiresAt
|
||||
}: StoreCachedOgImageInput): Promise<void> {
|
||||
const db = getDatabase();
|
||||
const relativePath = getShardRelativePath(id);
|
||||
const absolutePath = getAbsolutePath(relativePath);
|
||||
const tempPath = `${absolutePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
await mkdir(dirname(absolutePath), { recursive: true });
|
||||
await writeFile(tempPath, jpg);
|
||||
await rename(tempPath, absolutePath);
|
||||
|
||||
try {
|
||||
db.prepare(
|
||||
`INSERT INTO og_image_cache (paste_id, relative_path, paste_expires_at, cache_expires_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(paste_id) DO UPDATE SET
|
||||
relative_path = excluded.relative_path,
|
||||
paste_expires_at = excluded.paste_expires_at,
|
||||
cache_expires_at = excluded.cache_expires_at`
|
||||
).run(id, relativePath, pasteExpiresAt ?? null, getCacheTtlExpiry(pasteExpiresAt));
|
||||
} catch (error) {
|
||||
await unlink(absolutePath).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function purgeExpiredCache(limit: number = PURGE_BATCH_SIZE): Promise<void> {
|
||||
const db = getDatabase();
|
||||
const now = Date.now();
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT paste_id AS pasteId, relative_path AS relativePath
|
||||
FROM og_image_cache
|
||||
WHERE cache_expires_at <= ?
|
||||
OR (paste_expires_at IS NOT NULL AND paste_expires_at > 0 AND paste_expires_at <= ?)
|
||||
LIMIT ?`
|
||||
)
|
||||
.all(now, now, limit) as ExpiredCacheRow[];
|
||||
|
||||
if (rows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const row of rows) {
|
||||
await deleteCacheFile(row.relativePath);
|
||||
db.prepare('DELETE FROM og_image_cache WHERE paste_id = ?').run(row.pasteId);
|
||||
}
|
||||
}
|
||||
|
||||
export function scheduleOgImageCachePurge(): void {
|
||||
const now = Date.now();
|
||||
if (purgeInFlight || now - lastPurgeAt < CACHE_CLEAN_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
purgeInFlight = purgeExpiredCache().finally(() => {
|
||||
lastPurgeAt = Date.now();
|
||||
purgeInFlight = null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export type PasteEmbedMetadataItem = {
|
||||
icon:
|
||||
| 'size'
|
||||
| 'views'
|
||||
| 'created'
|
||||
| 'expires'
|
||||
| 'syntax'
|
||||
| 'visibility-0'
|
||||
| 'visibility-1'
|
||||
| 'visibility-2';
|
||||
value: string;
|
||||
};
|
||||
|
||||
export type PasteEmbedProps = {
|
||||
title: string;
|
||||
uploader: string;
|
||||
metadata: PasteEmbedMetadataItem[];
|
||||
previewLines: string[];
|
||||
isEncrypted: boolean;
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import type { Author } from './author';
|
||||
export interface Paste {
|
||||
id: string;
|
||||
uuid: string;
|
||||
createdAt: number;
|
||||
title: string | null;
|
||||
size: number;
|
||||
trueSize: number;
|
||||
|
||||
@@ -8,7 +8,8 @@ export interface User {
|
||||
displayName: string | null;
|
||||
email: string | null;
|
||||
lastLogin: number | null;
|
||||
roles: number[];
|
||||
roles: number; // bitfield; 5 = User | Admin
|
||||
isBanned: boolean;
|
||||
visibility: 0 | 1 | 2;
|
||||
pastes: Paste[] | null;
|
||||
pagination: Pagination | null;
|
||||
@@ -17,3 +18,12 @@ export interface User {
|
||||
export interface AuthUser extends User {
|
||||
totpEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface JWTUser {
|
||||
uuid: string;
|
||||
username: string;
|
||||
displayname: string;
|
||||
totpEnabled: boolean;
|
||||
roles: number;
|
||||
isBanned: boolean;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,23 @@
|
||||
import { browser } from '$app/environment';
|
||||
import type { Cookies } from '@sveltejs/kit';
|
||||
import { user } from '$lib/stores/user';
|
||||
import type { JWTUser } from '$lib/types/user';
|
||||
|
||||
export const roles = {
|
||||
User: 1,
|
||||
Moderator: 2,
|
||||
Admin: 4
|
||||
} as const;
|
||||
|
||||
export type Role = keyof typeof roles;
|
||||
|
||||
const TOKEN_KEY = 'token';
|
||||
const REFRESH_TOKEN_KEY = 'refreshToken';
|
||||
|
||||
let refreshPromise: Promise<void> | null = null;
|
||||
let lastRefreshAttempt = 0;
|
||||
let refreshFailureCount = 0;
|
||||
|
||||
export function getToken() {
|
||||
if (!browser) return null;
|
||||
return (
|
||||
@@ -27,19 +40,25 @@ export function getRefreshToken() {
|
||||
|
||||
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`;
|
||||
refreshFailureCount = 0;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function getBackoffDelay(attempt: number): number {
|
||||
const baseDelay = 1000;
|
||||
const maxDelay = 30000;
|
||||
const delay = Math.min(baseDelay * Math.pow(2, attempt), maxDelay);
|
||||
return delay + Math.random() * 1000;
|
||||
}
|
||||
|
||||
export async function refreshTokenIfNeeded() {
|
||||
const token = getToken();
|
||||
const refreshToken = getRefreshToken();
|
||||
@@ -49,28 +68,55 @@ export async function refreshTokenIfNeeded() {
|
||||
const exp = payload.exp * 1000;
|
||||
const now = Date.now();
|
||||
|
||||
if (exp - now < 2 * 60 * 1000) {
|
||||
console.log('Refreshing token...');
|
||||
if (exp - now >= 2 * 60 * 1000) return;
|
||||
|
||||
if (refreshPromise) {
|
||||
await refreshPromise;
|
||||
return;
|
||||
}
|
||||
|
||||
const timeSinceLastAttempt = now - lastRefreshAttempt;
|
||||
const minDelay = getBackoffDelay(refreshFailureCount);
|
||||
if (timeSinceLastAttempt < minDelay) return;
|
||||
|
||||
refreshPromise = performRefresh(token, refreshToken);
|
||||
try {
|
||||
await refreshPromise;
|
||||
} finally {
|
||||
refreshPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function performRefresh(token: string, refreshToken: string) {
|
||||
lastRefreshAttempt = Date.now();
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/auth/refresh', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token, refreshToken })
|
||||
});
|
||||
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');
|
||||
|
||||
if (!res.ok) {
|
||||
refreshFailureCount++;
|
||||
if (res.status === 400 || res.status === 401 || res.status === 403) {
|
||||
clearTokens();
|
||||
}
|
||||
} else {
|
||||
console.log('Failed to refresh token');
|
||||
clearTokens();
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
if (data.success && data.token?.token && data.token?.refreshToken) {
|
||||
setTokens(data.token.token, data.token.refreshToken);
|
||||
} else {
|
||||
refreshFailureCount++;
|
||||
if (!data.success) {
|
||||
clearTokens();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
refreshFailureCount++;
|
||||
}
|
||||
console.log('Token is still valid, no refresh needed');
|
||||
}
|
||||
|
||||
export function startTokenRefreshInterval() {
|
||||
@@ -100,3 +146,24 @@ export function clearServerTokens(cookies: Cookies) {
|
||||
cookies.delete('token', { path: '/' });
|
||||
cookies.delete('refreshToken', { path: '/' });
|
||||
}
|
||||
|
||||
export function getUserFromToken(token: string): JWTUser | null {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||||
return {
|
||||
uuid: payload.uuid,
|
||||
username: payload.username,
|
||||
displayname: payload.displayname,
|
||||
totpEnabled: payload.totp_enabled === 'True',
|
||||
roles: typeof payload.roles === 'string' ? parseInt(payload.roles, 10) : payload.roles,
|
||||
isBanned: payload.is_banned === 'True'
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const hasRole = (userRoles: number, role: number) => (userRoles & role) !== 0;
|
||||
|
||||
export const getUserRoles = (userRoles: number): Role[] =>
|
||||
(Object.keys(roles) as Role[]).filter((role) => hasRole(userRoles, roles[role]));
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
import { argon2id } from 'hash-wasm';
|
||||
|
||||
const BASE64_CHUNK_SIZE = 0x8000;
|
||||
const SALT_LENGTH = 16;
|
||||
const IV_LENGTH = 12;
|
||||
const ARGON2_MEMORY_SIZE = 262144;
|
||||
const ARGON2_ITERATIONS = 3;
|
||||
const ARGON2_PARALLELISM = 1;
|
||||
const ARGON2_HASH_LENGTH = 32;
|
||||
const AES_KEY_LENGTH = 256;
|
||||
const ENCRYPTION_AAD = 'enc-v4';
|
||||
const ENCRYPTED_DATA_OVERHEAD = 60;
|
||||
const ENCRYPTED_METADATA_OVERHEAD = 150;
|
||||
|
||||
function toBase64(bytes: Uint8Array): string {
|
||||
let binary = '';
|
||||
const chunkSize = 0x8000;
|
||||
for (let i = 0; i < bytes.length; i += chunkSize) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
|
||||
for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + BASE64_CHUNK_SIZE));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
@@ -20,34 +31,32 @@ function fromBase64(data: string): Uint8Array {
|
||||
|
||||
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 salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
|
||||
|
||||
const keyMaterial = await argon2id({
|
||||
password,
|
||||
salt,
|
||||
iterations,
|
||||
memorySize,
|
||||
parallelism,
|
||||
hashLength: 32,
|
||||
iterations: ARGON2_ITERATIONS,
|
||||
memorySize: ARGON2_MEMORY_SIZE,
|
||||
parallelism: ARGON2_PARALLELISM,
|
||||
hashLength: ARGON2_HASH_LENGTH,
|
||||
outputType: 'binary'
|
||||
});
|
||||
|
||||
const key = await window.crypto.subtle.importKey(
|
||||
'raw',
|
||||
keyMaterial as unknown as BufferSource,
|
||||
{ name: 'AES-GCM' },
|
||||
new Uint8Array(keyMaterial),
|
||||
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||
false,
|
||||
['encrypt']
|
||||
);
|
||||
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(IV_LENGTH));
|
||||
const encryptedContent = await window.crypto.subtle.encrypt(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
iv
|
||||
iv,
|
||||
additionalData: enc.encode(ENCRYPTION_AAD)
|
||||
},
|
||||
key,
|
||||
enc.encode(content)
|
||||
@@ -61,9 +70,9 @@ export async function encryptAES(content: string, password: string): Promise<str
|
||||
return JSON.stringify({
|
||||
version: 4,
|
||||
kdf: 'Argon2id',
|
||||
memorySize,
|
||||
iterations,
|
||||
parallelism,
|
||||
memorySize: ARGON2_MEMORY_SIZE,
|
||||
iterations: ARGON2_ITERATIONS,
|
||||
parallelism: ARGON2_PARALLELISM,
|
||||
algorithm: 'AES-GCM',
|
||||
saltLength: salt.byteLength,
|
||||
ivLength: iv.byteLength,
|
||||
@@ -73,9 +82,9 @@ export async function encryptAES(content: string, password: string): Promise<str
|
||||
|
||||
export function estimateEncryptedSize(content: string): number {
|
||||
const rawSize = new TextEncoder().encode(content).length;
|
||||
const combinedSize = rawSize + 60;
|
||||
const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
|
||||
const b64Size = Math.ceil(combinedSize / 3) * 4;
|
||||
return b64Size + 150;
|
||||
return b64Size + ENCRYPTED_METADATA_OVERHEAD;
|
||||
}
|
||||
|
||||
export async function decryptAES(result: string, password: string): Promise<string | null> {
|
||||
@@ -84,8 +93,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
||||
const parsed = JSON.parse(result);
|
||||
const combined = fromBase64(parsed.data);
|
||||
|
||||
const saltLength = parsed.saltLength || 16;
|
||||
const ivLength = parsed.ivLength || 12;
|
||||
const saltLength = parsed.saltLength || SALT_LENGTH;
|
||||
const ivLength = parsed.ivLength || IV_LENGTH;
|
||||
const salt = combined.slice(0, saltLength);
|
||||
const iv = combined.slice(saltLength, saltLength + ivLength);
|
||||
const data = combined.slice(saltLength + ivLength);
|
||||
@@ -99,7 +108,7 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
||||
iterations: parsed.iterations,
|
||||
memorySize: parsed.memorySize,
|
||||
parallelism: parsed.parallelism,
|
||||
hashLength: 32,
|
||||
hashLength: ARGON2_HASH_LENGTH,
|
||||
outputType: 'binary'
|
||||
});
|
||||
} else {
|
||||
@@ -118,7 +127,7 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
||||
hash: parsed.hash
|
||||
},
|
||||
baseKey,
|
||||
{ name: 'AES-GCM', length: 256 },
|
||||
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||
true,
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
@@ -127,8 +136,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
||||
|
||||
const key = await window.crypto.subtle.importKey(
|
||||
'raw',
|
||||
keyMaterial as unknown as BufferSource,
|
||||
{ name: 'AES-GCM' },
|
||||
new Uint8Array(keyMaterial),
|
||||
{ name: 'AES-GCM', length: AES_KEY_LENGTH },
|
||||
false,
|
||||
['decrypt']
|
||||
);
|
||||
@@ -136,7 +145,8 @@ export async function decryptAES(result: string, password: string): Promise<stri
|
||||
const decryptedContent = await window.crypto.subtle.decrypt(
|
||||
{
|
||||
name: 'AES-GCM',
|
||||
iv
|
||||
iv,
|
||||
additionalData: enc.encode(ENCRYPTION_AAD)
|
||||
},
|
||||
key,
|
||||
data
|
||||
|
||||
@@ -3,6 +3,8 @@ import createDOMPurify from 'dompurify';
|
||||
import type { WindowLike } from 'dompurify';
|
||||
import { trustedDomains } from '$lib/consts';
|
||||
|
||||
export const externalMediaWarningStorageKey = 'sharpbin:ignore-external-media-warning';
|
||||
|
||||
const tagMap: Record<string, string> = {
|
||||
IMG: 'image',
|
||||
VIDEO: 'video',
|
||||
@@ -10,6 +12,18 @@ const tagMap: Record<string, string> = {
|
||||
IFRAME: 'iframe'
|
||||
};
|
||||
|
||||
export function getIgnoreExternalMediaWarning(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
|
||||
return window.localStorage.getItem(externalMediaWarningStorageKey) === 'true';
|
||||
}
|
||||
|
||||
export function setIgnoreExternalMediaWarning(ignore: boolean) {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
window.localStorage.setItem(externalMediaWarningStorageKey, ignore ? 'true' : 'false');
|
||||
}
|
||||
|
||||
export async function parseMarkdown(
|
||||
md: string,
|
||||
preventExternal: boolean = true,
|
||||
@@ -80,6 +94,14 @@ export async function parseMarkdown(
|
||||
'background-color: #404040; color: white; padding: 0.25rem 0.75rem; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
|
||||
);
|
||||
|
||||
const ignoreButton = dom.document.createElement('button');
|
||||
ignoreButton.textContent = "Don't warn again";
|
||||
ignoreButton.className = 'ignore-media-warning-btn';
|
||||
ignoreButton.setAttribute(
|
||||
'style',
|
||||
'background-color: transparent; color: #d4d4d8; padding: 0.25rem 0.75rem; border: 1px solid #525252; border-radius: 0.25rem; cursor: pointer; text-decoration: none;'
|
||||
);
|
||||
|
||||
if (element.getAttribute('alt'))
|
||||
button.setAttribute('data-alt', element.getAttribute('alt') || '');
|
||||
if (element.getAttribute('title'))
|
||||
@@ -89,9 +111,17 @@ export async function parseMarkdown(
|
||||
if (element.getAttribute('height'))
|
||||
button.setAttribute('data-height', element.getAttribute('height') || '');
|
||||
|
||||
const actions = dom.document.createElement('span');
|
||||
actions.setAttribute(
|
||||
'style',
|
||||
'display: flex; gap: 0.5rem; justify-content: center; flex-wrap: wrap;'
|
||||
);
|
||||
actions.appendChild(button);
|
||||
actions.appendChild(ignoreButton);
|
||||
|
||||
placeholder.appendChild(warning);
|
||||
placeholder.appendChild(subWarning);
|
||||
placeholder.appendChild(button);
|
||||
placeholder.appendChild(actions);
|
||||
|
||||
const parent = element.parentNode;
|
||||
if (parent && parent.nodeName === 'A') {
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { syntaxes } from '$lib/consts';
|
||||
|
||||
/**
|
||||
* @param bytes Bytes to format.
|
||||
* @param decimals Number of decimal places to include for non-integer values. Defaults to 2.
|
||||
* @returns A human readable string representing the byte size, e.g. "1.5 MB".
|
||||
*/
|
||||
export function formatBytes(bytes: number, decimals = 2): string {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
|
||||
@@ -15,6 +20,10 @@ export function formatBytes(bytes: number, decimals = 2): string {
|
||||
return `${formattedValue} ${unitLabel}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param num The number to format with commas as thousand separators.
|
||||
* @returns The formatted number as a string with commas. For example, 1234567 becomes "1,234,567".
|
||||
*/
|
||||
export function formatNumber(num: number): string {
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
}
|
||||
@@ -61,13 +70,21 @@ export function extractError(resData: unknown): string | null {
|
||||
export function syntaxFromExtension(extension: string): string | null {
|
||||
const ext = extension.startsWith('.') ? extension.slice(1) : extension;
|
||||
for (const [key, value] of Object.entries(syntaxes)) {
|
||||
if (value.extension === `.${ext}`) {
|
||||
if (value.extension.toLowerCase() === ext.toLowerCase()) {
|
||||
return key;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param date The date to compare to the current time.
|
||||
* @param useSuffix Whether to include "ago" or "from now" suffixes. Defaults to true.
|
||||
* @param full Whether to return a full breakdown of all time units (e.g. "1 year, 2 months, 3 days ago") or just the largest unit (e.g. "1 year ago"). Defaults to false.
|
||||
* @param nowArg Optional date to use as the current time for comparison, useful for testing. Defaults to the actual current time.
|
||||
* @param accuracy The maximum number of time units to include in the output when full is true. For example, with an accuracy of 2, you might get "1 year, 2 months ago" but not "1 year, 2 months, 3 days ago". Defaults to 1.
|
||||
* @returns A human readable relative time string.
|
||||
*/
|
||||
export function dateToRelativeString(
|
||||
date: Date,
|
||||
useSuffix = true,
|
||||
@@ -96,7 +113,7 @@ export function dateToRelativeString(
|
||||
return `${count} ${unit.name}${count > 1 ? 's' : ''} ${suffix}`.trim();
|
||||
}
|
||||
}
|
||||
return `0 seconds ${suffix}`.trim();
|
||||
return useSuffix ? 'just now' : '0 seconds';
|
||||
}
|
||||
const parts: string[] = [];
|
||||
let acc = 0;
|
||||
@@ -109,10 +126,18 @@ export function dateToRelativeString(
|
||||
acc++;
|
||||
}
|
||||
}
|
||||
if (parts.length === 0) parts.push('0 seconds');
|
||||
if (parts.length === 0) return useSuffix ? 'just now' : '0 seconds';
|
||||
return `${parts.join(', ')} ${suffix}`.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param node The HTML element to attach the tooltip to.
|
||||
* @param params The tooltip text, or an array where the first element is the tooltip text and the second element is a boolean indicating whether to use a darker background for the tooltip.
|
||||
* @returns An object with update and destroy methods to manage the tooltip lifecycle.
|
||||
* @example
|
||||
* <button use:tooltip="This is a tooltip">Hover me</button>
|
||||
* <button use:tooltip={["This is a darker tooltip", true]}>Hover me</button>
|
||||
*/
|
||||
export function tooltip(node: HTMLElement, params: string | [string, boolean?]) {
|
||||
let currentText = typeof params === 'string' ? params : (params[0] ?? '');
|
||||
let darker = typeof params === 'string' ? false : (params[1] ?? false);
|
||||
|
||||
@@ -10,9 +10,9 @@ export function parseTotpEnabled(tokenValue: string | null) {
|
||||
}
|
||||
}
|
||||
|
||||
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number[], nextRoles: number[]) {
|
||||
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number, nextRoles: number) {
|
||||
if (!totpEnabled) return false;
|
||||
const nextHasAdmin = nextRoles.includes(255);
|
||||
const alreadyAdmin = currentRoles.includes(255);
|
||||
const nextHasAdmin = (nextRoles & 4) !== 0;
|
||||
const alreadyAdmin = (currentRoles & 4) !== 0;
|
||||
return nextHasAdmin && !alreadyAdmin;
|
||||
}
|
||||
|
||||
@@ -439,7 +439,7 @@
|
||||
crypto.getRandomValues(bytes);
|
||||
password = Array.from(bytes, (b) => chars[b % chars.length]).join('');
|
||||
}}
|
||||
use:tooltip={'Generate Random Password'}
|
||||
use:tooltip={['Generate Random Password', true]}
|
||||
>
|
||||
<Dices class="h-5 w-5" />
|
||||
</button>
|
||||
@@ -473,7 +473,7 @@
|
||||
{/if}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={$user?.roles && $user.roles.includes(403)}
|
||||
disabled={$user?.isBanned}
|
||||
class="mb-2 w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
|
||||
>Create Paste</button
|
||||
>
|
||||
@@ -485,7 +485,7 @@
|
||||
{error}
|
||||
</div>
|
||||
{/if}
|
||||
{#if $user?.roles && $user.roles.includes(403)}
|
||||
{#if $user?.isBanned}
|
||||
<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"
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { syntaxes } from '$lib/consts';
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
import {
|
||||
getCachedOgImage,
|
||||
getCacheControlHeader,
|
||||
getCacheTtlSeconds,
|
||||
scheduleOgImageCachePurge,
|
||||
storeCachedOgImage
|
||||
} from '$lib/server/og/cache';
|
||||
import OgPasteEmbed from '$lib/server/og/PasteEmbed.svelte';
|
||||
import type { PasteEmbedProps } from '$lib/server/og/pasteEmbed';
|
||||
import type { Paste } from '$lib/types/paste';
|
||||
import {
|
||||
dateToRelativeString,
|
||||
extractDateFromUUIDv7,
|
||||
formatBytes,
|
||||
formatNumber
|
||||
} from '$lib/utils/misc';
|
||||
import { Resvg } from '@resvg/resvg-js';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
import satori from 'satori';
|
||||
import { html } from 'satori-html';
|
||||
import sharp from 'sharp';
|
||||
import type { Component } from 'svelte';
|
||||
import { render } from 'svelte/server';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
const WIDTH = 1200;
|
||||
const HEIGHT = 630;
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
type FontConfig = {
|
||||
name: string;
|
||||
data: Buffer;
|
||||
weight: 400 | 700;
|
||||
style: 'normal';
|
||||
};
|
||||
|
||||
type GeneratedImage = {
|
||||
jpg: Buffer;
|
||||
cacheControl: string;
|
||||
};
|
||||
const generationInFlight = new Map<string, Promise<GeneratedImage>>();
|
||||
|
||||
const visibilityLabels: Record<Paste['visibility'], string> = {
|
||||
0: 'Public',
|
||||
1: 'Unlisted',
|
||||
2: 'Private'
|
||||
};
|
||||
|
||||
const fontsPromise: Promise<FontConfig[]> = Promise.all([
|
||||
readFile(require.resolve('@fontsource/inter/files/inter-latin-400-normal.woff')),
|
||||
readFile(require.resolve('@fontsource/inter/files/inter-latin-700-normal.woff')),
|
||||
readFile(require.resolve('@fontsource/jetbrains-mono/files/jetbrains-mono-latin-400-normal.woff'))
|
||||
]).then(([inter400, inter700, mono400]) => [
|
||||
{ name: 'Inter', data: inter400, weight: 400, style: 'normal' },
|
||||
{ name: 'Inter', data: inter700, weight: 700, style: 'normal' },
|
||||
{ name: 'JetBrains Mono', data: mono400, weight: 400, style: 'normal' }
|
||||
]);
|
||||
|
||||
function getPreviewLines(content: string): string[] {
|
||||
return content
|
||||
.split('\n')
|
||||
.slice(0, 15)
|
||||
.map((line) => {
|
||||
const normalized = line.replace(/\t/g, ' ');
|
||||
return normalized.length > 86 ? `${normalized.slice(0, 83)}...` : normalized;
|
||||
});
|
||||
}
|
||||
|
||||
const entityMap: Record<string, string> = {
|
||||
lt: '<',
|
||||
gt: '>',
|
||||
amp: '&',
|
||||
quot: '"',
|
||||
'#39': "'",
|
||||
'#x27': "'"
|
||||
};
|
||||
|
||||
// satori sanitizes html but doesnt render them properly (stays as < for example)
|
||||
// so replace sanitized entities with the actual characters
|
||||
function decodeHtmlEntities(value: string): string {
|
||||
let output = value;
|
||||
for (;;) {
|
||||
const next = output.replace(
|
||||
/&(lt|gt|amp|quot|#39|#x27);/g,
|
||||
(_, entity: string) => entityMap[entity]
|
||||
);
|
||||
if (next === output) return next;
|
||||
output = next;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeSatoriTextNodes(node: unknown): unknown {
|
||||
if (typeof node === 'string') return decodeHtmlEntities(node);
|
||||
if (Array.isArray(node)) return node.map(normalizeSatoriTextNodes);
|
||||
if (!node || typeof node !== 'object') return node;
|
||||
|
||||
const props = (node as { props?: { children?: unknown } }).props;
|
||||
if (props && 'children' in props) {
|
||||
props.children = normalizeSatoriTextNodes(props.children);
|
||||
}
|
||||
|
||||
if (props && Array.isArray(props.children) && props.children.length === 0) {
|
||||
delete (props as Record<string, unknown>).children;
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
export const GET: RequestHandler = async ({ params, fetch }) => {
|
||||
const id = params.id;
|
||||
if (!id) {
|
||||
return new Response('Missing paste id.', { status: 400 });
|
||||
}
|
||||
|
||||
scheduleOgImageCachePurge();
|
||||
|
||||
const cachedImage = await getCachedOgImage(id);
|
||||
if (cachedImage) {
|
||||
return new Response(new Uint8Array(cachedImage.jpg), {
|
||||
headers: {
|
||||
'Content-Type': 'image/jpeg',
|
||||
'Cache-Control': getCacheControlHeader(cachedImage.ttlSeconds)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const existingGeneration = generationInFlight.get(id);
|
||||
if (existingGeneration) {
|
||||
const generated = await existingGeneration;
|
||||
return new Response(new Uint8Array(generated.jpg), {
|
||||
headers: {
|
||||
'Content-Type': 'image/jpeg',
|
||||
'Cache-Control': generated.cacheControl
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const generation = (async (): Promise<GeneratedImage> => {
|
||||
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`);
|
||||
if (!pasteRes.ok) {
|
||||
throw new Response('Paste not found.', { status: pasteRes.status === 404 ? 404 : 500 });
|
||||
}
|
||||
|
||||
const pasteData = (await pasteRes.json()) as { paste?: Paste };
|
||||
const paste = pasteData.paste;
|
||||
if (!paste) {
|
||||
throw new Response('Invalid paste response.', { status: 500 });
|
||||
}
|
||||
|
||||
const isEncrypted = paste.visibility === 2;
|
||||
let rawContent = '';
|
||||
if (!isEncrypted) {
|
||||
const rawRes = await fetch(`${apiUrl}/api/paste/${id}/raw`);
|
||||
rawContent = rawRes.ok ? await rawRes.text() : '';
|
||||
}
|
||||
|
||||
const content = rawContent || 'No content available.';
|
||||
const created = paste.createdAt ? new Date(paste.createdAt) : extractDateFromUUIDv7(paste.uuid);
|
||||
const metadata: PasteEmbedProps['metadata'] = [
|
||||
{ icon: 'size', value: formatBytes(paste.trueSize) },
|
||||
{
|
||||
icon: 'views',
|
||||
value: `${formatNumber(paste.views)} view${paste.views === 1 ? '' : 's'}`
|
||||
},
|
||||
{ icon: 'created', value: created ? created.toLocaleDateString() : 'Unknown' },
|
||||
...(paste.expiresAt
|
||||
? [
|
||||
{
|
||||
icon: 'expires' as const,
|
||||
value: `Expires in ${dateToRelativeString(new Date(paste.expiresAt), false)}`
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{ icon: 'syntax', value: syntaxes[paste.syntax]?.name ?? paste.syntax },
|
||||
{ icon: `visibility-${paste.visibility}`, value: visibilityLabels[paste.visibility] }
|
||||
];
|
||||
const props: PasteEmbedProps = {
|
||||
title: paste.title?.trim() || 'Untitled Paste',
|
||||
uploader: paste.author?.username ?? 'Anonymous Uploader',
|
||||
metadata,
|
||||
previewLines: isEncrypted ? [] : getPreviewLines(content),
|
||||
isEncrypted
|
||||
};
|
||||
|
||||
const fonts = await fontsPromise;
|
||||
const markup = render(OgPasteEmbed as unknown as Component<PasteEmbedProps>, { props }).body;
|
||||
const satoriNode = normalizeSatoriTextNodes(html(markup));
|
||||
const svg = await satori(satoriNode, { width: WIDTH, height: HEIGHT, fonts });
|
||||
const png = new Resvg(svg, { fitTo: { mode: 'width', value: WIDTH } }).render().asPng();
|
||||
const jpg = await sharp(png).jpeg({ quality: 92, mozjpeg: true }).toBuffer();
|
||||
|
||||
const cacheTtlSeconds = getCacheTtlSeconds(paste.expiresAt);
|
||||
const cacheControl = getCacheControlHeader(cacheTtlSeconds);
|
||||
await storeCachedOgImage({ id, jpg, pasteExpiresAt: paste.expiresAt ?? null }).catch(
|
||||
() => undefined
|
||||
);
|
||||
|
||||
return { jpg, cacheControl };
|
||||
})();
|
||||
|
||||
generationInFlight.set(id, generation);
|
||||
|
||||
try {
|
||||
const generated = await generation;
|
||||
return new Response(new Uint8Array(generated.jpg), {
|
||||
headers: {
|
||||
'Content-Type': 'image/jpeg',
|
||||
'Cache-Control': generated.cacheControl
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof Response) {
|
||||
return error;
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
generationInFlight.delete(id);
|
||||
}
|
||||
};
|
||||
@@ -1,37 +1,33 @@
|
||||
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 { apiUrl, viewInternalApiKey } from '$lib/server/api';
|
||||
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 }) => {
|
||||
export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent, request }) => {
|
||||
const { id } = params;
|
||||
if (!id) {
|
||||
// realistically this shouldnt happen
|
||||
throw error(400, 'Missing paste id.');
|
||||
}
|
||||
const parentData = await parent().catch(() => null);
|
||||
|
||||
const token = getServerToken(cookies);
|
||||
const userAgent = request.headers.get('user-agent') ?? 'Sharpbin Client';
|
||||
const clientHeaders = new Headers(request.headers);
|
||||
clientHeaders.set('Authorization', token ? `Bearer ${token}` : '');
|
||||
clientHeaders.set('User-Agent', userAgent);
|
||||
|
||||
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, {
|
||||
headers: {
|
||||
Authorization: token ? `Bearer ${token}` : ''
|
||||
}
|
||||
});
|
||||
const pasteRes = await fetch(`${apiUrl}/api/paste/${id}`, { headers: clientHeaders });
|
||||
|
||||
if (pasteRes.status === 404) {
|
||||
throw error(pasteRes.status, 'Paste not found.');
|
||||
}
|
||||
|
||||
const viewedHeaders = new Headers(clientHeaders);
|
||||
viewedHeaders.set('X-Internal-API-Key', viewInternalApiKey);
|
||||
const viewed = await fetch(`${apiUrl}/api/paste/${id}/view`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Internal-API-Key': apiKey,
|
||||
Authorization: token ? `Bearer ${token}` : ''
|
||||
}
|
||||
headers: viewedHeaders
|
||||
});
|
||||
|
||||
const pasteData = await pasteRes.json();
|
||||
@@ -39,22 +35,17 @@ export const load: PageServerLoad = async ({ params, fetch, url, cookies, parent
|
||||
|
||||
if (viewed.status === 200) {
|
||||
const viewJson = await viewed.json();
|
||||
if (viewJson.success === true && viewJson.message !== 'View already recorded.') {
|
||||
if (viewJson.success === true && viewJson.message === 'Paste view recorded.') {
|
||||
pasteData.views += 1;
|
||||
}
|
||||
} else {
|
||||
} else if (viewInternalApiKey === '') {
|
||||
console.error(
|
||||
`Failed to increment view count for paste ${id}, status code ${viewed.status}: ${await viewed.text()}`
|
||||
'The API key for internal requests is not set. Please configure it in the environment variables.'
|
||||
);
|
||||
if (apiKey === '') {
|
||||
console.error(
|
||||
'The API key for internal requests is not set. Please configure it in the environment variables.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const pasteContent = await fetch(`/api/paste/${id}/raw`);
|
||||
const pasteOptions = await fetch('/api/paste/info');
|
||||
const pasteContent = await fetch(`${apiUrl}/api/paste/${id}/raw`, { headers: clientHeaders });
|
||||
const pasteOptions = await fetch(`${apiUrl}/api/paste/info`, { headers: clientHeaders });
|
||||
const options = await pasteOptions.json();
|
||||
const content = await pasteContent.text();
|
||||
|
||||
|
||||
@@ -23,7 +23,8 @@
|
||||
Check,
|
||||
CalendarCog,
|
||||
Flag,
|
||||
ArrowUp
|
||||
ArrowUp,
|
||||
HatGlasses
|
||||
} from '@lucide/svelte/icons/index';
|
||||
import {
|
||||
formatBytes,
|
||||
@@ -33,12 +34,16 @@
|
||||
tooltip,
|
||||
isBinaryData
|
||||
} from '$lib/utils/misc';
|
||||
import { parseMarkdown } from '$lib/utils/markdown';
|
||||
import {
|
||||
getIgnoreExternalMediaWarning,
|
||||
parseMarkdown,
|
||||
setIgnoreExternalMediaWarning
|
||||
} from '$lib/utils/markdown';
|
||||
import { syntaxes, expiresOptions } 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 { getToken, hasRole } from '$lib/utils/auth';
|
||||
import { user } from '$lib/stores/user';
|
||||
import Dropdown from '$lib/components/Dropdown.svelte';
|
||||
import { openModal } from '$lib/stores/modal';
|
||||
@@ -62,6 +67,7 @@
|
||||
let copiedPaste = false;
|
||||
let highlightWorker: Worker | null = null;
|
||||
let highlightRequestId = 0;
|
||||
let ignoreExternalMediaWarning = false;
|
||||
|
||||
let scrollY = 0;
|
||||
|
||||
@@ -112,7 +118,7 @@
|
||||
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>`
|
||||
`<div class="code-row"><span class="line-number" style="--digits:${digits}">${i + 1}</span><span class="code-line">${line}</span></div>`
|
||||
)
|
||||
.join('');
|
||||
return html.replace(code, numbered);
|
||||
@@ -132,7 +138,7 @@
|
||||
|
||||
switch (data.paste.syntax) {
|
||||
case 'markdown':
|
||||
pasteContent = await parseMarkdown(contentToRender);
|
||||
pasteContent = await parseMarkdown(contentToRender, !ignoreExternalMediaWarning);
|
||||
contentRendered = true;
|
||||
decryptStatus = '';
|
||||
break;
|
||||
@@ -357,6 +363,13 @@
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
if (target.classList.contains('ignore-media-warning-btn')) {
|
||||
ignoreExternalMediaWarning = true;
|
||||
setIgnoreExternalMediaWarning(true);
|
||||
renderPaste();
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.classList.contains('load-media-btn')) {
|
||||
const src = target.getAttribute('data-src');
|
||||
const tag = target.getAttribute('data-tag');
|
||||
@@ -422,6 +435,8 @@
|
||||
|
||||
onMount(async () => {
|
||||
try {
|
||||
ignoreExternalMediaWarning = getIgnoreExternalMediaWarning();
|
||||
|
||||
if (data?.paste && data.paste.visibility === 2) {
|
||||
contentRendered = false;
|
||||
decryptStatus = 'Preparing decryption...';
|
||||
@@ -479,6 +494,8 @@
|
||||
$: reportSiteKey =
|
||||
(data as unknown as { authOptions?: { cf_turnstile_site_key?: string | null } }).authOptions
|
||||
?.cf_turnstile_site_key ?? null;
|
||||
$: pasteImageUrl =
|
||||
data?.paste && data?.url ? `${new URL(data.url).origin}/${data.paste.id}.jpg` : null;
|
||||
</script>
|
||||
|
||||
<svelte:window bind:scrollY />
|
||||
@@ -502,6 +519,14 @@
|
||||
<meta property="og:type" content="article" />
|
||||
<meta property="og:url" content={data.url} />
|
||||
<meta property="og:site_name" content="Sharpbin" />
|
||||
{#if pasteImageUrl}
|
||||
<meta property="og:image" content={pasteImageUrl} />
|
||||
<meta property="og:image:type" content="image/jpeg" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
<meta property="og:image:height" content="630" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:image" content={pasteImageUrl} />
|
||||
{/if}
|
||||
<meta
|
||||
property="og:article:published_time"
|
||||
content={extractDateFromUUIDv7(data.paste.uuid)?.toISOString() ?? ''}
|
||||
@@ -525,8 +550,7 @@
|
||||
{#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 : ''}
|
||||
class="mx-auto max-w-[90%] min-w-0 text-3xl leading-tight font-bold wrap-break-word sm:text-4xl"
|
||||
>
|
||||
{#if !editing}
|
||||
{data.paste.title || 'Untitled Paste'}
|
||||
@@ -541,14 +565,15 @@
|
||||
{/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}
|
||||
<User class="inline-block h-4 w-4 text-neutral-400" />
|
||||
<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}
|
||||
<HatGlasses class="inline-block h-4 w-4 text-neutral-400" />
|
||||
<span class="text-neutral-400">Anonymous</span>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -684,7 +709,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="sticky top-0 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row"
|
||||
class="sticky top-15 z-10 flex flex-col items-center justify-between gap-2 rounded-t-md border-b border-neutral-700 bg-neutral-800 px-3 py-2 md:flex-row"
|
||||
>
|
||||
{#if !isBinary}
|
||||
<div class="flex items-center gap-2 text-sm text-neutral-300">
|
||||
@@ -811,7 +836,7 @@
|
||||
<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 $user && ($user.uuid === data.paste?.author?.uuid || hasRole($user.roles, 2) || hasRole($user.roles, 4))}
|
||||
{#if !editing}
|
||||
{#if !isBinary}
|
||||
<button
|
||||
@@ -943,6 +968,7 @@
|
||||
<style>
|
||||
.hljs {
|
||||
background-color: var(--color-neutral-800) !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
.codeblock-with-lines {
|
||||
@@ -970,29 +996,42 @@
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
min-width: 0;
|
||||
padding: 0.1em 0;
|
||||
border-radius: 0.15em;
|
||||
padding: 0;
|
||||
}
|
||||
.code-row:hover {
|
||||
background-color: rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
.line-number {
|
||||
flex-shrink: 0;
|
||||
display: inline-flex;
|
||||
align-self: stretch;
|
||||
align-items: flex-start;
|
||||
justify-content: flex-end;
|
||||
flex: 0 0 calc(var(--digits, 1) * 1ch + 1.3em);
|
||||
width: calc(var(--digits, 1) * 1ch + 1.3em);
|
||||
box-sizing: border-box;
|
||||
text-align: right;
|
||||
color: #888;
|
||||
user-select: none;
|
||||
margin-right: 1em;
|
||||
margin-right: 0;
|
||||
font-family:
|
||||
ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New',
|
||||
monospace;
|
||||
font-variant-numeric: tabular-nums;
|
||||
padding-top: 0.1em;
|
||||
padding-bottom: 0.1em;
|
||||
padding-right: 0.5em;
|
||||
padding-left: 0.25em;
|
||||
padding-left: 0.9em;
|
||||
background: none;
|
||||
border-right: 1px solid var(--color-neutral-700);
|
||||
}
|
||||
.code-line {
|
||||
display: block;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
padding-left: 0.25em;
|
||||
padding-top: 0.1em;
|
||||
padding-bottom: 0.1em;
|
||||
padding-left: 0.9em;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -83,7 +83,8 @@ select {
|
||||
color: #3b82f6;
|
||||
text-decoration: underline;
|
||||
}
|
||||
.markdown .load-media-btn:hover {
|
||||
.markdown .load-media-btn:hover,
|
||||
.markdown .ignore-media-warning-btn:hover {
|
||||
background-color: #525252 !important;
|
||||
}
|
||||
.markdown pre {
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import type { RequestHandler } from '@sveltejs/kit';
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
|
||||
const apiUrl = process.env.VITE_API_URL || 'http://localhost:5050';
|
||||
|
||||
export const GET: RequestHandler = async ({ params }) => {
|
||||
export const GET: RequestHandler = async ({ params, request }) => {
|
||||
const { id } = params;
|
||||
const headers = new Headers(request.headers);
|
||||
|
||||
const res = await fetch(`${apiUrl}/api/paste/${id}/raw`);
|
||||
const res = await fetch(`${apiUrl}/api/paste/${id}/raw`, {
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (res.status === 404) {
|
||||
return new Response('Paste not found', { status: 404 });
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
statusText: 'Not Found'
|
||||
});
|
||||
}
|
||||
const content = await res.text();
|
||||
return new Response(content, {
|
||||
|
||||
@@ -3,9 +3,10 @@ import type { Paste } from '$lib/types/paste';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
import { error } from '@sveltejs/kit';
|
||||
|
||||
export const load: PageServerLoad = async ({ fetch }) => {
|
||||
export const load: PageServerLoad = async ({ fetch, request }) => {
|
||||
try {
|
||||
const res = await fetch('/api/paste/recent');
|
||||
const headers = new Headers(request.headers);
|
||||
const res = await fetch('/api/paste/recent', { headers });
|
||||
if (!res.ok) {
|
||||
const errorMsg = extractError(await res.json()) || 'Failed to fetch recent pastes.';
|
||||
throw error(res.status, errorMsg);
|
||||
|
||||
@@ -1,33 +1,24 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getServerToken } from '$lib/utils/auth';
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
import { getServerToken, clearServerTokens, roles, getUserFromToken } 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 }) => {
|
||||
export const load: PageServerLoad = async ({ fetch, cookies, params, url, request }) => {
|
||||
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}` }
|
||||
const user = getUserFromToken(token);
|
||||
if (!user) {
|
||||
clearServerTokens(cookies);
|
||||
throw error(401, 'Invalid token');
|
||||
}
|
||||
const canEdit = (user.roles & roles.Admin) !== 0 || (user.roles & roles.Moderator) !== 0;
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
|
||||
const res = await fetch(`${apiUrl}/api/report/${params.reportId}`, {
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -36,7 +27,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, params, url }) => {
|
||||
}
|
||||
|
||||
const report = (await res.json()) as Report;
|
||||
const optionsRes = await fetch(`${API_URL}/api/report/options`);
|
||||
const optionsRes = await fetch(`${apiUrl}/api/report/options`);
|
||||
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
|
||||
|
||||
return { report, url: url.href, canEdit, options };
|
||||
|
||||
@@ -1,37 +1,32 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { getServerToken } from '$lib/utils/auth';
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
import {
|
||||
getServerToken,
|
||||
getUserFromToken,
|
||||
clearServerTokens,
|
||||
hasRole,
|
||||
roles
|
||||
} from '$lib/utils/auth';
|
||||
import type { ReportListResponse } from '$lib/types/report';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
|
||||
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 [];
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeTarget(value: string | null): 'all' | 'pastes' | 'users' {
|
||||
if (value === 'pastes' || value === 'users') return value;
|
||||
return 'all';
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
|
||||
export const load: PageServerLoad = async ({ fetch, cookies, url, request }) => {
|
||||
const token = getServerToken(cookies);
|
||||
if (!token) throw error(401, 'Login required');
|
||||
|
||||
const roles = decodeJwtRoles(token);
|
||||
if (!roles.includes(1) && !roles.includes(255)) {
|
||||
const user = getUserFromToken(token);
|
||||
if (!user) {
|
||||
clearServerTokens(cookies);
|
||||
throw error(401, 'Invalid token');
|
||||
}
|
||||
|
||||
if (!hasRole(user.roles, roles.Admin) && !hasRole(user.roles, roles.Moderator)) {
|
||||
throw error(403, 'You do not have permission to view reports.');
|
||||
}
|
||||
|
||||
@@ -49,8 +44,11 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
|
||||
if ((target === 'pastes' || target === 'all') && pasteId) query.set('pasteId', pasteId);
|
||||
if ((target === 'users' || target === 'all') && userUuid) query.set('userUUID', userUuid);
|
||||
|
||||
const reportsRes = await fetch(`${API_URL}/api/report/${target}?${query.toString()}`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
|
||||
const reportsRes = await fetch(`${apiUrl}/api/report/${target}?${query.toString()}`, {
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (!reportsRes.ok) {
|
||||
@@ -60,7 +58,7 @@ export const load: PageServerLoad = async ({ fetch, cookies, url }) => {
|
||||
|
||||
const reports = (await reportsRes.json()) as ReportListResponse;
|
||||
|
||||
const optionsRes = await fetch(`${API_URL}/api/report/options`);
|
||||
const optionsRes = await fetch(`${apiUrl}/api/report/options`);
|
||||
const options = optionsRes.ok ? await optionsRes.json() : { types: [], statuses: [] };
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
import { error, isHttpError } from '@sveltejs/kit';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
|
||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
||||
|
||||
export const load: PageServerLoad = async ({ fetch }) => {
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/api/stats`);
|
||||
const res = await fetch(`${apiUrl}/api/stats`);
|
||||
|
||||
if (!res.ok) {
|
||||
const json = await res.json().catch(() => ({}));
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { error } from '@sveltejs/kit';
|
||||
import { env } from '$env/dynamic/private';
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
import { getServerToken } from '$lib/utils/auth';
|
||||
import type { User } from '$lib/types/user';
|
||||
import type { Paste } from '$lib/types/paste';
|
||||
import type { Pagination } from '$lib/types/pagination';
|
||||
import type { Report, ReportListResponse } from '$lib/types/report';
|
||||
|
||||
const API_URL = env.VITE_API_URL ?? 'http://localhost:5050';
|
||||
|
||||
function decodeJwtRoles(token?: string | null): number[] {
|
||||
function decodeJwtRoles(token?: string | null): number {
|
||||
try {
|
||||
if (!token) return [];
|
||||
if (!token) return 0;
|
||||
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));
|
||||
if (typeof roles === 'number') return roles;
|
||||
if (typeof roles === 'string') {
|
||||
const parsed = parseInt(roles, 10);
|
||||
return isNaN(parsed) ? 0 : parsed;
|
||||
}
|
||||
return [];
|
||||
return 0;
|
||||
} catch {
|
||||
return [];
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,14 +34,19 @@ function decodeJwtUuid(token?: string | null): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent }) => {
|
||||
export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent, request }) => {
|
||||
const token = getServerToken(cookies);
|
||||
const { username } = params;
|
||||
const { options } = await parent();
|
||||
const jwtUuid = decodeJwtUuid(token);
|
||||
const asGuest = url.searchParams.get('guest') === '1';
|
||||
const headers = new Headers(request.headers);
|
||||
if (token && !asGuest) {
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_URL}/api/user/${username}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined
|
||||
const res = await fetch(`${apiUrl}/api/user/${username}`, {
|
||||
headers: headers
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -60,8 +65,8 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
|
||||
const isOwner = jwtUuid ? user.uuid === jwtUuid : false;
|
||||
let reportsTarget: ReportListResponse | null = null;
|
||||
let reportsSubmitted: ReportListResponse | null = null;
|
||||
const roles = token ? decodeJwtRoles(token) : [];
|
||||
const canModerate = roles.includes(255) || roles.includes(1);
|
||||
const roles = token ? decodeJwtRoles(token) : 0;
|
||||
const canModerate = (roles & 4) !== 0 || (roles & 2) !== 0;
|
||||
|
||||
if (isOwner && reports && reportsPagination) {
|
||||
reportsSubmitted = {
|
||||
@@ -70,20 +75,20 @@ export const load: PageServerLoad = async ({ params, fetch, cookies, url, parent
|
||||
};
|
||||
}
|
||||
|
||||
if (token && canModerate && (!reportsSubmitted || !isOwner)) {
|
||||
const submittedRes = await fetch(`${API_URL}/api/user/${user.uuid}/reports/submitted`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
if (token && !asGuest && canModerate && (!reportsSubmitted || !isOwner)) {
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
const submittedRes = await fetch(`${apiUrl}/api/user/${user.uuid}/reports/submitted`, {
|
||||
headers: headers
|
||||
});
|
||||
if (submittedRes.ok) reportsSubmitted = await submittedRes.json();
|
||||
}
|
||||
|
||||
if (token && !isOwner) {
|
||||
if (canModerate) {
|
||||
const r = await fetch(`${API_URL}/api/user/${user.uuid}/reports`, {
|
||||
headers: { Authorization: `Bearer ${token}` }
|
||||
});
|
||||
if (r.ok) reportsTarget = await r.json();
|
||||
}
|
||||
if (token && !asGuest && !isOwner && canModerate) {
|
||||
headers.set('Authorization', `Bearer ${token}`);
|
||||
const r = await fetch(`${apiUrl}/api/user/${user.uuid}/reports`, {
|
||||
headers: headers
|
||||
});
|
||||
if (r.ok) reportsTarget = await r.json();
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -27,8 +27,7 @@
|
||||
dateToRelativeString,
|
||||
extractError
|
||||
} from '$lib/utils/misc';
|
||||
import { roles } from '$lib/consts';
|
||||
import { getToken } from '$lib/utils/auth';
|
||||
import { getToken, hasRole, roles } from '$lib/utils/auth';
|
||||
import { needsAdminTotp } from '$lib/utils/totp';
|
||||
import { openModal } from '$lib/stores/modal';
|
||||
import { user } from '$lib/stores/user';
|
||||
@@ -80,7 +79,7 @@
|
||||
const url = new URL(page.url);
|
||||
url.searchParams.set('tab', newPageTab);
|
||||
|
||||
// @ts-expect-error
|
||||
// @ts-expect-error - resolve still works even though it's flagged as an error
|
||||
// eslint-disable-next-line svelte/no-navigation-without-resolve
|
||||
await goto(resolve(url.pathname) + url.search, {
|
||||
replaceState: true,
|
||||
@@ -109,7 +108,7 @@
|
||||
else activeTab = 'pastes';
|
||||
break;
|
||||
case 'settings':
|
||||
if (isOwner || $user?.roles?.some((r) => r === 255 || r === 1)) {
|
||||
if (isOwner || ($user?.roles && (hasRole($user.roles, 2) || hasRole($user.roles, 4)))) {
|
||||
activeTab = 'settings';
|
||||
} else activeTab = 'pastes';
|
||||
break;
|
||||
@@ -123,10 +122,9 @@
|
||||
}
|
||||
|
||||
const roleOptions = [
|
||||
{ label: 'Member', value: 0 },
|
||||
{ label: 'Moderator', value: 1 },
|
||||
{ label: 'Administrator', value: 255 },
|
||||
{ label: 'Banned', value: 403 }
|
||||
{ label: 'Member', value: 1 },
|
||||
{ label: 'Moderator', value: 2 },
|
||||
{ label: 'Administrator', value: 4 }
|
||||
];
|
||||
|
||||
async function fetchPage(pageNum: number) {
|
||||
@@ -147,11 +145,11 @@
|
||||
loading = false;
|
||||
}
|
||||
|
||||
async function handleUserUpdate(displayName?: string, selectedRoles?: number[]) {
|
||||
async function handleUserUpdate(displayName?: string, selectedRoles?: number) {
|
||||
loading = true;
|
||||
modalError = '';
|
||||
const token = getToken();
|
||||
const currentRoles = data.user?.roles ?? [];
|
||||
const currentRoles = data.user?.roles ?? 0;
|
||||
const nextRoles = selectedRoles ?? currentRoles;
|
||||
let totpcode = '';
|
||||
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles)) {
|
||||
@@ -363,15 +361,22 @@
|
||||
}
|
||||
|
||||
async function openEditRoles() {
|
||||
const currentRoleBitfield = data.user?.roles ?? 0;
|
||||
const selectedValues: number[] = [];
|
||||
if (hasRole(currentRoleBitfield, roles.User)) selectedValues.push(roles.User);
|
||||
if (hasRole(currentRoleBitfield, roles.Moderator)) selectedValues.push(roles.Moderator);
|
||||
if (hasRole(currentRoleBitfield, roles.Admin)) selectedValues.push(roles.Admin);
|
||||
|
||||
const value = await openModal({
|
||||
mode: 'multiselect',
|
||||
title: 'Edit User Roles',
|
||||
items: roleOptions,
|
||||
initialValue: data.user?.roles,
|
||||
initialValue: selectedValues,
|
||||
cancelValue: null
|
||||
});
|
||||
if (!Array.isArray(value)) return;
|
||||
await handleUserUpdate(undefined, value as number[]);
|
||||
const bitfield = value.reduce((acc, val) => acc | val, 0);
|
||||
await handleUserUpdate(undefined, bitfield);
|
||||
}
|
||||
|
||||
async function openDeleteAccount() {
|
||||
@@ -450,20 +455,24 @@
|
||||
>
|
||||
<div class="relative w-[95%] max-w-5xl rounded border-2 border-neutral-800 bg-neutral-900 p-6">
|
||||
<h1 class="flex flex-wrap items-center justify-center gap-4 text-center text-4xl font-bold">
|
||||
{#if data.user?.roles?.includes(403)}
|
||||
{#if data.user?.isBanned}
|
||||
<span
|
||||
class="relative flex h-7 w-7 items-center justify-center overflow-hidden rounded-full"
|
||||
use:tooltip={roles[403]}
|
||||
use:tooltip={'Banned'}
|
||||
>
|
||||
<User class="h-8 w-8 text-neutral-500" />
|
||||
<Ban class="absolute h-7 w-7 text-red-500" />
|
||||
</span>
|
||||
{:else if data.user?.roles?.includes(1) || data.user?.roles?.includes(255)}
|
||||
{#if data.user?.roles?.length}
|
||||
<span use:tooltip={roles[Math.max(...data.user.roles) as keyof typeof roles]}>
|
||||
<ShieldUser class="h-8 w-8 text-neutral-400" />
|
||||
</span>
|
||||
{/if}
|
||||
{:else if data.user?.roles && (hasRole(data.user.roles, roles.Admin) || hasRole(data.user.roles, roles.Moderator))}
|
||||
<span
|
||||
use:tooltip={hasRole(data.user.roles, roles.Admin)
|
||||
? 'Admin'
|
||||
: hasRole(data.user.roles, roles.Moderator)
|
||||
? 'Moderator'
|
||||
: 'User'}
|
||||
>
|
||||
<ShieldUser class="h-8 w-8 text-neutral-400" />
|
||||
</span>
|
||||
{:else}
|
||||
<span use:tooltip={'User'}>
|
||||
<User class="h-8 w-8 text-neutral-400" />
|
||||
@@ -511,7 +520,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if !isOwner && !$user?.roles?.some((r) => r === 403)}
|
||||
{#if !isOwner && !$user?.isBanned}
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
@@ -531,7 +540,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
<div class="mt-8 flex w-full border-b border-neutral-800">
|
||||
{#if isOwner || $user?.roles?.some((r) => r === 255 || r === 1)}
|
||||
{#if isOwner || ($user?.roles && (hasRole($user.roles, roles.Admin) || hasRole($user.roles, roles.Moderator)))}
|
||||
<button
|
||||
class="border-b-2 px-4 py-2 font-medium transition-colors hover:text-white {activeTab ===
|
||||
'settings'
|
||||
@@ -685,7 +694,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if $user?.roles?.some((r) => r === 255)}
|
||||
{#if $user?.roles && hasRole($user.roles, roles.Admin)}
|
||||
<div class="col-span-2 {isOwner ? 'md:col-span-1' : ''}">
|
||||
<div class="h-full rounded border border-neutral-800 bg-neutral-900/50 p-6">
|
||||
<div class="mb-6 flex items-start">
|
||||
@@ -699,7 +708,15 @@
|
||||
<div class="flex flex-col">
|
||||
<span class="text-sm font-medium text-neutral-200">User Roles</span>
|
||||
<span class="text-xs text-neutral-500"
|
||||
>{data.user?.roles?.length ?? 0} roles assigned</span
|
||||
>{(() => {
|
||||
let count = 0;
|
||||
if (data.user?.roles) {
|
||||
if (hasRole(data.user.roles, roles.User)) count++;
|
||||
if (hasRole(data.user.roles, roles.Moderator)) count++;
|
||||
if (hasRole(data.user.roles, roles.Admin)) count++;
|
||||
}
|
||||
return count;
|
||||
})()} roles assigned</span
|
||||
>
|
||||
</div>
|
||||
<button
|
||||
@@ -857,7 +874,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if isOwner || $user?.roles?.some((r) => r === 255)}
|
||||
{#if isOwner || ($user?.roles && hasRole($user.roles, roles.Admin))}
|
||||
<div class="col-span-2">
|
||||
<div class="rounded border border-red-900/30 bg-red-900/10 p-6">
|
||||
<div class="flex items-start">
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { error, redirect } from '@sveltejs/kit';
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
import { getServerToken } from '$lib/utils/auth';
|
||||
|
||||
export const load = async ({ params, fetch, cookies }: RequestEvent) => {
|
||||
const token = getServerToken(cookies);
|
||||
const uuid = (params as Record<string, string | undefined>).uuid;
|
||||
|
||||
if (!uuid) throw error(404, 'User not found');
|
||||
|
||||
const res = await fetch(`${apiUrl}/api/user/uuid/${uuid}`, {
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : undefined
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const { message } = await res.json().catch(() => ({}));
|
||||
throw error(res.status, message ?? 'Request failed');
|
||||
}
|
||||
|
||||
const { user } = (await res.json()) as { user: { username: string } };
|
||||
throw redirect(302, `/user/${encodeURIComponent(user.username)}`);
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import { apiUrl } from '$lib/server/api';
|
||||
import { extractError } from '$lib/utils/misc';
|
||||
import { error } from '@sveltejs/kit';
|
||||
|
||||
export const load = async ({ url, request }) => {
|
||||
const token = url.searchParams.get('token');
|
||||
if (token) {
|
||||
const headers = new Headers(request.headers);
|
||||
const res = await fetch(`${apiUrl}/api/auth/verify-email?token=${token}`, { headers });
|
||||
if (!res.ok) {
|
||||
const json = await res.json().catch();
|
||||
const message = extractError(json);
|
||||
throw error(res.status, message ?? 'Request failed');
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
<main
|
||||
class="flex min-h-[calc(100vh-120px)] w-full flex-col items-center justify-center pt-5 pb-5 text-white"
|
||||
>
|
||||
<div
|
||||
class="w-[95%] max-w-7xl rounded border-2
|
||||
border-neutral-800 bg-neutral-900 p-6 text-center"
|
||||
>
|
||||
<h1 class="mb-4 text-4xl font-bold">Email verified.</h1>
|
||||
<p class="mb-2 text-lg">You may close this page.</p>
|
||||
</div>
|
||||
</main>
|
||||
@@ -16,7 +16,8 @@ const allowedHosts = process.env.VITE_ALLOWED_HOSTS
|
||||
export default defineConfig({
|
||||
plugins: [tailwindcss(), sveltekit()],
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(pkg.version)
|
||||
__APP_VERSION__: JSON.stringify(pkg.version),
|
||||
COMMIT_HASH: JSON.stringify(process.env.GIT_COMMIT_HASH || 'unknown')
|
||||
},
|
||||
server: {
|
||||
host: true,
|
||||
|
||||
@@ -32,11 +32,10 @@ namespace SharpbinV3.Server.Authentication
|
||||
new("username", apiKey.User.Username ?? ""),
|
||||
new("displayname", apiKey.User.DisplayName ?? ""),
|
||||
new("totp_enabled", (apiKey.User.Totp != null).ToString()),
|
||||
new("roles", ((int)apiKey.User.Roles).ToString()),
|
||||
new("is_banned", apiKey.User.IsBanned.ToString()),
|
||||
};
|
||||
|
||||
if (apiKey.User.Roles != null)
|
||||
claims.AddRange(apiKey.User.Roles.Select(r => new Claim(ClaimTypes.Role, r.ToString())));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, AuthSchemes.ApiKey);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, AuthSchemes.ApiKey);
|
||||
|
||||
@@ -25,9 +25,13 @@ namespace SharpbinV3.Server.Authorization
|
||||
if (_requireAuth && !isAuthenticated)
|
||||
return Task.CompletedTask;
|
||||
|
||||
var isBanned = context.User.Claims.Any(c => (c.Type == ClaimTypes.Role || c.Type == "role") && c.Value == "403");
|
||||
var isBanned =
|
||||
bool.TryParse(context.User.Claims.FirstOrDefault(c => c.Type == "is_banned")?.Value, out var parsedIsBanned) && parsedIsBanned;
|
||||
|
||||
if (httpContext?.GetApiKeyFromContext()?.User?.Roles?.Contains(403) == true)
|
||||
if (!isBanned && httpContext?.GetJwtUser()?.IsBanned == true)
|
||||
isBanned = true;
|
||||
|
||||
if (httpContext?.GetApiKeyFromContext()?.User?.IsBanned == true)
|
||||
isBanned = true;
|
||||
|
||||
if (!isBanned)
|
||||
|
||||
@@ -62,6 +62,9 @@ namespace SharpbinV3.Server.Controllers
|
||||
return BadRequest(new { success = false, message = "Display name should not exceed 26 characters." });
|
||||
|
||||
var user = await _authService.CreateUser(request.Username, request.Password, request.Email, request.DisplayName);
|
||||
if (!string.IsNullOrWhiteSpace(user.Email))
|
||||
await _authService.SendEmailVerification(user);
|
||||
|
||||
return Ok(
|
||||
new
|
||||
{
|
||||
@@ -74,6 +77,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
DisplayName = user.DisplayName,
|
||||
Email = user.Email,
|
||||
Roles = user.Roles,
|
||||
IsBanned = user.IsBanned,
|
||||
Visibility = user.Visibility,
|
||||
LastLogin = user.LastLogin,
|
||||
},
|
||||
@@ -322,5 +326,16 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
return Ok(new { success = true, message = "API key deleted." });
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Route("verify-email")]
|
||||
public async Task<IActionResult> VerifyEmail(string token)
|
||||
{
|
||||
(bool verifiedEmail, string message) = await _authService.VerifyEmailVerificationToken(token);
|
||||
if (verifiedEmail)
|
||||
return Ok(new { success = true, message });
|
||||
else
|
||||
return BadRequest(new { success = false, message });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
using SharpbinV3.Server.DTOs.Paste;
|
||||
using SharpbinV3.Server.DTOs.Report;
|
||||
using SharpbinV3.Server.DTOs.User;
|
||||
@@ -38,7 +39,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
public async Task<IActionResult> CreatePaste(
|
||||
string title = "",
|
||||
string syntax = "plaintext",
|
||||
int visibility = 0,
|
||||
Visibility visibility = Visibility.Public,
|
||||
long expiresAt = 0,
|
||||
string? verificationToken = null
|
||||
)
|
||||
@@ -85,21 +86,24 @@ namespace SharpbinV3.Server.Controllers
|
||||
Size = paste.Size,
|
||||
TrueSize = paste.TrueSize,
|
||||
ExpiresAt = paste.ExpiresAt,
|
||||
Visibility = paste.Visibility,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("NoLimit")]
|
||||
[Route("{id}")]
|
||||
public async Task<IActionResult> GetPasteByID(string id)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||
return NotFound(new { success = false, message = "Paste not found" });
|
||||
|
||||
var jwtUser = HttpContext.GetJwtUser();
|
||||
|
||||
int? reportCount = null;
|
||||
if (jwtUser != null && jwtUser.Roles.Any(r => r == 1 || r == 255))
|
||||
if (jwtUser != null && (jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator)))
|
||||
{
|
||||
var query = new ReportQuery { PastePID = paste.PID };
|
||||
reportCount = await _reportService.GetReportCount(query);
|
||||
@@ -134,6 +138,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
DisplayName = paste.User.DisplayName,
|
||||
Visibility = paste.User.Visibility,
|
||||
Roles = paste.User.Roles,
|
||||
IsBanned = paste.User.IsBanned,
|
||||
}
|
||||
: null,
|
||||
},
|
||||
@@ -142,11 +147,12 @@ namespace SharpbinV3.Server.Controllers
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[EnableRateLimiting("NoLimit")]
|
||||
[Route("{id}/raw")]
|
||||
public async Task<IActionResult> GetRawPasteByID(string id)
|
||||
{
|
||||
var paste = await _pasteService.Get(id);
|
||||
if (paste == null)
|
||||
if (paste == null || paste.ExpiresAt != 0 && paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
|
||||
return NotFound();
|
||||
if (paste.IsCompressed)
|
||||
Response.Headers.Append("Content-Encoding", "gzip");
|
||||
@@ -169,11 +175,9 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to edit this paste." });
|
||||
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
|
||||
bool result = await _pasteService.EditText(paste, content);
|
||||
if (!result)
|
||||
@@ -192,12 +196,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to modify this paste." });
|
||||
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
|
||||
if (request.Title != null)
|
||||
paste.Title = request.Title;
|
||||
if (request.Syntax != null)
|
||||
@@ -251,11 +254,9 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||
if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this paste." });
|
||||
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
|
||||
bool result = await _pasteService.Delete(paste);
|
||||
if (!result)
|
||||
@@ -280,6 +281,11 @@ namespace SharpbinV3.Server.Controllers
|
||||
)
|
||||
return Unauthorized(new { success = false, message = "Invalid API key." });
|
||||
|
||||
if (paste.AuthorUUID != HttpContext.GetJwtUser()?.UUID)
|
||||
return Ok(new { success = true, message = "View not recorded for author's own paste." });
|
||||
if (paste.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() && paste.Visibility != 0)
|
||||
return Ok(new { success = true, message = "View not recorded for expired paste." });
|
||||
|
||||
var result = await _pasteService.RecordView(paste, HttpContext);
|
||||
|
||||
if (result.paste is null && !result.alreadyExists)
|
||||
@@ -353,7 +359,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to modify this report." });
|
||||
|
||||
@@ -387,13 +393,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||
if (report.ReporterUUID != user.UUID && !hasPrivilegedRole)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this report." });
|
||||
|
||||
if (user.Roles.Contains(255) && !user.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
|
||||
bool result = await _reportService.DeleteReport(report);
|
||||
if (!result)
|
||||
return StatusCode(500, new { success = false, message = "An error occurred while deleting the report." });
|
||||
@@ -431,6 +434,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
DisplayName = p.User.DisplayName,
|
||||
Visibility = p.User.Visibility,
|
||||
Roles = p.User.Roles,
|
||||
IsBanned = p.User.IsBanned,
|
||||
}
|
||||
: null,
|
||||
})
|
||||
|
||||
@@ -24,7 +24,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (report is null)
|
||||
return NotFound(new { success = false, message = "Report not found." });
|
||||
|
||||
var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
|
||||
var hasPrivilegedRole = user.Roles.HasFlag(Role.Admin) || user.Roles.HasFlag(Role.Moderator);
|
||||
if (!hasPrivilegedRole && report.ReporterUUID != user.UUID)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view this report." });
|
||||
|
||||
@@ -59,7 +59,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
public async Task<IActionResult> UpdateReport(int reportId, [FromBody] ReportUpdateDto request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to update reports." });
|
||||
|
||||
var report = await reportService.GetReportByID(reportId);
|
||||
@@ -127,7 +127,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
public async Task<IActionResult> GetReportsForPastes([FromQuery] ReportQuery request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view pastes." });
|
||||
|
||||
var query = request with { Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100), UserUUID = null };
|
||||
@@ -157,7 +157,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
public async Task<IActionResult> GetReportsForUsers([FromQuery] ReportQuery request)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view users." });
|
||||
|
||||
var query = request with
|
||||
@@ -200,7 +200,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
)
|
||||
{
|
||||
var user = HttpContext.GetJwtUser()!;
|
||||
if (!user.Roles.Contains(1) && !user.Roles.Contains(255))
|
||||
if (!user.Roles.HasFlag(Role.Admin) && !user.Roles.HasFlag(Role.Moderator))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view reports." });
|
||||
|
||||
var query = new ReportQuery
|
||||
|
||||
@@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
using SharpbinV3.Server.DTOs;
|
||||
using SharpbinV3.Server.DTOs.Paste;
|
||||
using SharpbinV3.Server.DTOs.Report;
|
||||
@@ -63,7 +64,6 @@ namespace SharpbinV3.Server.Controllers
|
||||
[EnableRateLimiting("Strict")]
|
||||
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
|
||||
{
|
||||
Console.WriteLine($"{ModelState.IsValid}");
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
@@ -74,23 +74,23 @@ namespace SharpbinV3.Server.Controllers
|
||||
return NotFound(new { success = false, message = "User not found." });
|
||||
|
||||
if (
|
||||
(user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
|
||||
|| (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID)
|
||||
(user.Roles.HasFlag(Role.Admin) && !jwtUser.Roles.HasFlag(Role.Admin))
|
||||
|| (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
|
||||
)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to modify this user." });
|
||||
|
||||
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
|
||||
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
|
||||
if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self
|
||||
if (jwtUser.Roles.HasFlag(Role.Admin) || user.UUID == jwtUser.UUID) // only admins or self
|
||||
{
|
||||
user.Email = updatedUser.Email ?? user.Email;
|
||||
user.Visibility = updatedUser.Visibility ?? user.Visibility;
|
||||
}
|
||||
if (jwtUser.Roles.Contains(255))
|
||||
if (jwtUser.Roles.HasFlag(Role.Admin))
|
||||
{
|
||||
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled)
|
||||
if (jwtUser.TotpEnabled)
|
||||
{
|
||||
if (
|
||||
string.IsNullOrEmpty(updatedUser.TotpCode)
|
||||
@@ -100,7 +100,9 @@ namespace SharpbinV3.Server.Controllers
|
||||
return Unauthorized(new { message = "Invalid TOTP code." });
|
||||
}
|
||||
}
|
||||
|
||||
user.Roles = updatedUser.Roles ?? user.Roles;
|
||||
user.IsBanned = updatedUser.IsBanned ?? user.IsBanned;
|
||||
}
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
@@ -118,9 +120,9 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (user == null)
|
||||
return NotFound(new { success = false, message = "User not found." });
|
||||
|
||||
if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID)
|
||||
if (!jwtUser.Roles.HasFlag(Role.Admin) && user.UUID != jwtUser.UUID)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to delete this user." });
|
||||
if (jwtUser.Roles.Contains(255) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
if (jwtUser.Roles.HasFlag(Role.Admin) && !jwtUser.TotpEnabled && _authSettings.Admins_Require_2FA)
|
||||
return StatusCode(403, new { success = false, message = "2FA is required to perform this action." });
|
||||
|
||||
if (jwtUser.TotpEnabled)
|
||||
@@ -259,7 +261,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
if (user == null)
|
||||
return NotFound(new { success = false, message = "User not found." });
|
||||
|
||||
if (!jwtUser.Roles.Any(r => r == 1 || r == 255))
|
||||
if (!jwtUser.Roles.HasFlag(Role.Admin))
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's reports." });
|
||||
|
||||
var query = request with { UserUUID = user.UUID, Page = Math.Max(request.Page, 1), PageSize = Math.Clamp(request.PageSize, 1, 100) };
|
||||
@@ -293,7 +295,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
return NotFound(new { success = false, message = "User not found." });
|
||||
|
||||
var isOwner = user.UUID == jwtUser.UUID;
|
||||
var hasPrivilegedRole = jwtUser.Roles.Any(r => r == 1 || r == 255);
|
||||
var hasPrivilegedRole = jwtUser.Roles.HasFlag(Role.Admin) || jwtUser.Roles.HasFlag(Role.Moderator);
|
||||
if (!isOwner && !hasPrivilegedRole)
|
||||
return StatusCode(403, new { success = false, message = "You do not have permission to view this user's submitted reports." });
|
||||
|
||||
@@ -324,10 +326,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
var pasteQuery = _db.Pastes.AsNoTracking().Where(p => p.AuthorUUID == user.UUID);
|
||||
if (!isAuthenticatedUser)
|
||||
{
|
||||
if (user.Visibility == 2)
|
||||
if (user.Visibility == Visibility.Private && (!user.Roles.HasFlag(Role.Admin) || !user.Roles.HasFlag(Role.Moderator)))
|
||||
return NotFound();
|
||||
else if (user.Visibility != 1)
|
||||
pasteQuery = pasteQuery.Where(p => p.Visibility == 0);
|
||||
else if (user.Visibility != Visibility.Unlisted)
|
||||
pasteQuery = pasteQuery.Where(p => p.Visibility == Visibility.Public);
|
||||
}
|
||||
|
||||
if (page < 1)
|
||||
@@ -389,8 +391,10 @@ namespace SharpbinV3.Server.Controllers
|
||||
CreatedAt = user.CreatedAt,
|
||||
DisplayName = user.DisplayName,
|
||||
Email = user.Email,
|
||||
EmailVerified = user.EmailVerified,
|
||||
LastLogin = user.LastLogin,
|
||||
Roles = user.Roles,
|
||||
IsBanned = user.IsBanned,
|
||||
Visibility = user.Visibility,
|
||||
},
|
||||
Pastes = pastes,
|
||||
@@ -418,6 +422,7 @@ namespace SharpbinV3.Server.Controllers
|
||||
CreatedAt = user.CreatedAt,
|
||||
DisplayName = user.DisplayName,
|
||||
Roles = user.Roles,
|
||||
IsBanned = user.IsBanned,
|
||||
Visibility = user.Visibility,
|
||||
},
|
||||
Pastes = pastes,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
using SharpbinV3.Server.DTOs.User;
|
||||
|
||||
namespace SharpbinV3.Server.DTOs.Paste
|
||||
@@ -13,7 +14,7 @@ namespace SharpbinV3.Server.DTOs.Paste
|
||||
public long TrueSize { get; set; }
|
||||
public bool IsCompressed { get; set; }
|
||||
public int Views { get; set; }
|
||||
public int Visibility { get; set; }
|
||||
public Visibility Visibility { get; set; }
|
||||
public long? EditedAt { get; set; }
|
||||
public long ExpiresAt { get; set; }
|
||||
public int? ReportCount { get; set; }
|
||||
@@ -29,6 +30,7 @@ namespace SharpbinV3.Server.DTOs.Paste
|
||||
public long Size { get; set; }
|
||||
public long TrueSize { get; set; }
|
||||
public long ExpiresAt { get; set; }
|
||||
public Visibility Visibility { get; set; }
|
||||
}
|
||||
|
||||
public class PasteOptionsDto
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
namespace SharpbinV3.Server.DTOs.Paste
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
|
||||
namespace SharpbinV3.Server.DTOs.Paste
|
||||
{
|
||||
public class UpdatePasteDto
|
||||
{
|
||||
public string? Title { get; set; }
|
||||
public string? Syntax { get; set; }
|
||||
public int? Visibility { get; set; }
|
||||
public Visibility? Visibility { get; set; }
|
||||
public long? ExpiresAt { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.RegularExpressions;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
|
||||
namespace SharpbinV3.Server.DTOs
|
||||
{
|
||||
@@ -7,8 +9,9 @@ namespace SharpbinV3.Server.DTOs
|
||||
{
|
||||
public string? DisplayName { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public int? Visibility { get; set; } = 0;
|
||||
public int[]? Roles { get; set; }
|
||||
public Visibility? Visibility { get; set; } = Data.Enums.Visibility.Public;
|
||||
public Role? Roles { get; set; }
|
||||
public bool? IsBanned { get; set; }
|
||||
public string? TotpCode { get; set; }
|
||||
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
@@ -34,19 +37,14 @@ namespace SharpbinV3.Server.DTOs
|
||||
}
|
||||
if (Visibility != null && Visibility.HasValue)
|
||||
{
|
||||
if (Visibility < 0 || Visibility > 2)
|
||||
results.Add(new ValidationResult("Visibility must be between 0 and 2.", [nameof(Visibility)]));
|
||||
if (!Enum.IsDefined(typeof(Visibility), Visibility.Value))
|
||||
results.Add(new ValidationResult($"Invalid visibility: {Visibility.Value}.", [nameof(Visibility)]));
|
||||
}
|
||||
if (Roles != null && Roles.Length > 0)
|
||||
if (Roles != null && Roles.HasValue)
|
||||
{
|
||||
if (Roles.Length == 0)
|
||||
results.Add(new ValidationResult("Roles cannot be an empty array.", [nameof(Roles)]));
|
||||
int[] validRoles = [0, 1, 255, 403];
|
||||
foreach (var role in Roles)
|
||||
{
|
||||
if (!validRoles.Contains(role))
|
||||
results.Add(new ValidationResult($"Invalid role: {role}.", [nameof(Roles)]));
|
||||
}
|
||||
int validBits = Enum.GetValues(typeof(Role)).Cast<Role>().Aggregate(0, (acc, role) => acc | (int)role);
|
||||
if ((((int)Roles.Value) & validBits) != (int)Roles.Value || Roles.Value == 0)
|
||||
results.Add(new ValidationResult($"Invalid role: {Roles.Value}.", [nameof(Roles)]));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
|
||||
namespace SharpbinV3.Server.DTOs.User
|
||||
{
|
||||
public class UserSimpleDto
|
||||
@@ -7,13 +10,15 @@ namespace SharpbinV3.Server.DTOs.User
|
||||
public long CreatedAt { get; set; }
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string? DisplayName { get; set; }
|
||||
public int[] Roles { get; set; } = [];
|
||||
public int Visibility { get; set; }
|
||||
public Role Roles { get; set; } = Role.User;
|
||||
public bool IsBanned { get; set; } = false;
|
||||
public Visibility Visibility { get; set; }
|
||||
}
|
||||
|
||||
public class UserResponseDto : UserSimpleDto
|
||||
{
|
||||
public string? Email { get; set; }
|
||||
public bool EmailVerified { get; set; } = false;
|
||||
public long? LastLogin { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ namespace SharpbinV3.Server.Data
|
||||
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
|
||||
public DbSet<Report> Reports => Set<Report>();
|
||||
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
|
||||
public DbSet<EmailVerificationToken> EmailVerificationTokens => Set<EmailVerificationToken>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -63,6 +64,12 @@ namespace SharpbinV3.Server.Data
|
||||
.WithMany(u => u.ApiKeys)
|
||||
.HasForeignKey(a => a.UserUUID)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
modelBuilder.Entity<EmailVerificationToken>()
|
||||
.HasOne(a => a.User)
|
||||
.WithMany(u => u.EmailVerificationTokens)
|
||||
.HasForeignKey(a => a.UserUUID)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Data.Entities
|
||||
{
|
||||
public enum EmailTokenType
|
||||
{
|
||||
VerifyEmail,
|
||||
ResetPassword,
|
||||
ChangeEmail,
|
||||
DeleteAccount,
|
||||
}
|
||||
|
||||
public sealed class EmailVerificationToken
|
||||
{
|
||||
[Key]
|
||||
public Guid UUID { get; set; } = Guid.CreateVersion7();
|
||||
public required Guid UserUUID { get; set; }
|
||||
public User User { get; set; } = null!;
|
||||
public required string TokenHash { get; set; }
|
||||
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
public long ExpiresAt { get; set; }
|
||||
public required EmailTokenType Type { get; set; }
|
||||
public bool Used { get; set; } = false;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Data.Entities
|
||||
@@ -33,7 +34,7 @@ namespace SharpbinV3.Server.Data.Entities
|
||||
|
||||
public int Views { get; set; }
|
||||
public string? Syntax { get; set; }
|
||||
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private (encrypted pastes handled on frontend)
|
||||
public Visibility Visibility { get; set; } = Visibility.Public;
|
||||
|
||||
public long ExpiresAt { get; set; } // timestamp of when the paste expires, or 0 for never
|
||||
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Data.Entities
|
||||
{
|
||||
|
||||
[Flags]
|
||||
public enum Role
|
||||
{
|
||||
User = 1,
|
||||
Moderator = 2,
|
||||
Admin = 4
|
||||
}
|
||||
|
||||
[Index(nameof(UID))]
|
||||
[Index(nameof(UUID), IsUnique = true)]
|
||||
public sealed class User
|
||||
@@ -15,15 +25,20 @@ namespace SharpbinV3.Server.Data.Entities
|
||||
public required string PasswordHash { get; set; }
|
||||
|
||||
public string? Email { get; set; }
|
||||
public bool EmailVerified { get; set; } = false;
|
||||
|
||||
public string? DisplayName { get; set; }
|
||||
public long? LastLogin { get; set; }
|
||||
|
||||
public int[] Roles { get; set; } = [0]; // 0 = regular user, 1 = moderator, 255 = admin
|
||||
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
|
||||
public Role Roles { get; set; } = Role.User;
|
||||
public bool IsBanned { get; set; } = false;
|
||||
|
||||
public Visibility Visibility { get; set; } = Visibility.Public;
|
||||
public List<Paste> Pastes { get; set; } = [];
|
||||
public List<RefreshToken> RefreshTokens { get; set; } = [];
|
||||
public List<Report> Reports { get; set; } = [];
|
||||
public List<ApiKey> ApiKeys { get; set; } = [];
|
||||
public List<EmailVerificationToken> EmailVerificationTokens { get; set; } = [];
|
||||
public UserTotp? Totp { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace SharpbinV3.Server.Data.Enums
|
||||
{
|
||||
public enum Visibility
|
||||
{
|
||||
Public = 0,
|
||||
Unlisted = 1,
|
||||
Private = 2
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace SharpbinV3.Server
|
||||
{
|
||||
/// <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))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(line) || line.StartsWith("#"))
|
||||
continue;
|
||||
var parts = line.Split('=', StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
if (parts.Length != 2)
|
||||
continue;
|
||||
|
||||
Environment.SetEnvironmentVariable(parts[0], parts[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{{TITLE}}</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: 'IBM Plex Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
background-color: #0a0a0a;
|
||||
color: #ffffff;
|
||||
}
|
||||
.container {
|
||||
max-width: 600px;
|
||||
margin: 40px auto;
|
||||
background-color: #171717;
|
||||
border: 2px solid #262626;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.header {
|
||||
background-color: #171717;
|
||||
padding: 32px 30px;
|
||||
border-bottom: 1px solid #262626;
|
||||
}
|
||||
.header h1 {
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
color: #ffffff;
|
||||
}
|
||||
.content {
|
||||
padding: 32px 30px;
|
||||
}
|
||||
.content h2 {
|
||||
margin: 0 0 20px 0;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
}
|
||||
.content p {
|
||||
margin: 0 0 16px 0;
|
||||
font-size: 15px;
|
||||
line-height: 1.6;
|
||||
color: #d4d4d4;
|
||||
}
|
||||
.button {
|
||||
display: inline-block;
|
||||
padding: 12px 24px;
|
||||
background-color: #404040;
|
||||
color: #ffffff !important;
|
||||
text-decoration: none;
|
||||
border-radius: 6px;
|
||||
font-weight: 500;
|
||||
font-size: 15px;
|
||||
margin: 12px 0;
|
||||
}
|
||||
.button:hover {
|
||||
background-color: #525252;
|
||||
}
|
||||
.link-box {
|
||||
background-color: #262626;
|
||||
padding: 16px;
|
||||
border-radius: 6px;
|
||||
margin: 16px 0;
|
||||
word-break: break-all;
|
||||
}
|
||||
.link-box a {
|
||||
color: #3b82f6;
|
||||
text-decoration: underline;
|
||||
font-size: 14px;
|
||||
}
|
||||
.footer {
|
||||
padding: 24px 30px;
|
||||
text-align: center;
|
||||
background-color: #0a0a0a;
|
||||
border-top: 1px solid #262626;
|
||||
}
|
||||
.footer p {
|
||||
margin: 0 0 8px 0;
|
||||
font-size: 13px;
|
||||
color: #737373;
|
||||
}
|
||||
.footer .brand {
|
||||
font-weight: 600;
|
||||
color: #ffffff;
|
||||
font-size: 15px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>Sharpbin</h1>
|
||||
</div>
|
||||
<div class="content">
|
||||
{{CONTENT}}
|
||||
</div>
|
||||
<div class="footer">
|
||||
<p class="brand">Sharpbin</p>
|
||||
<p>This is an automated email. Please do not reply to this message.</p>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
<h2>Verify Your Email Address</h2>
|
||||
<p>Hi <strong>{{USERNAME}}</strong>,</p>
|
||||
<p>Thank you for signing up for Sharpbin. To complete your registration, please verify your email address by clicking the button below.</p>
|
||||
<p style="text-align: center;">
|
||||
<a href="{{VERIFICATION_URL}}" class="button">Verify Email Address</a>
|
||||
</p>
|
||||
<p>If the button doesn't work, you can copy and paste this link into your browser:</p>
|
||||
<div class="link-box">
|
||||
<a href="{{VERIFICATION_URL}}">{{VERIFICATION_URL}}</a>
|
||||
</div>
|
||||
<p><strong>This link will expire in 24 hours.</strong></p>
|
||||
<p>If you didn't create an account with Sharpbin, you can safely ignore this email.</p>
|
||||
@@ -19,6 +19,18 @@ namespace SharpbinV3.Server.Extensions
|
||||
|
||||
private const string ApiKeyContextKey = "ApiKey";
|
||||
|
||||
private static string? GetClaimValue(IEnumerable<Claim> claims, params string[] claimTypes)
|
||||
{
|
||||
foreach (var claimType in claimTypes)
|
||||
{
|
||||
var value = claims.FirstOrDefault(c => c.Type == claimType)?.Value;
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
return value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static string? GetApiKey(this HttpContext context)
|
||||
{
|
||||
var apiKeyHeader = context.Request.Headers["X-API-Key"].FirstOrDefault();
|
||||
@@ -54,19 +66,20 @@ namespace SharpbinV3.Server.Extensions
|
||||
if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
|
||||
return null;
|
||||
|
||||
var claims = context.User.Claims;
|
||||
var claims = context.User.Claims.ToArray();
|
||||
|
||||
var uuidClaim = claims.FirstOrDefault(c => c.Type == "uuid")?.Value;
|
||||
var uuidClaim = GetClaimValue(claims, "uuid");
|
||||
if (string.IsNullOrEmpty(uuidClaim) || !Guid.TryParse(uuidClaim, out var uuid))
|
||||
return null;
|
||||
|
||||
var username = claims.FirstOrDefault(c => c.Type == "username")?.Value ?? "";
|
||||
var displayName = claims.FirstOrDefault(c => c.Type == "displayname")?.Value ?? "";
|
||||
var totpEnabled = claims.FirstOrDefault(c => c.Type == "totp_enabled")?.Value == "True";
|
||||
var username = GetClaimValue(claims, "username") ?? "";
|
||||
var displayName = GetClaimValue(claims, "displayname") ?? "";
|
||||
var totpEnabled = bool.TryParse(GetClaimValue(claims, "totp_enabled"), out var parsedTotpEnabled) && parsedTotpEnabled;
|
||||
var isBanned = bool.TryParse(GetClaimValue(claims, "is_banned"), out var parsedIsBanned) && parsedIsBanned;
|
||||
var rolesClaim = GetClaimValue(claims, "roles", "role", ClaimTypes.Role);
|
||||
var roles = int.TryParse(rolesClaim, out var roleInt) ? (Role)roleInt : Role.User;
|
||||
|
||||
var roles = claims.Where(c => c.Type == ClaimTypes.Role).Select(c => int.TryParse(c.Value, out var r) ? r : 0).ToArray();
|
||||
|
||||
var expClaim = claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value;
|
||||
var expClaim = GetClaimValue(claims, JwtRegisteredClaimNames.Exp, ClaimTypes.Expiration, "exp");
|
||||
var expires =
|
||||
expClaim != null && long.TryParse(expClaim, out var expUnix)
|
||||
? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime
|
||||
@@ -78,7 +91,8 @@ namespace SharpbinV3.Server.Extensions
|
||||
Username = username,
|
||||
DisplayName = displayName,
|
||||
TotpEnabled = totpEnabled,
|
||||
Roles = roles.Length > 0 ? roles : [0],
|
||||
Roles = roles,
|
||||
IsBanned = isBanned,
|
||||
Expires = expires,
|
||||
};
|
||||
}
|
||||
|
||||
+453
@@ -0,0 +1,453 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SharpbinV3.Server.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260221080317_EmailVerificationToken")]
|
||||
partial class EmailVerificationToken
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("KeyHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("LastUsedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("ApiKeys");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("EmailVerificationTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Property<int>("PID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("AuthorUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<byte[]>("Content")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("EditedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("IsCompressed")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("Size")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Syntax")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("TrueSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Views")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("PID");
|
||||
|
||||
b.HasIndex("AuthorUUID");
|
||||
|
||||
b.HasIndex("ExpiresAt");
|
||||
|
||||
b.HasIndex("ID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("PID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Size");
|
||||
|
||||
b.HasIndex("Syntax");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Views");
|
||||
|
||||
b.HasIndex("Visibility");
|
||||
|
||||
b.ToTable("Pastes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ViewedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ViewerHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PastePID", "ViewerHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PasteViews");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("JwtId")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("ReplacedByToken")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Revoked")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("RowVersion")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
|
||||
{
|
||||
b.Property<int>("ReportID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int?>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("ReporterUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("TargetType")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("UpdatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("ReportID");
|
||||
|
||||
b.HasIndex("PastePID");
|
||||
|
||||
b.HasIndex("ReportID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ReporterUUID");
|
||||
|
||||
b.HasIndex("TargetType");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("EmailVerified")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("LastLogin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.PrimitiveCollection<string>("Roles")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int?>("UID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UID");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
|
||||
{
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("EncryptedSecret")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.HasKey("UserUUID");
|
||||
|
||||
b.ToTable("UserTotps");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("ApiKeys")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("EmailVerificationTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Pastes")
|
||||
.HasForeignKey("AuthorUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("PasteViews")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Paste");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("RefreshTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.Navigation("Paste");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithOne("Totp")
|
||||
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Navigation("PasteViews");
|
||||
|
||||
b.Navigation("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Navigation("ApiKeys");
|
||||
|
||||
b.Navigation("EmailVerificationTokens");
|
||||
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
b.Navigation("Reports");
|
||||
|
||||
b.Navigation("Totp");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class EmailVerificationToken : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "EmailVerified",
|
||||
table: "Users",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "EmailVerificationTokens",
|
||||
columns: table => new
|
||||
{
|
||||
UUID = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
TokenHash = table.Column<string>(type: "TEXT", nullable: false),
|
||||
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
ExpiresAt = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
Type = table.Column<int>(type: "INTEGER", nullable: false),
|
||||
Used = table.Column<bool>(type: "INTEGER", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_EmailVerificationTokens", x => x.UUID);
|
||||
table.ForeignKey(
|
||||
name: "FK_EmailVerificationTokens_Users_UserUUID",
|
||||
column: x => x.UserUUID,
|
||||
principalTable: "Users",
|
||||
principalColumn: "UUID",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_EmailVerificationTokens_UserUUID",
|
||||
table: "EmailVerificationTokens",
|
||||
column: "UserUUID");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "EmailVerificationTokens");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "EmailVerified",
|
||||
table: "Users");
|
||||
}
|
||||
}
|
||||
}
|
||||
+455
@@ -0,0 +1,455 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SharpbinV3.Server.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260310055909_FlaggedRolesEnumVisiblity")]
|
||||
partial class FlaggedRolesEnumVisiblity
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.ApiKey", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("KeyHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("LastUsedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("ApiKeys");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.EmailVerificationToken", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("EmailVerificationTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
|
||||
{
|
||||
b.Property<int>("PID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("AuthorUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<byte[]>("Content")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("EditedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("IsCompressed")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("Size")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Syntax")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("TrueSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Views")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("PID");
|
||||
|
||||
b.HasIndex("AuthorUUID");
|
||||
|
||||
b.HasIndex("ExpiresAt");
|
||||
|
||||
b.HasIndex("ID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("PID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Size");
|
||||
|
||||
b.HasIndex("Syntax");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Views");
|
||||
|
||||
b.HasIndex("Visibility");
|
||||
|
||||
b.ToTable("Pastes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.PasteView", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ViewedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ViewerHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PastePID", "ViewerHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PasteViews");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("JwtId")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("ReplacedByToken")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Revoked")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("RowVersion")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Report", b =>
|
||||
{
|
||||
b.Property<int>("ReportID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int?>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("ReporterUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("TargetType")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("UpdatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("ReportID");
|
||||
|
||||
b.HasIndex("PastePID");
|
||||
|
||||
b.HasIndex("ReportID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ReporterUUID");
|
||||
|
||||
b.HasIndex("TargetType");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("EmailVerified")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("IsBanned")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("LastLogin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Roles")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int?>("UID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UID");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.UserTotp", b =>
|
||||
{
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("EncryptedSecret")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.HasKey("UserUUID");
|
||||
|
||||
b.ToTable("UserTotps");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.ApiKey", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
|
||||
.WithMany("ApiKeys")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.EmailVerificationToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
|
||||
.WithMany("EmailVerificationTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
|
||||
.WithMany("Pastes")
|
||||
.HasForeignKey("AuthorUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.PasteView", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Enums.Paste", "Paste")
|
||||
.WithMany("PasteViews")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Paste");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
|
||||
.WithMany("RefreshTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Report", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Enums.Paste", "Paste")
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.Navigation("Paste");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.UserTotp", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Enums.User", "User")
|
||||
.WithOne("Totp")
|
||||
.HasForeignKey("SharpbinV3.Server.Data.Enums.UserTotp", "UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.Paste", b =>
|
||||
{
|
||||
b.Navigation("PasteViews");
|
||||
|
||||
b.Navigation("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Enums.User", b =>
|
||||
{
|
||||
b.Navigation("ApiKeys");
|
||||
|
||||
b.Navigation("EmailVerificationTokens");
|
||||
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
b.Navigation("Reports");
|
||||
|
||||
b.Navigation("Totp");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class FlaggedRolesEnumVisiblity : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<int>(
|
||||
name: "Roles",
|
||||
table: "Users",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "TEXT");
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "IsBanned",
|
||||
table: "Users",
|
||||
type: "INTEGER",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "IsBanned",
|
||||
table: "Users");
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "Roles",
|
||||
table: "Users",
|
||||
type: "TEXT",
|
||||
nullable: false,
|
||||
oldClrType: typeof(int),
|
||||
oldType: "INTEGER");
|
||||
}
|
||||
}
|
||||
}
|
||||
+455
@@ -0,0 +1,455 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
using SharpbinV3.Server.Data;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
[DbContext(typeof(AppDbContext))]
|
||||
[Migration("20260310072309_CorrectNamespaceRename")]
|
||||
partial class CorrectNamespaceRename
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("KeyHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long?>("LastUsedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("ApiKeys");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("EmailVerificationTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Property<int>("PID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("AuthorUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<byte[]>("Content")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("EditedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("IsCompressed")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("Size")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Syntax")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Title")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("TrueSize")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Views")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("PID");
|
||||
|
||||
b.HasIndex("AuthorUUID");
|
||||
|
||||
b.HasIndex("ExpiresAt");
|
||||
|
||||
b.HasIndex("ID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("PID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Size");
|
||||
|
||||
b.HasIndex("Syntax");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("Views");
|
||||
|
||||
b.HasIndex("Visibility");
|
||||
|
||||
b.ToTable("Pastes");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ViewedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("ViewerHash")
|
||||
.IsRequired()
|
||||
.HasMaxLength(64)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("PastePID", "ViewerHash")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("PasteViews");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTimeOffset>("CreatedAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<DateTimeOffset>("ExpiresAt")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("JwtId")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("ReplacedByToken")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Revoked")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("RowVersion")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TokenHash")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
|
||||
{
|
||||
b.Property<int>("ReportID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.HasMaxLength(1000)
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int?>("PastePID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("ReporterUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Status")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("TargetType")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("UpdatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid?>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("ReportID");
|
||||
|
||||
b.HasIndex("PastePID");
|
||||
|
||||
b.HasIndex("ReportID")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("ReporterUUID");
|
||||
|
||||
b.HasIndex("TargetType");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("DisplayName")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<string>("Email")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("EmailVerified")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("IsBanned")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("LastLogin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Roles")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int?>("UID")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Visibility")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UID");
|
||||
|
||||
b.HasIndex("UUID")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("Users");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
|
||||
{
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<byte[]>("EncryptedSecret")
|
||||
.IsRequired()
|
||||
.HasColumnType("BLOB");
|
||||
|
||||
b.HasKey("UserUUID");
|
||||
|
||||
b.ToTable("UserTotps");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("ApiKeys")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("EmailVerificationTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Pastes")
|
||||
.HasForeignKey("AuthorUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.PasteView", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("PasteViews")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Paste");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("RefreshTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Report", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.Paste", "Paste")
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("PastePID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("Reports")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.Navigation("Paste");
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.UserTotp", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithOne("Totp")
|
||||
.HasForeignKey("SharpbinV3.Server.Data.Entities.UserTotp", "UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Navigation("PasteViews");
|
||||
|
||||
b.Navigation("Reports");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
|
||||
{
|
||||
b.Navigation("ApiKeys");
|
||||
|
||||
b.Navigation("EmailVerificationTokens");
|
||||
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
b.Navigation("Reports");
|
||||
|
||||
b.Navigation("Totp");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class CorrectNamespaceRename : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ namespace SharpbinV3.Server.Migrations
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
|
||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.3");
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.ApiKey", b =>
|
||||
{
|
||||
@@ -47,6 +47,38 @@ namespace SharpbinV3.Server.Migrations
|
||||
b.ToTable("ApiKeys");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.Property<Guid>("UUID")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<long>("CreatedAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long>("ExpiresAt")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<string>("TokenHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<int>("Type")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("Used")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<Guid>("UserUUID")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.HasKey("UUID");
|
||||
|
||||
b.HasIndex("UserUUID");
|
||||
|
||||
b.ToTable("EmailVerificationTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.Property<int>("PID")
|
||||
@@ -258,6 +290,12 @@ namespace SharpbinV3.Server.Migrations
|
||||
b.Property<string>("Email")
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.Property<bool>("EmailVerified")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<bool>("IsBanned")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<long?>("LastLogin")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
@@ -265,9 +303,8 @@ namespace SharpbinV3.Server.Migrations
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
|
||||
b.PrimitiveCollection<string>("Roles")
|
||||
.IsRequired()
|
||||
.HasColumnType("TEXT");
|
||||
b.Property<int>("Roles")
|
||||
.HasColumnType("INTEGER");
|
||||
|
||||
b.Property<int?>("UID")
|
||||
.HasColumnType("INTEGER");
|
||||
@@ -317,6 +354,17 @@ namespace SharpbinV3.Server.Migrations
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.EmailVerificationToken", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
.WithMany("EmailVerificationTokens")
|
||||
.HasForeignKey("UserUUID")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("User");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
|
||||
{
|
||||
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
|
||||
@@ -388,6 +436,8 @@ namespace SharpbinV3.Server.Migrations
|
||||
{
|
||||
b.Navigation("ApiKeys");
|
||||
|
||||
b.Navigation("EmailVerificationTokens");
|
||||
|
||||
b.Navigation("Pastes");
|
||||
|
||||
b.Navigation("RefreshTokens");
|
||||
|
||||
@@ -24,6 +24,7 @@ namespace SharpbinV3.Server
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
DotEnv.Load(".env");
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
@@ -68,6 +69,8 @@ namespace SharpbinV3.Server
|
||||
builder.Services.AddSingleton<ICompressionService, CompressionService>();
|
||||
builder.Services.AddSingleton<IHostedService, PasteCleanUpService>();
|
||||
builder.Services.AddSingleton<IHostedService, PasteViewCleanUpService>();
|
||||
builder.Services.AddSingleton<EmailService>();
|
||||
builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<EmailService>());
|
||||
builder.Services.AddScoped<UserService>();
|
||||
builder.Services.AddScoped<AuthService>();
|
||||
builder.Services.AddScoped<PasteService>();
|
||||
@@ -91,7 +94,9 @@ namespace SharpbinV3.Server
|
||||
.Bind(builder.Configuration.GetSection("JwtSettings"))
|
||||
.ValidateDataAnnotations()
|
||||
.ValidateOnStart();
|
||||
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
|
||||
builder.Services.AddOptions<AppSettings>().Bind(builder.Configuration).ValidateDataAnnotations().ValidateOnStart();
|
||||
builder.Services.AddOptions<AuthSettings>().Bind(builder.Configuration.GetSection("AuthSettings")).ValidateDataAnnotations();
|
||||
builder.Services.AddOptions<EmailSettings>().Bind(builder.Configuration.GetSection("EmailSettings")).ValidateDataAnnotations();
|
||||
|
||||
builder
|
||||
.Services.AddAuthentication(options =>
|
||||
|
||||
@@ -19,21 +19,29 @@ namespace SharpbinV3.Server.Services
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string DisplayName { get; set; } = string.Empty;
|
||||
public bool TotpEnabled { get; set; }
|
||||
public int[] Roles { get; set; } = [];
|
||||
public Role Roles { get; set; }
|
||||
public bool IsBanned { get; set; }
|
||||
public DateTime Expires { get; set; }
|
||||
}
|
||||
|
||||
public sealed class AuthService(
|
||||
AppDbContext db,
|
||||
EmailService email,
|
||||
IOptions<JWTSettings> jwtOptions,
|
||||
IOptions<AuthSettings> authOptions,
|
||||
IOptions<AppSettings> appSettings,
|
||||
IOptions<EmailSettings> emailSettings,
|
||||
ILogger<AuthService> logger
|
||||
)
|
||||
{
|
||||
private readonly AppDbContext _db = db;
|
||||
private readonly EmailService _email = email;
|
||||
private readonly JWTSettings _jwtSettings = jwtOptions.Value;
|
||||
private readonly AuthSettings _authSettings = authOptions.Value;
|
||||
private readonly AppSettings _appSettings = appSettings.Value;
|
||||
private readonly EmailSettings _emailSettings = emailSettings.Value;
|
||||
private readonly ILogger _logger = logger;
|
||||
private const int EmailVerificationTokenLength = 64;
|
||||
|
||||
public async Task<User> CreateUser(string username, string password, string? email, string? displayName)
|
||||
{
|
||||
@@ -47,7 +55,7 @@ namespace SharpbinV3.Server.Services
|
||||
};
|
||||
|
||||
if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync())
|
||||
user.Roles = [0, 1, 255];
|
||||
user.Roles = Role.User | Role.Admin;
|
||||
|
||||
_db.Users.Add(user);
|
||||
await _db.SaveChangesAsync();
|
||||
@@ -66,19 +74,11 @@ namespace SharpbinV3.Server.Services
|
||||
new("username", user.Username),
|
||||
new("displayname", user.DisplayName ?? ""),
|
||||
new("totp_enabled", totpEnabled.ToString()),
|
||||
new("roles", ((int)user.Roles).ToString()),
|
||||
new("is_banned", user.IsBanned.ToString()),
|
||||
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
|
||||
};
|
||||
|
||||
if (user.Roles != null)
|
||||
{
|
||||
foreach (var role in user.Roles)
|
||||
claims.Add(new Claim(ClaimTypes.Role, role.ToString()));
|
||||
}
|
||||
else
|
||||
{
|
||||
claims.Add(new Claim(ClaimTypes.Role, "0"));
|
||||
}
|
||||
|
||||
var descriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(claims),
|
||||
@@ -142,9 +142,9 @@ namespace SharpbinV3.Server.Services
|
||||
);
|
||||
|
||||
var jti = principal.Claims.First(c => c.Type == JwtRegisteredClaimNames.Jti).Value;
|
||||
var userUUID = principal.Claims.First(c => c.Type == "uuid").Value;
|
||||
|
||||
var tokenHash = Utilities.ComputeSha256(refreshToken);
|
||||
|
||||
var storedToken = await _db.RefreshTokens.FirstOrDefaultAsync(rt => rt.TokenHash == tokenHash);
|
||||
|
||||
if (
|
||||
@@ -153,23 +153,25 @@ namespace SharpbinV3.Server.Services
|
||||
|| storedToken.Revoked
|
||||
|| storedToken.ExpiresAt < DateTimeOffset.UtcNow
|
||||
|| storedToken.JwtId != jti
|
||||
|| storedToken.UserUUID != Guid.Parse(userUUID)
|
||||
)
|
||||
{
|
||||
return new CreateJWT { Success = false, Errors = ["Invalid or expired refresh token."] };
|
||||
}
|
||||
|
||||
storedToken.Used = true;
|
||||
storedToken.Revoked = true;
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
var userUUID = principal.Claims.First(c => c.Type == "uuid").Value;
|
||||
var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID == Guid.Parse(userUUID));
|
||||
|
||||
if (user == null || storedToken.UserUUID != Guid.Parse(userUUID))
|
||||
if (user == null)
|
||||
return new CreateJWT { Success = false, Errors = ["Invalid token."] };
|
||||
|
||||
return await GenerateJWTToken(user);
|
||||
var newTokenResult = await GenerateJWTToken(user);
|
||||
if (!newTokenResult.Success)
|
||||
return newTokenResult;
|
||||
|
||||
storedToken.Used = true;
|
||||
storedToken.Revoked = true;
|
||||
await _db.SaveChangesAsync();
|
||||
|
||||
return newTokenResult;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -212,5 +214,56 @@ namespace SharpbinV3.Server.Services
|
||||
var userUUID = Guid.Parse(uuidClaim);
|
||||
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID);
|
||||
}
|
||||
|
||||
public async Task SendEmailVerification(User user)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(user.Email))
|
||||
return;
|
||||
|
||||
string token = Utilities.GenerateSecureRandomString(EmailVerificationTokenLength);
|
||||
string tokenHash = Utilities.ComputeSha256(token);
|
||||
|
||||
string verificationUrl = $"{(_appSettings.Https ? "https" : "http")}://{_appSettings.Domain}/verify-email?token={token}";
|
||||
string emailBody = EmailTemplates.VerifyEmail(verificationUrl, user.Username);
|
||||
|
||||
await _email.SendAsync(user.Email, "Verify Your Email - Sharpbin", emailBody);
|
||||
var verificationToken = new EmailVerificationToken
|
||||
{
|
||||
TokenHash = tokenHash,
|
||||
UserUUID = user.UUID,
|
||||
User = user,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeMilliseconds(),
|
||||
Type = EmailTokenType.VerifyEmail,
|
||||
};
|
||||
await _db.EmailVerificationTokens.AddAsync(verificationToken);
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task<(bool success, string message)> VerifyEmailVerificationToken(string token)
|
||||
{
|
||||
if (token.Length != EmailVerificationTokenLength)
|
||||
return (false, "Invalid token.");
|
||||
|
||||
string tokenHash = Utilities.ComputeSha256(token);
|
||||
var verificationToken = await _db.EmailVerificationTokens.Include(t => t.User).FirstOrDefaultAsync(t => t.TokenHash == tokenHash);
|
||||
|
||||
if (
|
||||
verificationToken == null
|
||||
|| verificationToken.User == null
|
||||
|| verificationToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|
||||
|| verificationToken.Used
|
||||
)
|
||||
return (false, "Token is expired or already used.");
|
||||
|
||||
if (verificationToken != null && !verificationToken.Used)
|
||||
{
|
||||
verificationToken.Used = true;
|
||||
verificationToken.User.EmailVerified = true;
|
||||
await _db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
await _db.SaveChangesAsync();
|
||||
return (true, "Email successfully verified.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Threading.Channels;
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MimeKit;
|
||||
using SharpbinV3.Server.Settings;
|
||||
|
||||
namespace SharpbinV3.Server.Services
|
||||
{
|
||||
public class EmailService(IOptions<EmailSettings> emailSettings, ILogger<EmailService> logger) : BackgroundService
|
||||
{
|
||||
private readonly EmailSettings settings = emailSettings.Value;
|
||||
private readonly Channel<QueuedEmail> queue = Channel.CreateUnbounded<QueuedEmail>(
|
||||
new UnboundedChannelOptions { SingleReader = true, SingleWriter = false }
|
||||
);
|
||||
|
||||
public async Task SendAsync(string to, string subject, string body)
|
||||
{
|
||||
if (
|
||||
string.IsNullOrWhiteSpace(settings.Host)
|
||||
|| string.IsNullOrWhiteSpace(settings.User)
|
||||
|| string.IsNullOrWhiteSpace(settings.Password)
|
||||
|| string.IsNullOrWhiteSpace(settings.From)
|
||||
)
|
||||
{
|
||||
logger.LogWarning($"Email settings are not fully configured. Skipping sending email to {to}");
|
||||
return;
|
||||
}
|
||||
var email = new QueuedEmail(to, subject, body);
|
||||
|
||||
if (queue.Writer.TryWrite(email))
|
||||
return;
|
||||
|
||||
await queue.Writer.WriteAsync(email);
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
await foreach (var email in queue.Reader.ReadAllAsync(stoppingToken))
|
||||
{
|
||||
try
|
||||
{
|
||||
await SendNowAsync(email, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Failed to send email to {EmailTo}", email.To);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SendNowAsync(QueuedEmail email, CancellationToken cancellationToken)
|
||||
{
|
||||
var message = new MimeMessage();
|
||||
message.From.Add(new MailboxAddress("Sharpbin", settings.From!));
|
||||
message.To.Add(MailboxAddress.Parse(email.To));
|
||||
message.Subject = email.Subject;
|
||||
|
||||
message.Body = new TextPart("html") { Text = email.Body };
|
||||
|
||||
using var smtp = new SmtpClient();
|
||||
await smtp.ConnectAsync(settings.Host, settings.Port, SecureSocketOptions.StartTls, cancellationToken);
|
||||
|
||||
await smtp.AuthenticateAsync(settings.User, settings.Password, cancellationToken);
|
||||
|
||||
await smtp.SendAsync(message, cancellationToken);
|
||||
await smtp.DisconnectAsync(true, cancellationToken);
|
||||
}
|
||||
|
||||
private readonly record struct QueuedEmail(string To, string Subject, string Body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace SharpbinV3.Server.Services
|
||||
{
|
||||
public static class EmailTemplates
|
||||
{
|
||||
private static readonly Assembly Assembly = Assembly.GetExecutingAssembly();
|
||||
private static readonly string BaseTemplateName = "SharpbinV3.Server.EmailTemplates.Base.html";
|
||||
|
||||
private static string LoadEmbeddedResource(string resourceName)
|
||||
{
|
||||
using var stream = Assembly.GetManifestResourceStream(resourceName);
|
||||
if (stream == null)
|
||||
throw new FileNotFoundException($"Embedded resource not found: {resourceName}");
|
||||
|
||||
using var reader = new StreamReader(stream);
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
private static string RenderTemplate(string title, string contentTemplate, Dictionary<string, string> replacements)
|
||||
{
|
||||
var baseTemplate = LoadEmbeddedResource(BaseTemplateName);
|
||||
var content = contentTemplate;
|
||||
|
||||
foreach (var (key, value) in replacements)
|
||||
{
|
||||
content = content.Replace($"{{{{{key}}}}}", value);
|
||||
}
|
||||
|
||||
return baseTemplate.Replace("{{TITLE}}", title).Replace("{{CONTENT}}", content);
|
||||
}
|
||||
|
||||
public static string VerifyEmail(string verificationUrl, string username)
|
||||
{
|
||||
var contentTemplate = LoadEmbeddedResource("SharpbinV3.Server.EmailTemplates.VerifyEmail.html");
|
||||
var replacements = new Dictionary<string, string> { { "USERNAME", username }, { "VERIFICATION_URL", verificationUrl } };
|
||||
|
||||
return RenderTemplate("Verify Your Email", contentTemplate, replacements);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SharpbinV3.Server.Data;
|
||||
using SharpbinV3.Server.Data.Entities;
|
||||
using SharpbinV3.Server.Data.Enums;
|
||||
using SharpbinV3.Server.Extensions;
|
||||
using SharpbinV3.Server.Settings;
|
||||
|
||||
@@ -23,7 +24,7 @@ namespace SharpbinV3.Server.Services
|
||||
string content,
|
||||
string title,
|
||||
string syntax,
|
||||
int visibility,
|
||||
Visibility visibility,
|
||||
long expiresAt,
|
||||
bool shouldCompress
|
||||
)
|
||||
@@ -198,9 +199,9 @@ namespace SharpbinV3.Server.Services
|
||||
return title.Length <= _pasteSettings.MaxTitleLength;
|
||||
}
|
||||
|
||||
public bool ValidateVisibility(int visibility)
|
||||
public bool ValidateVisibility(Visibility visibility)
|
||||
{
|
||||
return visibility >= 0 && visibility <= 2;
|
||||
return Enum.IsDefined(typeof(Visibility), visibility);
|
||||
}
|
||||
|
||||
public bool ValidateExpiresAt(long expiresAt)
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Settings
|
||||
{
|
||||
public class AppSettings
|
||||
{
|
||||
[Required, MaxLength(256)]
|
||||
public string Domain { get; set; } = string.Empty;
|
||||
public bool Https { get; set; } = true;
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,6 @@
|
||||
public bool First_User_Admin { get; set; } = true;
|
||||
public bool Admins_Require_2FA { get; set; } = true;
|
||||
public string API_Key_HMAC_Secret { get; set; } = string.Empty;
|
||||
public string Email_Verification_HMAC_Secret { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace SharpbinV3.Server.Settings
|
||||
{
|
||||
public class EmailSettings
|
||||
{
|
||||
[MaxLength(256)]
|
||||
public string Host { get; set; } = string.Empty;
|
||||
|
||||
[Range(1, 65535)]
|
||||
public int Port { get; set; } = 587;
|
||||
|
||||
[MaxLength(256)]
|
||||
public string User { get; set; } = string.Empty;
|
||||
|
||||
[MaxLength(256)]
|
||||
public string Password { get; set; } = string.Empty;
|
||||
|
||||
[EmailAddress]
|
||||
public string? From { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -13,26 +13,31 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.1">
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.1.0" />
|
||||
<PackageReference Include="MailKit" Version="4.15.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.3">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.01" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.3">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.1">
|
||||
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.3">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.3" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
|
||||
<PackageReference Include="Otp.NET" Version="1.4.1" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.15.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.16.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="EmailTemplates\*.html" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -14,27 +14,7 @@ namespace SharpbinV3.Server
|
||||
public static string GenerateSecureRandomString(int length)
|
||||
{
|
||||
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
Span<byte> buffer = stackalloc byte[128];
|
||||
|
||||
var result = new char[length];
|
||||
int pos = 0;
|
||||
|
||||
while (pos < length)
|
||||
{
|
||||
RandomNumberGenerator.Fill(buffer);
|
||||
|
||||
foreach (byte b in buffer)
|
||||
{
|
||||
if (b >= 248)
|
||||
continue; // 248 is the largest multiple of 62 < 256
|
||||
|
||||
result[pos++] = chars[b % chars.Length];
|
||||
if (pos == length)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new string(result);
|
||||
return RandomNumberGenerator.GetString(chars, length);
|
||||
}
|
||||
|
||||
public static string ComputeSha256(string input)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
{
|
||||
"Domain": "localhost:5173",
|
||||
"Https": false,
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
@@ -6,8 +8,7 @@
|
||||
}
|
||||
},
|
||||
"AuthSettings": {
|
||||
"CF_Turnstile_SiteKey": "3x00000000000000000000FF",
|
||||
"CF_Turnstile_SecretKey": "1x0000000000000000000000000000000AA",
|
||||
"First_User_Admin": true,
|
||||
"Admins_Require_2FA": false
|
||||
},
|
||||
"JwtSettings": {
|
||||
|
||||
@@ -53,6 +53,7 @@
|
||||
"crystal",
|
||||
"csp",
|
||||
"css",
|
||||
"csv",
|
||||
"d",
|
||||
"dart",
|
||||
"deplhi",
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Required Misc. Variables
|
||||
Domain=example.com
|
||||
Https=true
|
||||
JwtSettings__Secret=totally_random_and_secure_string
|
||||
|
||||
# Auth Settings
|
||||
AuthSettings__CF_Turnstile_SecretKey=1x0000000000000000000000000000000AA
|
||||
AuthSettings__CF_Turnstile_SiteKey=3x00000000000000000000FF
|
||||
AuthSettings__Registration_Enabled=true
|
||||
AuthSettings__Admins_Require_2FA=true
|
||||
AuthSettings__API_Key_HMAC_Secret=another_random_and_secure_string
|
||||
|
||||
# Paste Settings
|
||||
PasteSettings__MaxTitleLength=500
|
||||
PasteSettings__MaxPasteSizeInBytes=1048576
|
||||
PasteSettings__EnablePasteCompression=true
|
||||
PasteSettings__RequiresVerification=true
|
||||
PasteSettings__View_HMAC_Secret=random_minimum_32_char_string
|
||||
# Used so that views are only counted from the frontend
|
||||
# Must be the same on both the frontend and backend environment
|
||||
PasteSettings__View_Internal_API_Key=another_random_minimum_32_char_string
|
||||
+7
-13
@@ -5,17 +5,10 @@ services:
|
||||
dockerfile: SharpbinV3.Server/Dockerfile
|
||||
image: sharpbin-backend
|
||||
container_name: sharpbin-backend
|
||||
env_file:
|
||||
- "backend.env"
|
||||
environment:
|
||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production}
|
||||
ConnectionStrings__DefaultConnection: ${ConnectionStrings__DefaultConnection:-Data Source=/app/data/sharpbin.db}
|
||||
DATA_PROTECTION_KEY_PATH: ${DATA_PROTECTION_KEY_PATH:-/app/data/keys}
|
||||
JwtSettings__Secret: ${JwtSettings__Secret}
|
||||
AuthSettings__First_User_Admin: ${AuthSettings__First_User_Admin}
|
||||
AuthSettings__CF_Turnstile_SecretKey: ${AuthSettings__CF_Turnstile_SecretKey}
|
||||
AuthSettings__CF_Turnstile_SiteKey: ${AuthSettings__CF_Turnstile_SiteKey}
|
||||
PasteSettings__View_Internal_API_Key: ${PasteSettings__View_Internal_API_Key}
|
||||
PasteSettings__View_HMAC_Secret: ${PasteSettings__View_HMAC_Secret}
|
||||
|
||||
DATA_PROTECTION_KEY_PATH: /app/data/keys
|
||||
volumes:
|
||||
- sharpbin-data:/app/data
|
||||
- ./SharpbinV3.Server/appsettings.json:/app/appsettings.json
|
||||
@@ -33,13 +26,14 @@ services:
|
||||
build:
|
||||
context: ./SharpbinV3.Client
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
GIT_COMMIT_HASH: ${GIT_COMMIT_HASH}
|
||||
image: sharpbin-frontend
|
||||
container_name: sharpbin-frontend
|
||||
env_file:
|
||||
- "frontend.env"
|
||||
environment:
|
||||
VITE_API_URL: http://backend:8080
|
||||
VITE_ALLOWED_HOSTS: ${VITE_ALLOWED_HOSTS:-"localhost"}
|
||||
PasteSettings__View_Internal_API_Key: ${PasteSettings__View_Internal_API_Key}
|
||||
VIEW_INTERNAL_API_KEY: ${VIEW_INTERNAL_API_KEY}
|
||||
|
||||
ports:
|
||||
- "5173:5173"
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
VITE_ALLOWED_HOSTS=localhost,example.com
|
||||
# Used so that views are only counted from the frontend
|
||||
# Must be the same on both the frontend and backend environment
|
||||
# The frontend will also try to parse 'PasteSettings__View_Internal_API_Key'
|
||||
VIEW_INTERNAL_API_KEY=another_random_minimum_32_char_string
|
||||
Reference in New Issue
Block a user