feat: totp 2fa; httpcontext extension for jwtuser; asp.net data protection; prevent banned users from certain actions; account deletion requires 2fa if enabled; making users admins requires 2fa if enabled; httpcontext extension to get ip; enhance user store

refactor: organize dtos by domain; verification providers use verification context; move ip parsing into http context extensions
chore: clean code
This commit is contained in:
2026-01-07 16:36:41 -05:00
parent 361cf76f46
commit 20ceb91db8
46 changed files with 1568 additions and 162 deletions
+276 -5
View File
@@ -10,7 +10,8 @@
"dependencies": { "dependencies": {
"@lucide/svelte": "^0.562.0", "@lucide/svelte": "^0.562.0",
"@sveltejs/adapter-node": "^5.4.0", "@sveltejs/adapter-node": "^5.4.0",
"highlight.js": "^11.8.0" "highlight.js": "^11.8.0",
"qrcode": "^1.5.4"
}, },
"devDependencies": { "devDependencies": {
"@eslint/compat": "^1.4.0", "@eslint/compat": "^1.4.0",
@@ -20,6 +21,7 @@
"@sveltejs/vite-plugin-svelte": "^6.2.1", "@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17", "@tailwindcss/vite": "^4.1.17",
"@types/node": "^22", "@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.39.1", "eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.13.1", "eslint-plugin-svelte": "^3.13.1",
@@ -1544,6 +1546,16 @@
"undici-types": "~6.21.0" "undici-types": "~6.21.0"
} }
}, },
"node_modules/@types/qrcode": {
"version": "1.5.6",
"resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",
"integrity": "sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/resolve": { "node_modules/@types/resolve": {
"version": "1.20.2", "version": "1.20.2",
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
@@ -1845,11 +1857,19 @@
"url": "https://github.com/sponsors/epoberezkin" "url": "https://github.com/sponsors/epoberezkin"
} }
}, },
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/ansi-styles": { "node_modules/ansi-styles": {
"version": "4.3.0", "version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"color-convert": "^2.0.1" "color-convert": "^2.0.1"
@@ -1914,6 +1934,15 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/camelcase": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/chalk": { "node_modules/chalk": {
"version": "4.1.2", "version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -1947,6 +1976,17 @@
"url": "https://paulmillr.com/funding/" "url": "https://paulmillr.com/funding/"
} }
}, },
"node_modules/cliui": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
"strip-ansi": "^6.0.0",
"wrap-ansi": "^6.2.0"
}
},
"node_modules/clsx": { "node_modules/clsx": {
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",
@@ -1960,7 +2000,6 @@
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"color-name": "~1.1.4" "color-name": "~1.1.4"
@@ -1973,7 +2012,6 @@
"version": "1.1.4", "version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/commondir": { "node_modules/commondir": {
@@ -2043,6 +2081,15 @@
} }
} }
}, },
"node_modules/decamelize": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/deep-is": { "node_modules/deep-is": {
"version": "0.1.4", "version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -2075,6 +2122,18 @@
"integrity": "sha512-jDwizj+IlEZBunHcOuuFVBnIMPAEHvTsJj0BcIp94xYguLRVBcXO853px/MyIJvbVzWdsGvrRweIUWJw8hBP7A==", "integrity": "sha512-jDwizj+IlEZBunHcOuuFVBnIMPAEHvTsJj0BcIp94xYguLRVBcXO853px/MyIJvbVzWdsGvrRweIUWJw8hBP7A==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/dijkstrajs": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
"license": "MIT"
},
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"license": "MIT"
},
"node_modules/enhanced-resolve": { "node_modules/enhanced-resolve": {
"version": "5.18.4", "version": "5.18.4",
"resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.4.tgz", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.4.tgz",
@@ -2480,6 +2539,15 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/get-caller-file": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
"license": "ISC",
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
},
"node_modules/glob-parent": { "node_modules/glob-parent": {
"version": "6.0.2", "version": "6.0.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz",
@@ -2606,6 +2674,15 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/is-glob": { "node_modules/is-glob": {
"version": "4.0.3", "version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
@@ -3135,6 +3212,15 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/p-try": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/parent-module": { "node_modules/parent-module": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@@ -3152,7 +3238,6 @@
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
"dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
"node": ">=8" "node": ">=8"
@@ -3192,6 +3277,15 @@
"url": "https://github.com/sponsors/jonschlinkert" "url": "https://github.com/sponsors/jonschlinkert"
} }
}, },
"node_modules/pngjs": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
"license": "MIT",
"engines": {
"node": ">=10.13.0"
}
},
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.6", "version": "8.5.6",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
@@ -3454,6 +3548,23 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/qrcode": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
"license": "MIT",
"dependencies": {
"dijkstrajs": "^1.0.1",
"pngjs": "^5.0.0",
"yargs": "^15.3.1"
},
"bin": {
"qrcode": "bin/qrcode"
},
"engines": {
"node": ">=10.13.0"
}
},
"node_modules/readdirp": { "node_modules/readdirp": {
"version": "4.1.2", "version": "4.1.2",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
@@ -3468,6 +3579,21 @@
"url": "https://paulmillr.com/funding/" "url": "https://paulmillr.com/funding/"
} }
}, },
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/require-main-filename": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
"license": "ISC"
},
"node_modules/resolve": { "node_modules/resolve": {
"version": "1.22.11", "version": "1.22.11",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz",
@@ -3564,6 +3690,12 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
"license": "ISC"
},
"node_modules/set-cookie-parser": { "node_modules/set-cookie-parser": {
"version": "2.7.2", "version": "2.7.2",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
@@ -3616,6 +3748,32 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"license": "MIT",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"license": "MIT",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-json-comments": { "node_modules/strip-json-comments": {
"version": "3.1.1", "version": "3.1.1",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz",
@@ -3977,6 +4135,12 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/which-module": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
"license": "ISC"
},
"node_modules/word-wrap": { "node_modules/word-wrap": {
"version": "1.2.5", "version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
@@ -3987,6 +4151,113 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/wrap-ansi": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
"license": "MIT",
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
"strip-ansi": "^6.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/y18n": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
"license": "ISC"
},
"node_modules/yargs": {
"version": "15.4.1",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
"license": "MIT",
"dependencies": {
"cliui": "^6.0.0",
"decamelize": "^1.2.0",
"find-up": "^4.1.0",
"get-caller-file": "^2.0.1",
"require-directory": "^2.1.1",
"require-main-filename": "^2.0.0",
"set-blocking": "^2.0.0",
"string-width": "^4.2.0",
"which-module": "^2.0.0",
"y18n": "^4.0.0",
"yargs-parser": "^18.1.2"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yargs-parser": {
"version": "18.1.3",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
"license": "ISC",
"dependencies": {
"camelcase": "^5.0.0",
"decamelize": "^1.2.0"
},
"engines": {
"node": ">=6"
}
},
"node_modules/yargs/node_modules/find-up": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
"license": "MIT",
"dependencies": {
"locate-path": "^5.0.0",
"path-exists": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yargs/node_modules/locate-path": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
"license": "MIT",
"dependencies": {
"p-locate": "^4.1.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yargs/node_modules/p-limit": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
"license": "MIT",
"dependencies": {
"p-try": "^2.0.0"
},
"engines": {
"node": ">=6"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/yargs/node_modules/p-locate": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
"license": "MIT",
"dependencies": {
"p-limit": "^2.2.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/yocto-queue": { "node_modules/yocto-queue": {
"version": "0.1.0", "version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+3 -1
View File
@@ -21,6 +21,7 @@
"@sveltejs/vite-plugin-svelte": "^6.2.1", "@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.17", "@tailwindcss/vite": "^4.1.17",
"@types/node": "^22", "@types/node": "^22",
"@types/qrcode": "^1.5.6",
"eslint": "^9.39.1", "eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.13.1", "eslint-plugin-svelte": "^3.13.1",
@@ -38,6 +39,7 @@
"dependencies": { "dependencies": {
"@lucide/svelte": "^0.562.0", "@lucide/svelte": "^0.562.0",
"@sveltejs/adapter-node": "^5.4.0", "@sveltejs/adapter-node": "^5.4.0",
"highlight.js": "^11.8.0" "highlight.js": "^11.8.0",
"qrcode": "^1.5.4"
} }
} }
+244 -11
View File
@@ -1,6 +1,17 @@
<script lang="ts"> <script lang="ts">
import QRCode from 'qrcode';
import { getRefreshToken, getToken, setTokens } from '$lib/utils/auth';
import { parseTotpEnabled } from '$lib/utils/totp';
export let show = false; export let show = false;
export let mode: 'decrypt' | 'encrypt' | 'confirm' | 'prompt' | 'multiselect' = 'decrypt'; export let mode:
| 'decrypt'
| 'encrypt'
| 'confirm'
| 'prompt'
| 'multiselect'
| 'totp'
| 'totpSetup' = 'decrypt';
export let title = ''; export let title = '';
export let message = ''; export let message = '';
export let error = ''; export let error = '';
@@ -8,26 +19,189 @@
export let inputType = 'text'; export let inputType = 'text';
export let items: { label: string; value: unknown }[] = []; export let items: { label: string; value: unknown }[] = [];
export let initialValue: unknown = null; export let initialValue: unknown = null;
export let totpActive: boolean | null = null;
export let onConfirm: (value: unknown) => void; export let onConfirm: (value: unknown) => void;
export let onCancel: () => void; export let onCancel: () => void;
export let confirmButtonText = ''; export let confirmButtonText = '';
let inputValue: string | unknown[] | boolean = ''; let inputValue: string | unknown[] | boolean = '';
let totpSecret = '';
let totpQr = '';
let totpEnabled = false;
let totpInitialized = false;
let totpLoading = false;
let totpError = '';
let displayError = '';
$: if (!show) { $: displayError = error || totpError;
$: if (!show) resetModal();
$: if (show && mode === 'totpSetup' && !totpInitialized) {
totpInitialized = true;
if (totpActive !== null) {
totpEnabled = totpActive;
}
initializeTotp();
}
function resetModal() {
inputValue = inputValue =
initialValue !== null initialValue !== null
? JSON.parse(JSON.stringify(initialValue)) ? JSON.parse(JSON.stringify(initialValue))
: mode === 'multiselect' : mode === 'multiselect'
? [] ? []
: ''; : '';
totpSecret = '';
totpQr = '';
totpEnabled = false;
totpInitialized = false;
totpLoading = false;
totpError = '';
} }
function handleSubmit() { function getCodeOrError(message: string) {
if (mode === 'confirm') { if (typeof inputValue !== 'string') {
onConfirm(true); totpError = message;
} else { return null;
onConfirm(inputValue); }
const code = inputValue.trim();
if (!code) {
totpError = message;
return null;
}
return code;
}
function onCodeInput(e: Event) {
if (!(e.target instanceof HTMLInputElement)) return;
const sanitized = e.target.value.replace(/\D/g, '').slice(0, 6);
e.target.value = sanitized;
inputValue = sanitized;
}
async function initializeTotp() {
totpError = '';
totpLoading = true;
const token = getToken();
if (!token) {
totpError = 'You need to be logged in to manage TOTP.';
totpLoading = false;
return;
}
if (totpEnabled || parseTotpEnabled(token)) {
totpEnabled = true;
totpLoading = false;
return;
}
const res = await fetch('/api/auth/totp/enroll', {
headers: { Authorization: `Bearer ${token}` }
});
if (!res.ok) {
const data = await res.json().catch(() => null);
totpError = data?.message || 'Failed to start TOTP enrollment.';
totpLoading = false;
return;
}
const data = await res.json();
totpSecret = data.secret || '';
if (data.otpauth) {
totpQr = await QRCode.toDataURL(data.otpauth, { margin: 1, width: 300 });
}
totpLoading = false;
}
async function refreshTokens() {
const token = getToken();
const refreshToken = getRefreshToken();
if (!token || !refreshToken) return null;
const res = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, refreshToken })
});
if (!res.ok) return null;
const data = await res.json();
if (data.token?.token && data.token?.refreshToken && data.token?.success !== false) {
setTokens(data.token.token, data.token.refreshToken);
return data.token.token as string;
}
return null;
}
async function handleSubmit() {
if (mode === 'totp') {
if (!inputValue || typeof inputValue !== 'string') return;
onConfirm(inputValue.trim());
return;
}
if (mode === 'totpSetup') {
await submitTotp();
return;
}
onConfirm(mode === 'confirm' ? true : inputValue);
}
async function submitTotp() {
if (totpEnabled) {
await disableTotp();
return;
}
if (!totpSecret) {
totpError = 'Missing TOTP secret. Please reopen the modal.';
return;
}
const code = getCodeOrError('Enter the TOTP code from your authenticator app.');
if (!code) return;
const token = getToken();
if (!token) {
totpError = 'You need to be logged in to enable TOTP.';
return;
}
const res = await fetch('/api/auth/totp/enable', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ secret: totpSecret, totpcode: code })
});
if (!res.ok) {
const data = await res.json().catch(() => null);
totpError = data?.message || 'Failed to enable TOTP.';
return;
}
const newToken = await refreshTokens();
totpEnabled = parseTotpEnabled(newToken || getToken());
onConfirm({ enabled: totpEnabled, secret: totpSecret });
}
async function disableTotp() {
const code = getCodeOrError('Enter the TOTP code to disable two-factor authentication.');
if (!code) return;
const token = getToken();
if (!token) {
totpError = 'You need to be logged in to disable TOTP.';
return;
}
const res = await fetch('/api/auth/totp/disable', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ totpcode: code })
});
if (!res.ok) {
const data = await res.json().catch(() => null);
totpError = data?.message || 'Failed to disable TOTP.';
return;
}
const newToken = await refreshTokens();
totpEnabled = parseTotpEnabled(newToken || getToken());
onConfirm({ enabled: totpEnabled });
}
async function copySecret() {
if (!totpSecret) return;
try {
await navigator.clipboard.writeText(totpSecret);
} catch {
return;
} }
} }
@@ -41,6 +215,10 @@
? 'Confirm action' ? 'Confirm action'
: mode === 'multiselect' : mode === 'multiselect'
? 'Select items' ? 'Select items'
: mode === 'totpSetup'
? 'Set up two-factor authentication'
: mode === 'totp'
? 'Enter TOTP code'
: 'Enter value'); : 'Enter value');
$: confirmLabel = $: confirmLabel =
@@ -51,8 +229,12 @@
? 'Encrypt' ? 'Encrypt'
: mode === 'confirm' : mode === 'confirm'
? 'Delete' ? 'Delete'
: mode === 'totpSetup'
? totpEnabled
? 'Disable'
: 'Enable'
: 'Confirm'); : 'Confirm');
$: shouldShowInput = mode !== 'confirm' && mode !== 'multiselect'; $: shouldShowInput = mode !== 'confirm' && mode !== 'multiselect' && mode !== 'totpSetup';
</script> </script>
{#if show} {#if show}
@@ -71,7 +253,58 @@
</p> </p>
{/if} {/if}
{#if shouldShowInput} {#if mode === 'totpSetup'}
<div class="mb-4 space-y-3">
<div
class="rounded border border-neutral-700 bg-neutral-800 p-3 text-sm text-neutral-200"
>
{totpEnabled
? 'Two-factor authentication is enabled. Enter a current 6-digit code to disable it.'
: 'Scan the QR code with your authenticator app or copy the secret to add it manually.'}
</div>
{#if totpLoading}
<p class="text-neutral-300">Preparing TOTP enrollment...</p>
{:else}
{#if !totpEnabled}
{#if totpQr}
<div class="flex justify-center">
<img
src={totpQr}
alt="TOTP QR code"
class="aspect-square w-full rounded bg-white object-contain p-2"
/>
</div>
{/if}
{#if totpSecret}
<div
class="flex items-center gap-2 rounded border border-neutral-700 bg-neutral-800 p-2"
>
<span class="flex-1 truncate font-mono text-sm text-neutral-100"
>{totpSecret}</span
>
<button
type="button"
on:click={copySecret}
class="rounded bg-neutral-700 px-3 py-1 text-sm font-medium text-white transition-colors hover:bg-neutral-800"
>
Copy
</button>
</div>
{/if}
{/if}
<input
type="text"
bind:value={inputValue}
placeholder="Enter the 6-digit code"
maxlength="6"
inputmode="numeric"
pattern="[0-9]*"
on:input={onCodeInput}
class="w-full rounded border border-neutral-700 bg-neutral-800 p-2 text-white outline-none"
/>
{/if}
</div>
{:else if shouldShowInput}
<input <input
type={inputType} type={inputType}
bind:value={inputValue} bind:value={inputValue}
@@ -100,9 +333,9 @@
</div> </div>
{/if} {/if}
{#if error} {#if displayError}
<div class="mb-3 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"> <div class="mb-3 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200">
{error} {displayError}
</div> </div>
{/if} {/if}
+2 -2
View File
@@ -1,4 +1,4 @@
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import type { User } from '$lib/types/user'; import type { AuthUser } from '$lib/types/user';
export const user = writable<User | null>(null); export const user = writable<AuthUser | null>(null);
+4
View File
@@ -13,3 +13,7 @@ export interface User {
pastes: Paste[] | null; pastes: Paste[] | null;
pagination: Pagination | null; pagination: Pagination | null;
} }
export interface AuthUser extends User {
totpEnabled: boolean;
}
+18
View File
@@ -0,0 +1,18 @@
export function parseTotpEnabled(tokenValue: string | null) {
if (!tokenValue) return false;
try {
const payload = JSON.parse(atob(tokenValue.split('.')[1]));
const flag = payload?.TOTP_Enabled ?? payload?.totp_enabled ?? payload?.totpEnabled;
if (typeof flag === 'string') return flag.toLowerCase() === 'true';
return Boolean(flag);
} catch {
return false;
}
}
export function needsAdminTotp(totpEnabled: boolean, currentRoles: number[], nextRoles: number[]) {
if (!totpEnabled) return false;
const nextHasAdmin = nextRoles.includes(255);
const alreadyAdmin = currentRoles.includes(255);
return nextHasAdmin && !alreadyAdmin;
}
+3 -1
View File
@@ -5,6 +5,7 @@
import Navbar from '$lib/components/Navbar.svelte'; import Navbar from '$lib/components/Navbar.svelte';
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth'; import { startTokenRefreshInterval, getToken, refreshTokenIfNeeded } from '$lib/utils/auth';
import { parseTotpEnabled } from '$lib/utils/totp';
import { page } from '$app/state'; import { page } from '$app/state';
import type { LayoutData } from './$types'; import type { LayoutData } from './$types';
@@ -27,7 +28,8 @@
}); });
if (res.ok) { if (res.ok) {
user.set(await res.json()); const me = await res.json();
user.set({ ...me, totpEnabled: parseTotpEnabled(getToken()) });
} else { } else {
user.set(null); user.set(null);
} }
+14 -1
View File
@@ -81,8 +81,12 @@
return; return;
} }
window.location.href = `/${result.id}`; window.location.href = `/${result.id}`;
} else {
if (response.status === 403) {
error = 'You are banned from creating new pastes.';
} else { } else {
error = 'Failed to create paste. Please try again.'; error = 'Failed to create paste. Please try again.';
}
setInterval(() => { setInterval(() => {
error = ''; error = '';
}, 5000); }, 5000);
@@ -152,7 +156,8 @@
{/if} {/if}
<button <button
type="submit" type="submit"
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900" disabled={$user?.roles && $user.roles.includes(403)}
class="w-full cursor-pointer rounded bg-neutral-700 px-4 py-2 font-semibold text-white transition-colors duration-200 hover:bg-neutral-800 active:bg-neutral-900 disabled:cursor-not-allowed disabled:bg-neutral-950/50 disabled:text-neutral-400"
>Create Paste</button >Create Paste</button
> >
{#if error} {#if error}
@@ -163,6 +168,14 @@
{error} {error}
</div> </div>
{/if} {/if}
{#if $user?.roles && $user.roles.includes(403)}
<div
transition:fly={{ y: 40, duration: 300 }}
class="mt-2 rounded border border-red-900 bg-red-950 p-2 text-sm text-red-200"
>
You are banned from creating new pastes.
</div>
{/if}
</form> </form>
</div> </div>
</main> </main>
@@ -7,6 +7,8 @@
let username = ''; let username = '';
let password = ''; let password = '';
let error = ''; let error = '';
let totpEnabled = false;
let totpCode = '';
export let data: PageData; export let data: PageData;
onMount(() => { onMount(() => {
@@ -31,7 +33,7 @@
}); });
async function login() { async function login() {
const body: { username: string; password: string; token?: string } = { const body: { username: string; password: string; token?: string; totpcode?: string } = {
username, username,
password password
}; };
@@ -43,6 +45,10 @@
} }
} }
if (totpEnabled && totpCode) {
body.totpcode = totpCode;
}
const res = await fetch('/api/auth/login', { const res = await fetch('/api/auth/login', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
@@ -67,6 +73,14 @@
const messages = Object.values(resData.errors).flat(); const messages = Object.values(resData.errors).flat();
error = messages.join('\n'); error = messages.join('\n');
} else { } else {
if (resData.message === 'TOTP code is required.') {
totpEnabled = true;
}
if (resData.message === 'Verification failed.') {
if (window.turnstile) {
window.turnstile.reset();
}
}
error = resData.message || 'Login failed. Please try again.'; error = resData.message || 'Login failed. Please try again.';
} }
} }
@@ -95,6 +109,24 @@
autocomplete="current-password" autocomplete="current-password"
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600" class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/> />
{#if totpEnabled}
<input
type="text"
placeholder="TOTP Code"
bind:value={totpCode}
maxlength="6"
inputmode="numeric"
pattern="[0-9]*"
required
on:input={(e) => {
if (e.target instanceof HTMLInputElement) {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
totpCode = e.target.value;
}
}}
class="focus:bg-neutral-750 w-full rounded border border-neutral-700 bg-neutral-800 p-2 placeholder-neutral-500 transition-colors duration-200 focus:border-neutral-600"
/>
{/if}
{#if data.options?.cf_turnstile_site_key} {#if data.options?.cf_turnstile_site_key}
<div class="flex w-full justify-center"> <div class="flex w-full justify-center">
<div class="cf-turnstile"></div> <div class="cf-turnstile"></div>
@@ -100,6 +100,11 @@
const messages = Object.values(resData.errors).flat(); const messages = Object.values(resData.errors).flat();
error = messages.join('\n'); error = messages.join('\n');
} else { } else {
if (resData.message === 'Verification failed.') {
if (window.turnstile) {
window.turnstile.reset();
}
}
error = resData.message || 'Registration failed. Please try again.'; error = resData.message || 'Registration failed. Please try again.';
} }
} }
@@ -17,6 +17,7 @@
import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc'; import { extractDateFromUUIDv7, tooltip, dateToRelativeString } from '$lib/utils/misc';
import { roles } from '$lib/consts'; import { roles } from '$lib/consts';
import { getToken } from '$lib/utils/auth'; import { getToken } from '$lib/utils/auth';
import { needsAdminTotp } from '$lib/utils/totp';
import Modal from '$lib/components/Modal.svelte'; import Modal from '$lib/components/Modal.svelte';
import { user } from '$lib/stores/user'; import { user } from '$lib/stores/user';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
@@ -36,11 +37,19 @@
let showEditModal = false; let showEditModal = false;
let showDeleteModal = false; let showDeleteModal = false;
let showRoleModal = false; let showRoleModal = false;
let showTotpModal = false;
let showRoleTotpModal = false;
let showDeleteTotpModal = false;
let modalError = ''; let modalError = '';
let totpEnabled = false;
let pendingRoles: number[] | null = null;
let roleTotpCode = '';
let deleteTotpCode = '';
let now = new Date(); let now = new Date();
let interval: ReturnType<typeof setInterval> | null = null; let interval: ReturnType<typeof setInterval> | null = null;
$: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false; $: isOwner = data.user && $user ? data.user?.uuid === $user.uuid : false;
$: totpEnabled = Boolean($user?.totpEnabled);
const roleOptions = [ const roleOptions = [
{ label: 'Member', value: 0 }, { label: 'Member', value: 0 },
@@ -69,7 +78,16 @@
async function handleUserUpdate(displayName?: string, selectedRoles?: number[]) { async function handleUserUpdate(displayName?: string, selectedRoles?: number[]) {
loading = true; loading = true;
modalError = '';
const token = getToken(); const token = getToken();
const currentRoles = data.user?.roles ?? [];
const nextRoles = selectedRoles ?? currentRoles;
if (needsAdminTotp(totpEnabled, currentRoles, nextRoles) && !roleTotpCode) {
pendingRoles = nextRoles;
showRoleTotpModal = true;
loading = false;
return;
}
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, { const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
method: 'PATCH', method: 'PATCH',
headers: { headers: {
@@ -78,7 +96,8 @@
}, },
body: JSON.stringify({ body: JSON.stringify({
...(displayName !== undefined ? { displayName: displayName.trim() } : {}), ...(displayName !== undefined ? { displayName: displayName.trim() } : {}),
...(selectedRoles !== undefined ? { roles: selectedRoles } : {}) ...(selectedRoles !== undefined ? { roles: selectedRoles } : {}),
...(roleTotpCode ? { totpcode: roleTotpCode } : {})
}) })
}); });
loading = false; loading = false;
@@ -93,17 +112,36 @@
if (selectedRoles !== undefined) { if (selectedRoles !== undefined) {
data.user!.roles = selectedRoles; data.user!.roles = selectedRoles;
} }
roleTotpCode = '';
showRoleTotpModal = false;
pendingRoles = null;
modalError = ''; modalError = '';
} }
function handleRoleTotpConfirm(value: unknown) {
if (typeof value === 'string') {
roleTotpCode = value.trim();
}
showRoleTotpModal = false;
if (!roleTotpCode) return;
handleUserUpdate(undefined, pendingRoles ?? data.user?.roles ?? []);
}
async function handleDeleteAccount() { async function handleDeleteAccount() {
loading = true; loading = true;
modalError = '';
const token = getToken(); const token = getToken();
if (totpEnabled && !deleteTotpCode) {
showDeleteTotpModal = true;
loading = false;
return;
}
const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, { const res = await fetch(`/api/user/uuid/${data.user?.uuid}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
Authorization: `Bearer ${token}` Authorization: `Bearer ${token}`
} },
body: totpEnabled && deleteTotpCode ? JSON.stringify({ totpcode: deleteTotpCode }) : undefined
}); });
loading = false; loading = false;
if (!res.ok) { if (!res.ok) {
@@ -112,9 +150,29 @@
return; return;
} }
showDeleteModal = false; showDeleteModal = false;
showDeleteTotpModal = false;
deleteTotpCode = '';
window.location.href = '/'; window.location.href = '/';
} }
function handleTotpConfirm(value: unknown) {
if (value && typeof value === 'object' && 'enabled' in value) {
totpEnabled = Boolean((value as { enabled?: boolean }).enabled);
}
user.update((u) => (u ? { ...u, totpEnabled } : u));
showTotpModal = false;
modalError = '';
}
function handleDeleteTotpConfirm(value: unknown) {
if (typeof value === 'string') {
deleteTotpCode = value.trim();
}
showDeleteTotpModal = false;
if (!deleteTotpCode) return;
handleDeleteAccount();
}
onMount(() => { onMount(() => {
interval = setInterval(() => { interval = setInterval(() => {
now = new Date(); now = new Date();
@@ -201,6 +259,10 @@
{data.user?.uid} {data.user?.uid}
</span> </span>
</div> </div>
<div class="flex shrink-0 items-center">
<ShieldUser class="mr-2 h-6 w-6 text-neutral-400" />
<span class="text-neutral-400">2FA {totpEnabled ? 'enabled' : 'disabled'}</span>
</div>
{#if isOwner && data.user?.lastLogin} {#if isOwner && data.user?.lastLogin}
<div class="flex shrink-0 items-center"> <div class="flex shrink-0 items-center">
<Clock class="mr-2 h-6 w-6 text-neutral-400" /> <Clock class="mr-2 h-6 w-6 text-neutral-400" />
@@ -225,6 +287,18 @@
<Pencil class="h-4 w-4" /> <Pencil class="h-4 w-4" />
Edit Display Name Edit Display Name
</button> </button>
{#if isOwner}
<button
on:click={() => {
showTotpModal = true;
modalError = '';
}}
class="flex items-center gap-2 rounded bg-neutral-700 px-4 py-2 text-sm font-medium transition-colors hover:bg-neutral-600"
>
<ShieldUser class="h-4 w-4" />
{totpEnabled ? 'Manage 2FA' : 'Enable 2FA'}
</button>
{/if}
{#if $user?.roles.some((r) => r === 255)} {#if $user?.roles.some((r) => r === 255)}
<button <button
on:click={() => { on:click={() => {
@@ -323,6 +397,22 @@
}} }}
/> />
<Modal
show={showDeleteTotpModal}
mode="totp"
title="Enter TOTP to delete"
placeholder="Enter 6-digit code"
inputType="text"
error={modalError}
confirmButtonText="Delete Account"
onConfirm={(value) => handleDeleteTotpConfirm(value)}
onCancel={() => {
showDeleteTotpModal = false;
deleteTotpCode = '';
modalError = '';
}}
/>
<Modal <Modal
show={showRoleModal} show={showRoleModal}
mode="multiselect" mode="multiselect"
@@ -337,6 +427,38 @@
}} }}
/> />
<Modal
show={showTotpModal}
mode="totpSetup"
title="Two-Factor Authentication"
message={totpEnabled
? 'Two-factor authentication is currently enabled.'
: 'Enable two-factor authentication with an authenticator app.'}
error={modalError}
totpActive={totpEnabled}
onConfirm={(value) => handleTotpConfirm(value)}
onCancel={() => {
showTotpModal = false;
modalError = '';
}}
/>
<Modal
show={showRoleTotpModal}
mode="totp"
title="Admin role requires TOTP"
placeholder="Enter 6-digit code"
inputType="text"
error={modalError}
confirmButtonText="Continue"
onConfirm={(value) => handleRoleTotpConfirm(value)}
onCancel={() => {
showRoleTotpModal = false;
roleTotpCode = '';
pendingRoles = null;
modalError = '';
}}
/>
<style> <style>
button { button {
cursor: pointer; cursor: pointer;
+1
View File
@@ -0,0 +1 @@
SharpbinV3
@@ -0,0 +1,29 @@
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
namespace SharpbinV3.Server.Authorization
{
public sealed class NotBannedHandler(bool requireAuth = false) : AuthorizationHandler<NotBannedRequirement>
{
private readonly bool _requireAuth = requireAuth;
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
NotBannedRequirement requirement)
{
var isAuthenticated = context.User.Identity?.IsAuthenticated ?? false;
if (_requireAuth && !isAuthenticated)
return Task.CompletedTask;
var isBanned = context.User.Claims.Any(c =>
(c.Type == ClaimTypes.Role || c.Type == "role") &&
c.Value == "403");
if (!isBanned)
context.Succeed(requirement);
return Task.CompletedTask;
}
}
}
@@ -0,0 +1,8 @@
using Microsoft.AspNetCore.Authorization;
namespace SharpbinV3.Server.Authorization
{
public class NotBannedRequirement : IAuthorizationRequirement
{
}
}
+111 -7
View File
@@ -1,10 +1,17 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.DTOs.User;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services; using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification; using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
using Bcrypt = BCrypt.Net.BCrypt; using Bcrypt = BCrypt.Net.BCrypt;
@@ -12,20 +19,29 @@ namespace SharpbinV3.Server.Controllers
{ {
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options, VerificationService verification) : ControllerBase public class AuthController(UserService userService, AuthService authService, IOptions<AuthSettings> options,
VerificationService verification, TotpVerificationProvider totp, AppDbContext db) : ControllerBase
{ {
private readonly AuthService _authService = authService; private readonly AuthService _authService = authService;
private readonly UserService _userService = userService; private readonly UserService _userService = userService;
private readonly VerificationService _verification = verification; private readonly VerificationService _verification = verification;
private readonly TotpVerificationProvider _totp = totp;
private readonly AppDbContext _db = db;
[HttpPost] [HttpPost]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
[Route("register")] [Route("register")]
public async Task<IActionResult> Register([FromBody] RegisterRequest request) public async Task<IActionResult> Register([FromBody] RegisterUserDto request)
{ {
if (!options.Value.Registration_Enabled) if (!options.Value.Registration_Enabled)
return BadRequest(new { message = "Registration is disabled." }); return BadRequest(new { message = "Registration is disabled." });
if (!await _verification.VerifyAsync(request.Token, Utilities.GetRequestIP(HttpContext))) if (!ModelState.IsValid)
return BadRequest(ModelState);
if (!await _verification.VerifyAsync(new VerificationContext
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { message = "Verification failed." }); return BadRequest(new { message = "Verification failed." });
var existingUser = await _userService.GetByUsername(request.Username); var existingUser = await _userService.GetByUsername(request.Username);
@@ -60,12 +76,16 @@ namespace SharpbinV3.Server.Controllers
[HttpPost] [HttpPost]
[Route("login")] [Route("login")]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
public async Task<IActionResult> Login([FromBody] LoginRequest request) public async Task<IActionResult> Login([FromBody] LoginUserDto request)
{ {
if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email)) if (string.IsNullOrEmpty(request.Username) && string.IsNullOrEmpty(request.Email))
return BadRequest(new { message = "Username or email is required." }); return BadRequest(new { message = "Username or email is required." });
if (!await _verification.VerifyAsync(request.Token, Utilities.GetRequestIP(HttpContext))) if (!await _verification.VerifyAsync(new VerificationContext
{
Token = request.Token,
Ip = HttpContext.GetRequestIP()
}))
return BadRequest(new { message = "Verification failed." }); return BadRequest(new { message = "Verification failed." });
User? user = null; User? user = null;
@@ -77,6 +97,20 @@ namespace SharpbinV3.Server.Controllers
if (user == null) return BadRequest(new { message = "Invalid username/email or password." }); if (user == null) return BadRequest(new { message = "Invalid username/email or password." });
if (!Bcrypt.Verify(request.Password, user.PasswordHash)) if (!Bcrypt.Verify(request.Password, user.PasswordHash))
return BadRequest(new { message = "Invalid username/email or password." }); return BadRequest(new { message = "Invalid username/email or password." });
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
if (totpEnabled)
{
if (string.IsNullOrWhiteSpace(request.TotpCode))
return BadRequest(new { message = "TOTP code is required." });
var totpValid = await _totp.VerifyAsync(new VerificationContext
{
UserUUID = user.UUID,
Code = request.TotpCode
});
if (!totpValid)
return BadRequest(new { message = "Invalid TOTP code." });
}
var token = _authService.GenerateJWTToken(user); var token = _authService.GenerateJWTToken(user);
await _authService.UpdateLoginTime(user); await _authService.UpdateLoginTime(user);
return Ok(new { token.Result }); return Ok(new { token.Result });
@@ -84,7 +118,7 @@ namespace SharpbinV3.Server.Controllers
[HttpPost] [HttpPost]
[Route("refresh")] [Route("refresh")]
[EnableRateLimiting("Sliding")] [EnableRateLimiting("Sliding")]
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequest request) public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenDto request)
{ {
try try
{ {
@@ -108,5 +142,75 @@ namespace SharpbinV3.Server.Controllers
registration_enabled = authSettings.Registration_Enabled registration_enabled = authSettings.Registration_Enabled
}); });
} }
[HttpGet]
[Authorize]
[Route("totp/enroll")]
public async Task<IActionResult> StartTotpEnrollment()
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user is null) return BadRequest(new { message = "User not found." });
var secret = _totp.GenerateSecret();
var secretBase32 = _totp.ToBase32(secret);
var account = string.IsNullOrWhiteSpace(user.Email) ? user.Username : user.Email!;
var uri = _totp.BuildOtpAuthUri("SharpbinV3", account, secretBase32);
return Ok(new { secret = secretBase32, otpauth = uri });
}
[HttpPost]
[Authorize]
[Route("totp/enable")]
public async Task<IActionResult> EnableTotp([FromBody] EnableTotpDto request)
{
var uuidClaim = User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
if (string.IsNullOrEmpty(uuidClaim)) return Unauthorized();
var uuid = Guid.Parse(uuidClaim);
if (string.IsNullOrWhiteSpace(request.Secret) || string.IsNullOrWhiteSpace(request.Code))
return BadRequest(new { message = "Secret and code are required." });
if (!_totp.VerifyWithSecretBase32(request.Secret, request.Code))
return BadRequest(new { message = "Invalid TOTP code." });
var secretBytes = _totp.FromBase32(request.Secret);
var protectedBytes = _totp.Protect(secretBytes);
var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == uuid);
if (existing is null)
{
var entry = new UserTotp { UserUUID = uuid, EncryptedSecret = protectedBytes };
_db.UserTotps.Add(entry);
}
else
{
existing.EncryptedSecret = protectedBytes;
_db.UserTotps.Update(existing);
}
await _db.SaveChangesAsync();
return Ok(new { message = "TOTP enabled." });
}
[HttpPost]
[Authorize]
[Route("totp/disable")]
public async Task<IActionResult> DisableTotp([FromBody] DisableTotpDto dto)
{
var user = await _authService.GetUserFromHttpContext(HttpContext);
if (user == null) return BadRequest(new { message = "User not found." });
if (string.IsNullOrWhiteSpace(dto.Code))
return BadRequest(new { message = "TOTP code is required." });
var existing = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == user.UUID);
if (existing is null)
return BadRequest(new { message = "TOTP is not enabled." });
if (!_totp.VerifyAsync(new VerificationContext
{
UserUUID = user.UUID,
Code = dto.Code
}).Result)
return BadRequest(new { message = "Invalid TOTP code." });
_db.UserTotps.Remove(existing);
await _db.SaveChangesAsync();
return Ok(new { message = "TOTP disabled." });
}
} }
} }
@@ -2,23 +2,25 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs.Paste;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services; using SharpbinV3.Server.Services;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
using System.Security.Claims;
namespace SharpbinV3.Server.Controllers namespace SharpbinV3.Server.Controllers
{ {
[Route("api/[controller]")] [Route("api/[controller]")]
[ApiController] [ApiController]
public class PasteController(PasteService pasteService, UserService userService, IOptions<PasteSettings> options) : ControllerBase public class PasteController(PasteService pasteService, UserService userService, AuthService authService, IOptions<PasteSettings> options) : ControllerBase
{ {
private readonly PasteService _pasteService = pasteService; private readonly PasteService _pasteService = pasteService;
private readonly UserService _userService = userService; private readonly UserService _userService = userService;
private readonly AuthService _authService = authService;
private readonly PasteSettings _pasteSettings = options.Value; private readonly PasteSettings _pasteSettings = options.Value;
[HttpPost] [HttpPost]
[Route("create")] [Route("create")]
[Authorize(Policy = "NotBanned")]
public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0) public async Task<IActionResult> CreatePaste(string title = "", string syntax = "plaintext", int visibility = 0, long expiresAt = 0)
{ {
if (!await _pasteService.ValidateExpiresAt(expiresAt)) if (!await _pasteService.ValidateExpiresAt(expiresAt))
@@ -33,9 +35,7 @@ namespace SharpbinV3.Server.Controllers
string content = await new StreamReader(Request.Body).ReadToEndAsync(); string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes) if (System.Text.Encoding.UTF8.GetByteCount(content) > _pasteSettings.MaxPasteSizeInBytes)
return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." }); return BadRequest(new { message = $"Paste size exceeds the maximum allowed size of {_pasteSettings.MaxPasteSizeInBytes} bytes." });
var httpUser = HttpContext.User; var user = await _authService.GetUserFromHttpContext(HttpContext);
var userUUID = httpUser?.FindFirst("UUID")?.Value;
User? user = userUUID is not null ? await _userService.GetByUUID(Guid.Parse(userUUID)) : null;
Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt); Paste paste = await _pasteService.Create(user, content, title, syntax, visibility, expiresAt);
return Ok(new return Ok(new
{ {
@@ -95,21 +95,17 @@ namespace SharpbinV3.Server.Controllers
[HttpPut] [HttpPut]
[Route("{id}/edit")] [Route("{id}/edit")]
[Authorize] [Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> EditPaste(string id) public async Task<IActionResult> EditPaste(string id)
{ {
string content = await new StreamReader(Request.Body).ReadToEndAsync(); string content = await new StreamReader(Request.Body).ReadToEndAsync();
if (content == null || id == null) return NotFound(); if (content == null || id == null) return NotFound();
var paste = await _pasteService.Get(id); var paste = await _pasteService.Get(id);
if (paste == null) return NotFound(); if (paste == null) return NotFound();
var user = HttpContext.User; var user = HttpContext.GetJwtUser();
var uuidClaim = user?.FindFirst("UUID")?.Value; if (user == null) return Forbid();
if (uuidClaim == null || user == null) return Forbid(); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
var hasPrivilegedRole = user.Claims if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) && !hasPrivilegedRole)
return Forbid(); return Forbid();
bool result = await _pasteService.EditText(paste, content); bool result = await _pasteService.EditText(paste, content);
if (!result) return NotFound(); if (!result) return NotFound();
@@ -118,19 +114,15 @@ namespace SharpbinV3.Server.Controllers
[HttpPatch] [HttpPatch]
[Route("{id}/modify")] [Route("{id}/modify")]
[Authorize] [Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] PasteMetadataUpdateRequest request) public async Task<IActionResult> ModifyPasteMetadata(string id, [FromBody] UpdatePasteDto request)
{ {
var paste = await _pasteService.Get(id); var paste = await _pasteService.Get(id);
if (paste == null) return NotFound(); if (paste == null) return NotFound();
var user = HttpContext.User; var user = HttpContext.GetJwtUser();
var uuidClaim = user?.FindFirst("UUID")?.Value; if (user == null) return Forbid();
if (uuidClaim == null || user == null) return Forbid(); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
var hasPrivilegedRole = user.Claims if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) && !hasPrivilegedRole)
return Forbid(); return Forbid();
if (request.Title != null) if (request.Title != null)
paste.Title = request.Title; paste.Title = request.Title;
@@ -171,19 +163,15 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpDelete] [HttpDelete]
[Route("{id}/delete")] [Route("{id}/delete")]
[Authorize] [Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> DeletePaste(string id) public async Task<IActionResult> DeletePaste(string id)
{ {
var paste = await _pasteService.Get(id); var paste = await _pasteService.Get(id);
if (paste == null) return NotFound(); if (paste == null) return NotFound();
var user = HttpContext.User; var user = HttpContext.GetJwtUser();
var uuidClaim = user?.FindFirst("UUID")?.Value; if (user == null) return Forbid();
if (uuidClaim == null || user == null) return Forbid(); var hasPrivilegedRole = user.Roles.Any(r => r == 1 || r == 255);
var hasPrivilegedRole = user.Claims if (paste.AuthorUUID != user.UUID && !hasPrivilegedRole)
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value))
.Any(r => r == 1 || r == 255);
if (paste.AuthorUUID != Guid.Parse(uuidClaim) && !hasPrivilegedRole)
return Forbid(); return Forbid();
bool result = await _pasteService.Delete(paste); bool result = await _pasteService.Delete(paste);
if (!result) return NotFound(); if (!result) return NotFound();
+55 -27
View File
@@ -4,17 +4,23 @@ using Microsoft.EntityFrameworkCore;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs;
using SharpbinV3.Server.DTOs.User;
using SharpbinV3.Server.Extensions;
using SharpbinV3.Server.Services; using SharpbinV3.Server.Services;
using System.Security.Claims; using SharpbinV3.Server.Services.Verification;
using SharpbinV3.Server.Services.Verification.Providers;
namespace SharpbinV3.Server.Controllers namespace SharpbinV3.Server.Controllers
{ {
[ApiController] [ApiController]
[Route("api/[controller]")] [Route("api/[controller]")]
public class UserController(UserService userService, AppDbContext db) : ControllerBase public class UserController(UserService userService, AppDbContext db, AuthService authService, TotpVerificationProvider totp, VerificationService verificationService) : ControllerBase
{ {
private readonly UserService _userService = userService; private readonly UserService _userService = userService;
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
private readonly AuthService _authService = authService;
private readonly TotpVerificationProvider _totp = totp;
private readonly VerificationService _verificationService = verificationService;
[HttpGet("{username}")] [HttpGet("{username}")]
public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1) public async Task<IActionResult> GetByUsername(string username, [FromQuery] int page = 1)
@@ -44,33 +50,39 @@ namespace SharpbinV3.Server.Controllers
[HttpPatch("uuid/{uuid}")] [HttpPatch("uuid/{uuid}")]
[Authorize] [Authorize]
public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserRequest updatedUser) public async Task<IActionResult> UpdateByUUID(Guid uuid, [FromBody] UpdateUserDto updatedUser)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(ModelState); return BadRequest(ModelState);
var jwtUser = HttpContext.User; var jwtUser = HttpContext.GetJwtUser();
var uuidClaim = jwtUser?.FindFirst("UUID")?.Value; if (jwtUser == null) return Forbid();
if (uuidClaim == null || jwtUser == null) return Forbid();
var userRoles = jwtUser.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value));
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null)
return NotFound(); return NotFound();
if (!userRoles.Any(r => r == 1 || r == 255) && user.UUID != Guid.Parse(uuidClaim)) if (!jwtUser.Roles.Any(r => r == 1 || r == 255) && user.UUID != jwtUser.UUID)
return Forbid(); return Forbid();
if (user.Roles.Contains(255) && !userRoles.Contains(255)) if (user.Roles.Contains(255) && !jwtUser.Roles.Contains(255))
return Forbid(); return Forbid();
user.DisplayName = updatedUser.DisplayName ?? user.DisplayName; user.DisplayName = updatedUser.DisplayName ?? user.DisplayName;
if (userRoles.Any(r => r == 255) || user.UUID == Guid.Parse(uuidClaim)) // only admins or self if (jwtUser.Roles.Any(r => r == 255) || user.UUID == jwtUser.UUID) // only admins or self
{ {
user.Email = updatedUser.Email ?? user.Email; user.Email = updatedUser.Email ?? user.Email;
user.Visibility = updatedUser.Visibility ?? user.Visibility; user.Visibility = updatedUser.Visibility ?? user.Visibility;
} }
if (userRoles.Any(r => r == 255)) if (jwtUser.Roles.Contains(255))
{ {
if (updatedUser.Roles.Contains(255) && jwtUser.TotpEnabled)
{
if (string.IsNullOrEmpty(updatedUser.TotpCode) || !await _totp.VerifyAsync(new VerificationContext
{
UserUUID = jwtUser.UUID,
Code = updatedUser.TotpCode
}))
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
user.Roles = updatedUser.Roles ?? user.Roles; user.Roles = updatedUser.Roles ?? user.Roles;
} }
@@ -79,22 +91,39 @@ namespace SharpbinV3.Server.Controllers
} }
[HttpDelete("uuid/{uuid}")] [HttpDelete("uuid/{uuid}")]
[Authorize] [Authorize(Policy = "AuthAndNotBanned")]
public async Task<IActionResult> DeleteByUUID(Guid uuid) public async Task<IActionResult> DeleteByUUID(Guid uuid, [FromBody] DeleteUserDto dto)
{ {
var jwtUser = HttpContext.User; var jwtUser = HttpContext.GetJwtUser();
var uuidClaim = jwtUser?.FindFirst("UUID")?.Value; if (jwtUser == null) return Forbid();
if (uuidClaim == null || jwtUser == null) return Forbid();
var userRoles = jwtUser.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => int.Parse(c.Value));
var user = await _userService.GetByUUID(uuid); var user = await _userService.GetByUUID(uuid);
if (user == null) if (user == null) return Forbid();
return NotFound(); if (!jwtUser.Roles.Any(r => r == 255) && user.UUID != jwtUser.UUID)
if (!userRoles.Any(r => r == 255) && user.UUID != Guid.Parse(uuidClaim))
return Forbid(); return Forbid();
if (jwtUser.TotpEnabled)
{
if (string.IsNullOrEmpty(dto.TotpCode) || !await _totp.VerifyAsync(new VerificationContext
{
UserUUID = jwtUser.UUID,
Code = dto.TotpCode
}))
{
return Unauthorized(new { message = "Invalid TOTP code." });
}
}
else
{
if (string.IsNullOrEmpty(dto.Token) || !await _verificationService.VerifyAsync(new VerificationContext
{
Token = dto.Token,
Ip = HttpContext.GetRequestIP()
}))
{
return Unauthorized(new { message = "Invalid verification token." });
}
}
_db.Users.Remove(user); _db.Users.Remove(user);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return Ok(new { message = "User deleted successfully." }); return Ok(new { message = "User deleted successfully." });
@@ -139,7 +168,6 @@ namespace SharpbinV3.Server.Controllers
}) })
.ToListAsync(); .ToListAsync();
var pagination = new var pagination = new
{ {
Page = page, Page = page,
@@ -1,6 +1,6 @@
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs.Auth
{ {
public class JWTResult public class CreateJWT
{ {
public string? Token { get; set; } public string? Token { get; set; }
public string? RefreshToken { get; set; } public string? RefreshToken { get; set; }
@@ -0,0 +1,7 @@
namespace SharpbinV3.Server.DTOs.Auth
{
public class DisableTotpDto
{
public string Code { get; set; } = string.Empty;
}
}
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.DTOs.Auth
{
public sealed class EnableTotpDto
{
public string Secret { get; set; } = string.Empty;
public string Code { get; set; } = string.Empty;
}
}
@@ -1,8 +1,8 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs.Auth
{ {
public class RefreshTokenRequest public class RefreshTokenDto
{ {
[Required] [Required]
public required string Token { get; set; } public required string Token { get; set; }
@@ -1,8 +1,8 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs.Auth
{ {
public class TurnstileResponse public class TurnstileResponseDto
{ {
[JsonPropertyName("success")] [JsonPropertyName("success")]
public bool Success { get; set; } public bool Success { get; set; }
@@ -1,6 +1,6 @@
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs.Paste
{ {
public class PasteMetadataUpdateRequest public class UpdatePasteDto
{ {
public string? Title { get; set; } public string? Title { get; set; }
public string? Syntax { get; set; } public string? Syntax { get; set; }
@@ -0,0 +1,8 @@
namespace SharpbinV3.Server.DTOs.User
{
public class DeleteUserDto
{
public string? Token { get; set; }
public string? TotpCode { get; set; }
}
}
@@ -1,8 +1,8 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs.User
{ {
public class LoginRequest public class LoginUserDto
{ {
[StringLength(50, MinimumLength = 3)] [StringLength(50, MinimumLength = 3)]
public string? Username { get; set; } public string? Username { get; set; }
@@ -10,5 +10,6 @@ namespace SharpbinV3.Server.DTOs
[StringLength(128, MinimumLength = 6)] [StringLength(128, MinimumLength = 6)]
public string? Password { get; set; } public string? Password { get; set; }
public string? Token { get; set; } public string? Token { get; set; }
public string? TotpCode { get; set; }
} }
} }
@@ -3,7 +3,7 @@ using System.Text.RegularExpressions;
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs
{ {
public partial class RegisterRequest public partial class RegisterUserDto
{ {
[Required] [Required]
[StringLength(50, MinimumLength = 3)] [StringLength(50, MinimumLength = 3)]
@@ -3,12 +3,13 @@ using System.Text.RegularExpressions;
namespace SharpbinV3.Server.DTOs namespace SharpbinV3.Server.DTOs
{ {
public partial class UpdateUserRequest public partial class UpdateUserDto
{ {
public string? DisplayName { get; set; } public string? DisplayName { get; set; }
public string? Email { get; set; } public string? Email { get; set; }
public int? Visibility { get; set; } = 0; public int? Visibility { get; set; } = 0;
public int[]? Roles { get; set; } public int[]? Roles { get; set; }
public string? TotpCode { get; set; }
public IEnumerable<ValidationResult> Validate() public IEnumerable<ValidationResult> Validate()
{ {
+7
View File
@@ -8,6 +8,7 @@ namespace SharpbinV3.Server.Data
public DbSet<User> Users => Set<User>(); public DbSet<User> Users => Set<User>();
public DbSet<Paste> Pastes => Set<Paste>(); public DbSet<Paste> Pastes => Set<Paste>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>(); public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<UserTotp> UserTotps => Set<UserTotp>();
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
@@ -24,6 +25,12 @@ namespace SharpbinV3.Server.Data
.WithMany(u => u.RefreshTokens) .WithMany(u => u.RefreshTokens)
.HasForeignKey(r => r.UserUUID) .HasForeignKey(r => r.UserUUID)
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<UserTotp>()
.HasOne(t => t.User)
.WithOne(u => u.Totp)
.HasForeignKey<UserTotp>(t => t.UserUUID)
.OnDelete(DeleteBehavior.Cascade);
} }
} }
+1
View File
@@ -21,5 +21,6 @@ namespace SharpbinV3.Server.Data.Entities
public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private public int Visibility { get; set; } = 0; // 0 = public, 1 = unlisted, 2 = private
public List<Paste> Pastes { get; set; } = []; public List<Paste> Pastes { get; set; } = [];
public List<RefreshToken> RefreshTokens { get; set; } = []; public List<RefreshToken> RefreshTokens { get; set; } = [];
public UserTotp? Totp { get; set; }
} }
} }
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace SharpbinV3.Server.Data.Entities
{
public class UserTotp
{
[Key]
public Guid UserUUID { get; set; }
public byte[] EncryptedSecret { get; set; } = null!;
public long CreatedAt { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
public User User { get; set; } = null!;
}
}
@@ -0,0 +1,68 @@
using SharpbinV3.Server.Services;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace SharpbinV3.Server.Extensions
{
public static class HttpContextExtensions
{
public readonly static string[] ipHeaders =
[
"X-Forwarded-For",
"X-Real-IP",
"CF-Connecting-IP",
"True-Client-IP",
"X-Cluster-Client-IP",
"X-ProxyUser-IP"
];
public static JwtUser? GetJwtUser(this HttpContext context)
{
if (context.User == null || !context.User.Identity?.IsAuthenticated == true)
return null;
var claims = context.User.Claims;
var uuidClaim = claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
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 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 expires = expClaim != null && long.TryParse(expClaim, out var expUnix)
? DateTimeOffset.FromUnixTimeSeconds(expUnix).UtcDateTime
: DateTime.UtcNow.AddMinutes(15);
return new JwtUser
{
UUID = uuid,
Username = username,
DisplayName = displayName,
TotpEnabled = totpEnabled,
Roles = roles.Length > 0 ? roles : [0],
Expires = expires
};
}
public static string GetRequestIP(this HttpContext context)
{
foreach (var header in ipHeaders)
{
if (context.Request.Headers.TryGetValue(header, out Microsoft.Extensions.Primitives.StringValues value))
{
var ip = value.FirstOrDefault();
if (!string.IsNullOrEmpty(ip))
return ip.Split(',')[0].Trim();
}
}
return context.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
}
}
}
@@ -1,5 +1,4 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -0,0 +1,221 @@
// <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("20260107181640_UserTotps")]
partial class UserTotps
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
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?>("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("UUID")
.IsUnique();
b.HasIndex("Views");
b.HasIndex("Visibility");
b.ToTable("Pastes");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.RefreshToken", b =>
{
b.Property<Guid>("UserUUID")
.HasColumnType("TEXT");
b.Property<long>("CreatedAt")
.HasColumnType("INTEGER");
b.Property<long>("ExpiresAt")
.HasColumnType("INTEGER");
b.Property<string>("JwtId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Token")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Used")
.HasColumnType("INTEGER");
b.HasKey("UserUUID");
b.ToTable("RefreshTokens");
});
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{
b.Property<Guid>("UUID")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("DisplayName")
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT");
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.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.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.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.User", b =>
{
b.Navigation("Pastes");
b.Navigation("RefreshTokens");
b.Navigation("Totp");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SharpbinV3.Server.Migrations
{
/// <inheritdoc />
public partial class UserTotps : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "UserTotps",
columns: table => new
{
UserUUID = table.Column<Guid>(type: "TEXT", nullable: false),
EncryptedSecret = table.Column<byte[]>(type: "BLOB", nullable: false),
CreatedAt = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_UserTotps", x => x.UserUUID);
table.ForeignKey(
name: "FK_UserTotps_Users_UserUUID",
column: x => x.UserUUID,
principalTable: "Users",
principalColumn: "UUID",
onDelete: ReferentialAction.Cascade);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "UserTotps");
}
}
}
@@ -15,7 +15,7 @@ namespace SharpbinV3.Server.Migrations
protected override void BuildModel(ModelBuilder modelBuilder) protected override void BuildModel(ModelBuilder modelBuilder)
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.0"); modelBuilder.HasAnnotation("ProductVersion", "10.0.1");
modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{ {
@@ -155,6 +155,23 @@ namespace SharpbinV3.Server.Migrations
b.ToTable("Users"); 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.Paste", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.Paste", b =>
{ {
b.HasOne("SharpbinV3.Server.Data.Entities.User", "User") b.HasOne("SharpbinV3.Server.Data.Entities.User", "User")
@@ -176,11 +193,24 @@ namespace SharpbinV3.Server.Migrations
b.Navigation("User"); 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.User", b => modelBuilder.Entity("SharpbinV3.Server.Data.Entities.User", b =>
{ {
b.Navigation("Pastes"); b.Navigation("Pastes");
b.Navigation("RefreshTokens"); b.Navigation("RefreshTokens");
b.Navigation("Totp");
}); });
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
+31
View File
@@ -1,7 +1,10 @@
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Authorization;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Services; using SharpbinV3.Server.Services;
using SharpbinV3.Server.Services.Verification; using SharpbinV3.Server.Services.Verification;
@@ -33,7 +36,9 @@ namespace SharpbinV3.Server
builder.Services.AddScoped<AuthService>(); builder.Services.AddScoped<AuthService>();
builder.Services.AddScoped<PasteService>(); builder.Services.AddScoped<PasteService>();
builder.Services.AddScoped<VerificationService>(); builder.Services.AddScoped<VerificationService>();
builder.Services.AddScoped<TotpVerificationProvider>();
builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>(); builder.Services.AddHttpClient<IVerificationProvider, TurnstileVerificationProvider>();
builder.Services.AddMemoryCache();
builder.Services.AddHealthChecks() builder.Services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>("Database"); .AddDbContextCheck<AppDbContext>("Database");
@@ -65,6 +70,14 @@ namespace SharpbinV3.Server
ValidAlgorithms = [SecurityAlgorithms.HmacSha256] ValidAlgorithms = [SecurityAlgorithms.HmacSha256]
}; };
}); });
builder.Services.AddAuthorizationBuilder()
.AddPolicy("NotBanned", policy =>
policy.Requirements.Add(new NotBannedRequirement()));
builder.Services.AddAuthorizationBuilder()
.AddPolicy("AuthAndNotBanned", policy =>
policy.Requirements.Add(new NotBannedRequirement()));
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(false));
builder.Services.AddSingleton<IAuthorizationHandler>(new NotBannedHandler(true));
builder.Services.AddRateLimiter(options => builder.Services.AddRateLimiter(options =>
@@ -91,6 +104,10 @@ namespace SharpbinV3.Server
builder.Services.Configure<JWTSettings>(builder.Configuration.GetSection("JWTSettings")); builder.Services.Configure<JWTSettings>(builder.Configuration.GetSection("JWTSettings"));
builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings")); builder.Services.Configure<AuthSettings>(builder.Configuration.GetSection("AuthSettings"));
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(GetDataProtectionKeyDirectory(builder.Environment))
.SetApplicationName("SharpbinV3");
var app = builder.Build(); var app = builder.Build();
app.UseRateLimiter(); app.UseRateLimiter();
@@ -130,5 +147,19 @@ namespace SharpbinV3.Server
app.Run(); app.Run();
} }
static DirectoryInfo GetDataProtectionKeyDirectory(IHostEnvironment env)
{
var overridepath = Environment.GetEnvironmentVariable("DATA_PROTECTION_KEY_PATH");
if (!string.IsNullOrEmpty(overridepath))
return new DirectoryInfo(overridepath);
var basePath = env.IsDevelopment()
? Environment.CurrentDirectory
: Environment.SpecialFolder.ApplicationData.ToString();
var path = Path.Combine(basePath, "SharpbinV3", "DataProtectionKeys");
return new DirectoryInfo(path);
}
} }
} }
+30 -8
View File
@@ -3,7 +3,7 @@ using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using SharpbinV3.Server.Data; using SharpbinV3.Server.Data;
using SharpbinV3.Server.Data.Entities; using SharpbinV3.Server.Data.Entities;
using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims; using System.Security.Claims;
@@ -12,6 +12,15 @@ using Bcrypt = BCrypt.Net.BCrypt;
namespace SharpbinV3.Server.Services namespace SharpbinV3.Server.Services
{ {
public class JwtUser
{
public Guid UUID { get; set; }
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 DateTime Expires { get; set; }
}
public sealed class AuthService(AppDbContext db, IOptions<JWTSettings> jwtOptions, IOptions<AuthSettings> authOptions) public sealed class AuthService(AppDbContext db, IOptions<JWTSettings> jwtOptions, IOptions<AuthSettings> authOptions)
{ {
private readonly AppDbContext _db = db; private readonly AppDbContext _db = db;
@@ -30,20 +39,24 @@ namespace SharpbinV3.Server.Services
}; };
if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync()) if (_authSettings.First_User_Admin && !await _db.Users.AnyAsync())
user.Roles = [0,1,255]; user.Roles = [0, 1, 255];
_db.Users.Add(user); _db.Users.Add(user);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return user; return user;
} }
public async Task<JWTResult> GenerateJWTToken(User user) public async Task<CreateJWT> GenerateJWTToken(User user)
{ {
var jwtHandler = new JwtSecurityTokenHandler(); var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret); var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
var totpEnabled = await _db.UserTotps.AnyAsync(t => t.UserUUID == user.UUID);
var claims = new List<Claim> var claims = new List<Claim>
{ {
new("UUID", user.UUID.ToString()), new("UUID", user.UUID.ToString()),
new("Username", user.Username),
new("DisplayName", user.DisplayName ?? ""),
new("TOTP_Enabled", totpEnabled.ToString()),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}; };
@@ -100,7 +113,7 @@ namespace SharpbinV3.Server.Services
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
return new JWTResult() return new CreateJWT()
{ {
Token = jwtToken, Token = jwtToken,
Success = true, Success = true,
@@ -108,7 +121,7 @@ namespace SharpbinV3.Server.Services
}; };
} }
public async Task<JWTResult> RefreshJWTToken(string token, string refreshToken) public async Task<CreateJWT> RefreshJWTToken(string token, string refreshToken)
{ {
var jwtHandler = new JwtSecurityTokenHandler(); var jwtHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret); var key = Encoding.UTF8.GetBytes(_jwtSettings.Secret);
@@ -135,20 +148,20 @@ namespace SharpbinV3.Server.Services
|| storedRefreshToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() || storedRefreshToken.ExpiresAt < DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|| storedRefreshToken.JwtId != jwtId) || storedRefreshToken.JwtId != jwtId)
{ {
return new JWTResult() { Success = false, Errors = ["Invalid refresh token, possibly already used or expired."] }; return new CreateJWT() { Success = false, Errors = ["Invalid refresh token, possibly already used or expired."] };
} }
storedRefreshToken.Used = true; storedRefreshToken.Used = true;
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
var userUUID = principal.Claims.First(c => c.Type == "UUID").Value; var userUUID = principal.Claims.First(c => c.Type == "UUID").Value;
var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID == Guid.Parse(userUUID)); var user = await _db.Users.FirstOrDefaultAsync(u => u.UUID == Guid.Parse(userUUID));
if (user == null || storedRefreshToken.UserUUID != Guid.Parse(userUUID)) if (user == null || storedRefreshToken.UserUUID != Guid.Parse(userUUID))
return new JWTResult() { Success = false, Errors = ["Invalid token."] }; return new CreateJWT() { Success = false, Errors = ["Invalid token."] };
return await GenerateJWTToken(user); return await GenerateJWTToken(user);
} }
catch catch
{ {
return new JWTResult() { Success = false, Errors = ["Server Error"] }; return new CreateJWT() { Success = false, Errors = ["Server Error"] };
} }
} }
@@ -172,5 +185,14 @@ namespace SharpbinV3.Server.Services
_db.Users.Update(existingUser); _db.Users.Update(existingUser);
await _db.SaveChangesAsync(); await _db.SaveChangesAsync();
} }
public async Task<User?> GetUserFromHttpContext(HttpContext context)
{
var uuidClaim = context.User.Claims.FirstOrDefault(c => c.Type == "UUID")?.Value;
if (uuidClaim == null)
return null;
var userUUID = Guid.Parse(uuidClaim);
return await _db.Users.FirstOrDefaultAsync(u => u.UUID == userUUID);
}
} }
} }
@@ -4,6 +4,6 @@
{ {
int Priority { get; } int Priority { get; }
bool IsConfigured { get; } bool IsConfigured { get; }
Task<bool> VerifyAsync(string token, string? ip); Task<bool> VerifyAsync(VerificationContext context);
} }
} }
@@ -0,0 +1,73 @@
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using OtpNet;
using SharpbinV3.Server.Data;
namespace SharpbinV3.Server.Services.Verification.Providers
{
public sealed class TotpVerificationProvider : IVerificationProvider
{
private readonly AppDbContext _db;
private readonly IDataProtector _protector;
private readonly IMemoryCache _cache;
public TotpVerificationProvider(AppDbContext db, IDataProtectionProvider dataProtectionProvider, IMemoryCache cache)
{
_db = db;
_protector = dataProtectionProvider.CreateProtector("TotpSecret-v1");
_cache = cache;
}
public int Priority => 0;
public bool IsConfigured => false;
public async Task<bool> VerifyAsync(VerificationContext ctx)
{
if (ctx.UserUUID is null) return false;
if (string.IsNullOrWhiteSpace(ctx.Code)) return false;
var userTotp = await _db.UserTotps.FirstOrDefaultAsync(t => t.UserUUID == ctx.UserUUID.Value);
if (userTotp is null) return false;
var secret = _protector.Unprotect(userTotp.EncryptedSecret);
if (!VerifyCode(secret, ctx.Code, out var step))
return false;
var key = $"totp:{ctx.UserUUID}:{step}";
if (_cache.TryGetValue(key, out _))
return false;
_cache.Set(key, true, TimeSpan.FromSeconds(60));
return true;
}
public byte[] GenerateSecret(int size = 20) => KeyGeneration.GenerateRandomKey(size);
public string ToBase32(byte[] data) => Base32Encoding.ToString(data);
public byte[] FromBase32(string base32) => string.IsNullOrWhiteSpace(base32) ? [] : Base32Encoding.ToBytes(base32);
public string BuildOtpAuthUri(string issuer, string accountName, string secretBase32, int digits = 6, int period = 30, string algorithm = "SHA1")
{
var label = Uri.EscapeDataString($"{issuer}:{accountName}");
var query = $"secret={secretBase32}&issuer={Uri.EscapeDataString(issuer)}&algorithm={algorithm}&digits={digits}&period={period}";
return $"otpauth://totp/{label}?{query}";
}
public byte[] Protect(byte[] secret) => _protector.Protect(secret);
public byte[] Unprotect(byte[] protectedSecret) => _protector.Unprotect(protectedSecret);
public bool VerifyWithSecretBase32(string secretBase32, string code, int digits = 6, int period = 30, int window = 1)
{
var secret = FromBase32(secretBase32);
return VerifyCode(secret, code, out _, digits, period, window);
}
private bool VerifyCode(byte[] secret, string code, out long matchedStep, int digits = 6, int period = 30, int window = 1)
{
var totp = new Totp(secret, step: period, mode: OtpHashMode.Sha1, totpSize: digits);
return totp.VerifyTotp(code, out matchedStep, new VerificationWindow(previous: window, future: window));
}
private string ComputeCode(byte[] key, long timestep, int digits) => new Totp(key, totpSize: digits).ComputeTotp(DateTime.UtcNow);
}
}
@@ -1,5 +1,5 @@
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using SharpbinV3.Server.DTOs; using SharpbinV3.Server.DTOs.Auth;
using SharpbinV3.Server.Settings; using SharpbinV3.Server.Settings;
using System.Text.Json; using System.Text.Json;
@@ -13,26 +13,28 @@ namespace SharpbinV3.Server.Services.Verification.Providers
public int Priority => 1; public int Priority => 1;
public bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey); public bool IsConfigured => !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SecretKey) && !string.IsNullOrEmpty(_authSettings.CF_Turnstile_SiteKey);
public async Task<bool> VerifyAsync(string token, string? ip) public async Task<bool> VerifyAsync(VerificationContext ctx)
{ {
if (_authSettings.CF_Turnstile_SecretKey is null) if (_authSettings.CF_Turnstile_SecretKey is null)
throw new InvalidOperationException("Turnstile secret key is not configured."); throw new InvalidOperationException("Turnstile secret key is not configured.");
if (string.IsNullOrEmpty(ctx.Token))
return false;
var parameters = new Dictionary<string, string> var parameters = new Dictionary<string, string>
{ {
{ "secret", _authSettings.CF_Turnstile_SecretKey }, { "secret", _authSettings.CF_Turnstile_SecretKey },
{ "response", token } { "response", ctx.Token }
}; };
if (!string.IsNullOrEmpty(ip)) if (!string.IsNullOrEmpty(ctx.Ip))
parameters.Add("remoteip", ip); parameters.Add("remoteip", ctx.Ip);
var postContent = new FormUrlEncodedContent(parameters); var postContent = new FormUrlEncodedContent(parameters);
var response = await httpClient.PostAsync(SiteverifyUrl, postContent); var response = await httpClient.PostAsync(SiteverifyUrl, postContent);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync(); var json = await response.Content.ReadAsStringAsync();
var result = JsonSerializer.Deserialize<TurnstileResponse>(json); var result = JsonSerializer.Deserialize<TurnstileResponseDto>(json);
return result?.Success ?? false; return result?.Success ?? false;
} }
} }
@@ -0,0 +1,12 @@
namespace SharpbinV3.Server.Services.Verification
{
public sealed class VerificationContext
{
public string? Token { get; init; }
public string? Ip { get; init; }
public Guid? UserUUID { get; init; }
public string? Code { get; init; }
}
}
@@ -14,18 +14,17 @@ namespace SharpbinV3.Server.Services.Verification
.FirstOrDefault(); .FirstOrDefault();
} }
public async Task<bool> VerifyAsync(string? token, string? ip) public async Task<bool> VerifyAsync(VerificationContext context, IVerificationProvider? provider = null)
{ {
var provider = GetActiveProvider(); var activeProvider = provider ?? GetActiveProvider();
if (provider is null) if (activeProvider is null)
return true; return true;
if (string.IsNullOrWhiteSpace(token)) if (string.IsNullOrWhiteSpace(context.Token))
return false; return false;
return await provider.VerifyAsync(token, ip); return await activeProvider.VerifyAsync(context);
} }
} }
} }
+8 -7
View File
@@ -13,20 +13,21 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" /> <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.0"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.01" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.0"> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.0" /> <PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="10.0.1" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" /> <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.15.0" />
</ItemGroup> </ItemGroup>
+24
View File
@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharpbinV3.Server", "SharpbinV3.Server.csproj", "{79A5E17C-498C-F55E-C79E-1F32E48383EF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79A5E17C-498C-F55E-C79E-1F32E48383EF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {98CE5484-B4BF-4C6B-9EEC-07F6E621F094}
EndGlobalSection
EndGlobal
-23
View File
@@ -2,34 +2,11 @@
{ {
public class Utilities public class Utilities
{ {
public readonly static string[] ipHeaders =
[
"X-Forwarded-For",
"X-Real-IP",
"CF-Connecting-IP",
"True-Client-IP",
"X-Cluster-Client-IP",
"X-ProxyUser-IP"
];
public static string GenerateRandomString(int length) public static string GenerateRandomString(int length)
{ {
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random(); var random = new Random();
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]);
} }
public static string GetRequestIP(HttpContext request)
{
foreach (var header in ipHeaders)
{
if (request.Request.Headers.TryGetValue(header, out Microsoft.Extensions.Primitives.StringValues value))
{
var ip = value.FirstOrDefault();
if (!string.IsNullOrEmpty(ip))
return ip.Split(',')[0].Trim();
}
}
return request.Connection.RemoteIpAddress?.ToString() ?? "Unknown";
}
} }
} }
+1
View File
@@ -9,6 +9,7 @@ services:
ASPNETCORE_ENVIRONMENT: Production ASPNETCORE_ENVIRONMENT: Production
ConnectionStrings__DefaultConnection: "Data Source=/app/data/sharpbin.db" ConnectionStrings__DefaultConnection: "Data Source=/app/data/sharpbin.db"
ASPNETCORE_URLS: "http://+:8080" ASPNETCORE_URLS: "http://+:8080"
DATA_PROTECTION_KEY_PATH: "/app/data/keys"
volumes: volumes:
- sharpbin-data:/app/data - sharpbin-data:/app/data
- ./SharpbinV3.Server/appsettings.json:/app/appsettings.json - ./SharpbinV3.Server/appsettings.json:/app/appsettings.json