diff --git a/.brightsec/tests/get-api-basketitems-1.test.ts b/.brightsec/tests/get-api-basketitems-1.test.ts new file mode 100644 index 0000000..3c701f8 --- /dev/null +++ b/.brightsec/tests/get-api-basketitems-1.test.ts @@ -0,0 +1,34 @@ +import { test, before, after } from 'node:test'; +import { SecRunner } from '@sectester/runner'; +import { Severity, AttackParamLocation, HttpMethod } from '@sectester/scan'; + +const timeout = 40 * 60 * 1000; +const baseUrl = process.env.BRIGHT_TARGET_URL!; + +let runner!: SecRunner; + +before(async () => { + runner = new SecRunner({ + hostname: process.env.BRIGHT_HOSTNAME!, + projectId: process.env.BRIGHT_PROJECT_ID! + }); + + await runner.init(); +}); + +after(() => runner.clear()); + +test('GET /api/basketitems/1', { signal: AbortSignal.timeout(timeout) }, async () => { + await runner + .createScan({ + tests: ['jwt'], + attackParamLocations: [AttackParamLocation.PATH] + }) + .threshold(Severity.CRITICAL) + .timeout(timeout) + .run({ + method: HttpMethod.GET, + url: `${baseUrl}/api/BasketItems/1`, + auth: process.env.BRIGHT_AUTH_ID + }); +}); diff --git a/.brightsec/tests/get-api-basketitems.test.ts b/.brightsec/tests/get-api-basketitems.test.ts new file mode 100644 index 0000000..6a57617 --- /dev/null +++ b/.brightsec/tests/get-api-basketitems.test.ts @@ -0,0 +1,34 @@ +import { test, before, after } from 'node:test'; +import { SecRunner } from '@sectester/runner'; +import { Severity, AttackParamLocation, HttpMethod } from '@sectester/scan'; + +const timeout = 40 * 60 * 1000; +const baseUrl = process.env.BRIGHT_TARGET_URL!; + +let runner!: SecRunner; + +before(async () => { + runner = new SecRunner({ + hostname: process.env.BRIGHT_HOSTNAME!, + projectId: process.env.BRIGHT_PROJECT_ID! + }); + + await runner.init(); +}); + +after(() => runner.clear()); + +test('GET /api/basketitems', { signal: AbortSignal.timeout(timeout) }, async () => { + await runner + .createScan({ + tests: ['jwt'], + attackParamLocations: [AttackParamLocation.HEADER] + }) + .threshold(Severity.CRITICAL) + .timeout(timeout) + .run({ + method: HttpMethod.GET, + url: `${baseUrl}/api/BasketItems`, + auth: process.env.BRIGHT_AUTH_ID + }); +}); diff --git a/.brightsec/tests/get-api-users.test.ts b/.brightsec/tests/get-api-users.test.ts new file mode 100644 index 0000000..52ba809 --- /dev/null +++ b/.brightsec/tests/get-api-users.test.ts @@ -0,0 +1,35 @@ +import { test, before, after } from 'node:test'; +import { SecRunner } from '@sectester/runner'; +import { Severity, AttackParamLocation, HttpMethod } from '@sectester/scan'; + +const timeout = 40 * 60 * 1000; +const baseUrl = process.env.BRIGHT_TARGET_URL!; + +let runner!: SecRunner; + +before(async () => { + runner = new SecRunner({ + hostname: process.env.BRIGHT_HOSTNAME!, + projectId: process.env.BRIGHT_PROJECT_ID! + }); + + await runner.init(); +}); + +after(() => runner.clear()); + +test('GET /api/users', { signal: AbortSignal.timeout(timeout) }, async () => { + await runner + .createScan({ + tests: ['jwt'], + attackParamLocations: [AttackParamLocation.HEADER] + }) + .threshold(Severity.CRITICAL) + .timeout(timeout) + .run({ + method: HttpMethod.GET, + url: `${baseUrl}/api/Users`, + headers: { 'Authorization': 'Bearer ' }, + auth: process.env.BRIGHT_AUTH_ID + }); +}); diff --git a/.brightsec/tests/get-rest-chatbot-status.test.ts b/.brightsec/tests/get-rest-chatbot-status.test.ts new file mode 100644 index 0000000..26bdc2c --- /dev/null +++ b/.brightsec/tests/get-rest-chatbot-status.test.ts @@ -0,0 +1,35 @@ +import { test, before, after } from 'node:test'; +import { SecRunner } from '@sectester/runner'; +import { Severity, AttackParamLocation, HttpMethod } from '@sectester/scan'; + +const timeout = 40 * 60 * 1000; +const baseUrl = process.env.BRIGHT_TARGET_URL!; + +let runner!: SecRunner; + +before(async () => { + runner = new SecRunner({ + hostname: process.env.BRIGHT_HOSTNAME!, + projectId: process.env.BRIGHT_PROJECT_ID! + }); + + await runner.init(); +}); + +after(() => runner.clear()); + +test('GET /rest/chatbot/status', { signal: AbortSignal.timeout(timeout) }, async () => { + await runner + .createScan({ + tests: ['jwt'], + attackParamLocations: [AttackParamLocation.HEADER] + }) + .threshold(Severity.CRITICAL) + .timeout(timeout) + .run({ + method: HttpMethod.GET, + url: `${baseUrl}/rest/chatbot/status`, + headers: { 'Content-Type': 'application/json' }, + auth: process.env.BRIGHT_AUTH_ID + }); +}); diff --git a/.brightsec/tests/post-api-addresss.test.ts b/.brightsec/tests/post-api-addresss.test.ts new file mode 100644 index 0000000..ca5560f --- /dev/null +++ b/.brightsec/tests/post-api-addresss.test.ts @@ -0,0 +1,45 @@ +import { test, before, after } from 'node:test'; +import { SecRunner } from '@sectester/runner'; +import { Severity, AttackParamLocation, HttpMethod } from '@sectester/scan'; + +const timeout = 40 * 60 * 1000; +const baseUrl = process.env.BRIGHT_TARGET_URL!; + +let runner!: SecRunner; + +before(async () => { + runner = new SecRunner({ + hostname: process.env.BRIGHT_HOSTNAME!, + projectId: process.env.BRIGHT_PROJECT_ID! + }); + + await runner.init(); +}); + +after(() => runner.clear()); + +test('POST /api/addresss', { signal: AbortSignal.timeout(timeout) }, async () => { + await runner + .createScan({ + tests: ['id_enumeration'], + attackParamLocations: [AttackParamLocation.BODY] + }) + .threshold(Severity.CRITICAL) + .timeout(timeout) + .run({ + method: HttpMethod.POST, + url: `${baseUrl}/api/Addresss`, + body: { + UserId: 1, + fullName: 'John Doe', + mobileNum: 1234567890, + zipCode: '12345', + streetAddress: '123 Main St', + city: 'Metropolis', + state: 'NY', + country: 'USA' + }, + headers: { 'Content-Type': 'application/json' }, + auth: process.env.BRIGHT_AUTH_ID + }); +}); diff --git a/.github/workflows/bright.yml b/.github/workflows/bright.yml new file mode 100644 index 0000000..cbe4117 --- /dev/null +++ b/.github/workflows/bright.yml @@ -0,0 +1,54 @@ +name: Bright + +on: + pull_request: + branches: ['*'] + +permissions: + checks: write + contents: read + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Node.js 22.x + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Install application dependencies + run: | + npm install --ignore-scripts + cd frontend + npm install --ignore-scripts --legacy-peer-deps + + - name: Build and run application + run: | + docker build -t juice-shop . + docker run -d -p 3000:3000 juice-shop + + - name: Wait for application to be ready + run: | + for i in {1..30}; do + nc -zv 127.0.0.1 3000 && echo "Application is ready" && exit 0 + echo "Waiting for application..." + sleep 5 + done + echo "Application did not start in time" && exit 1 + + - name: Install SecTesterJS dependencies + run: npm i --save=false --prefix .brightsec @sectester/core @sectester/repeater @sectester/scan @sectester/runner @sectester/reporter + + - name: Run security tests + env: + BRIGHT_HOSTNAME: ${{ vars.BRIGHT_HOSTNAME }} + BRIGHT_PROJECT_ID: ${{ vars.BRIGHT_PROJECT_ID }} + BRIGHT_AUTH_ID: ${{ vars.BRIGHT_AUTH_ID }} + BRIGHT_TOKEN: ${{ secrets.BRIGHT_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BRIGHT_TARGET_URL: http://127.0.0.1:3000 + run: node --experimental-transform-types --experimental-strip-types --experimental-detect-module --disable-warning=MODULE_TYPELESS_PACKAGE_JSON --disable-warning=ExperimentalWarning --test-force-exit --test-concurrency=4 --test .brightsec/tests/*.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f51f1d9..c712655 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,22 +1,25 @@ name: "CI/CD Pipeline" on: - push: - branches-ignore: - - l10n_develop - - gh-pages - paths-ignore: - - '*.md' - - 'LICENSE' - - 'monitoring/grafana-dashboard.json' - - 'screenshots/**' - tags-ignore: - - '*' - pull_request: - paths-ignore: - - '*.md' - - 'LICENSE' - - 'data/static/i18n/*.json' - - 'frontend/src/assets/i18n/*.json' + workflow_dispatch: +# on: +# push: +# branches-ignore: +# - l10n_develop +# - gh-pages +# paths-ignore: +# - '*.md' +# - 'LICENSE' +# - 'monitoring/grafana-dashboard.json' +# - 'screenshots/**' +# tags-ignore: +# - '*' +# pull_request: +# paths-ignore: +# - '*.md' +# - 'LICENSE' +# - 'data/static/i18n/*.json' +# - 'frontend/src/assets/i18n/*.json' + env: NODE_DEFAULT_VERSION: 22 NODE_OPTIONS: "--max_old_space_size=4096" @@ -40,18 +43,8 @@ jobs: run: npm run lint - name: "Lint customization configs" run: > - npm run lint:config -- -f ./config/7ms.yml && - npm run lint:config -- -f ./config/addo.yml && - npm run lint:config -- -f ./config/bodgeit.yml && - npm run lint:config -- -f ./config/ctf.yml && - npm run lint:config -- -f ./config/default.yml && - npm run lint:config -- -f ./config/fbctf.yml && - npm run lint:config -- -f ./config/juicebox.yml && - npm run lint:config -- -f ./config/mozilla.yml && - npm run lint:config -- -f ./config/oss.yml && - npm run lint:config -- -f ./config/quiet.yml && - npm run lint:config -- -f ./config/tutorial.yml && - npm run lint:config -- -f ./config/unsafe.yml + npm run lint:config -- -f ./config/7ms.yml && npm run lint:config -- -f ./config/addo.yml && npm run lint:config -- -f ./config/bodgeit.yml && npm run lint:config -- -f ./config/ctf.yml && npm run lint:config -- -f ./config/default.yml && npm run lint:config -- -f ./config/fbctf.yml && npm run lint:config -- -f ./config/juicebox.yml && npm run lint:config -- -f ./config/mozilla.yml && npm run lint:config -- -f ./config/oss.yml && npm run lint:config -- -f ./config/quiet.yml && npm run lint:config -- -f ./config/tutorial.yml && npm run lint:config -- -f ./config/unsafe.yml + coding-challenge-rsn: runs-on: windows-latest steps: @@ -184,17 +177,8 @@ jobs: timeout_minutes: 30 max_attempts: 3 command: > - NODE_ENV=7ms npm run test:server && - NODE_ENV=addo npm run test:server && - NODE_ENV=bodgeit npm run test:server && - NODE_ENV=ctf npm run test:server && - NODE_ENV=fbctf npm run test:server && - NODE_ENV=juicebox npm run test:server && - NODE_ENV=mozilla npm run test:server && - NODE_ENV=oss npm run test:server && - NODE_ENV=quiet npm run test:server && - NODE_ENV=tutorial npm run test:server && - NODE_ENV=unsafe npm run test:server + NODE_ENV=7ms npm run test:server && NODE_ENV=addo npm run test:server && NODE_ENV=bodgeit npm run test:server && NODE_ENV=ctf npm run test:server && NODE_ENV=fbctf npm run test:server && NODE_ENV=juicebox npm run test:server && NODE_ENV=mozilla npm run test:server && NODE_ENV=oss npm run test:server && NODE_ENV=quiet npm run test:server && NODE_ENV=tutorial npm run test:server && NODE_ENV=unsafe npm run test:server + e2e: runs-on: ${{ matrix.os }} strategy: diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index fe353eb..df6c22c 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -1,8 +1,9 @@ name: "CodeQL Scan" - on: - push: - pull_request: + workflow_dispatch: +# on: +# push: +# pull_request: jobs: analyze: @@ -15,19 +16,19 @@ jobs: strategy: fail-fast: false matrix: - language: [ 'javascript-typescript' ] + language: ['javascript-typescript'] steps: - - name: Checkout repository - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2 - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: ${{ matrix.language }} - queries: security-extended - config: | - paths-ignore: - - 'data/static/codefixes' - - name: Autobuild - uses: github/codeql-action/autobuild@v3 - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 + - name: Checkout repository + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2 + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + queries: security-extended + config: | + paths-ignore: + - 'data/static/codefixes' + - name: Autobuild + uses: github/codeql-action/autobuild@v3 + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/lint-fixer.yml b/.github/workflows/lint-fixer.yml index 907f841..73a6204 100644 --- a/.github/workflows/lint-fixer.yml +++ b/.github/workflows/lint-fixer.yml @@ -1,29 +1,30 @@ name: "Let me lint:fix that for you" - -on: [push] +on: + workflow_dispatch: +# on: [push] jobs: LMLFTFY: runs-on: ubuntu-latest steps: - - name: "Check out Git repository" - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2 - - name: "Use Node.js 22" - uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af #v4.1.0 - with: - node-version: 22 - - name: "Install application" - run: | - npm install --ignore-scripts - cd frontend - npm install --ignore-scripts --legacy-peer-deps - - name: "Fix everything which can be fixed" - run: 'npm run lint:fix' - - uses: stefanzweifel/git-auto-commit-action@8621497c8c39c72f3e2a999a26b4ca1b5058a842 #v5.0.1 - with: - commit_message: "Auto-fix linting issues" - branch: ${{ github.head_ref }} - commit_options: '--signoff' - commit_user_name: JuiceShopBot - commit_user_email: 61591748+JuiceShopBot@users.noreply.github.com - commit_author: JuiceShopBot <61591748+JuiceShopBot@users.noreply.github.com> + - name: "Check out Git repository" + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2 + - name: "Use Node.js 22" + uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af #v4.1.0 + with: + node-version: 22 + - name: "Install application" + run: | + npm install --ignore-scripts + cd frontend + npm install --ignore-scripts --legacy-peer-deps + - name: "Fix everything which can be fixed" + run: 'npm run lint:fix' + - uses: stefanzweifel/git-auto-commit-action@8621497c8c39c72f3e2a999a26b4ca1b5058a842 #v5.0.1 + with: + commit_message: "Auto-fix linting issues" + branch: ${{ github.head_ref }} + commit_options: '--signoff' + commit_user_name: JuiceShopBot + commit_user_email: 61591748+JuiceShopBot@users.noreply.github.com + commit_author: JuiceShopBot <61591748+JuiceShopBot@users.noreply.github.com> diff --git a/.github/workflows/rebase.yml b/.github/workflows/rebase.yml index f999d22..d2dea74 100644 --- a/.github/workflows/rebase.yml +++ b/.github/workflows/rebase.yml @@ -1,8 +1,9 @@ name: Automatic Rebase - on: - issue_comment: - types: [created] + workflow_dispatch: +# on: +# issue_comment: +# types: [created] jobs: rebase: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5d01008..f66688e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,8 +1,11 @@ name: "Release Pipeline" on: - push: - tags: - - v* + workflow_dispatch: +# on: +# push: +# tags: +# - v* + env: CYCLONEDX_NPM_VERSION: '^2.0.0||^3.0.0' jobs: diff --git a/.github/workflows/update-challenges-www.yml b/.github/workflows/update-challenges-www.yml index caaa740..53223ac 100644 --- a/.github/workflows/update-challenges-www.yml +++ b/.github/workflows/update-challenges-www.yml @@ -1,34 +1,34 @@ name: "Update challenges on owasp-juice.shop" - on: - push: - branches: [ master ] - paths: - - 'data/static/challenges.yml' + workflow_dispatch: +# on: +# push: +# branches: [master] +# paths: +# - 'data/static/challenges.yml' jobs: UpdateChallengesOnWebsite: if: github.repository == 'juice-shop/juice-shop' runs-on: ubuntu-latest steps: - - name: Check out Git repository - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2 - with: - token: ${{ secrets.BOT_TOKEN }} - repository: OWASP/www-project-juice-shop - ref: master - - name: Update challenges.yml - run: | - cd _data/ - rm challenges.yml - wget https://raw.githubusercontent.com/juice-shop/juice-shop/master/data/static/challenges.yml - - uses: stefanzweifel/git-auto-commit-action@8621497c8c39c72f3e2a999a26b4ca1b5058a842 #v5.0.1 - with: - commit_message: "Auto-update challenges.yml from ${{ github.sha }}" - branch: master - commit_options: '--signoff' - - # Optional commit user and author settings - commit_user_name: JuiceShopBot - commit_user_email: 61591748+JuiceShopBot@users.noreply.github.com - commit_author: JuiceShopBot <61591748+JuiceShopBot@users.noreply.github.com> + - name: Check out Git repository + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2 + with: + token: ${{ secrets.BOT_TOKEN }} + repository: OWASP/www-project-juice-shop + ref: master + - name: Update challenges.yml + run: | + cd _data/ + rm challenges.yml + wget https://raw.githubusercontent.com/juice-shop/juice-shop/master/data/static/challenges.yml + - uses: stefanzweifel/git-auto-commit-action@8621497c8c39c72f3e2a999a26b4ca1b5058a842 #v5.0.1 + with: + commit_message: "Auto-update challenges.yml from ${{ github.sha }}" + branch: master + commit_options: '--signoff' + # Optional commit user and author settings + commit_user_name: JuiceShopBot + commit_user_email: 61591748+JuiceShopBot@users.noreply.github.com + commit_author: JuiceShopBot <61591748+JuiceShopBot@users.noreply.github.com> diff --git a/.github/workflows/update-news-www.yml b/.github/workflows/update-news-www.yml index 2675746..3c04b17 100644 --- a/.github/workflows/update-news-www.yml +++ b/.github/workflows/update-news-www.yml @@ -1,29 +1,29 @@ name: "Update news on owasp-juice.shop" - on: - release: - types: [ published ] + workflow_dispatch: +# on: +# release: +# types: [published] jobs: UpdateNewsOnWebsite: runs-on: ubuntu-latest steps: - - name: Check out Git repository - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2 - with: - token: ${{ secrets.BOT_TOKEN }} - repository: OWASP/www-project-juice-shop - branch: master - - name: Update tab_news.md - run: | - sed -i 's//\n* ${{ github.event.release.published_at }}: juice-shop [`${{ github.event.release.tag_name }}`](https:\/\/github.com\/juice-shop\/juice-shop\/releases\/tag\/${{ github.event.release.tag_name }})/' tab_news.md - - uses: stefanzweifel/git-auto-commit-action@8621497c8c39c72f3e2a999a26b4ca1b5058a842 #v5.0.1 - with: - commit_message: "Add juice-shop ${{ github.event.release.tag_name }} release notes to tab_news.md" - branch: master - commit_options: '--signoff' - - # Optional commit user and author settings - commit_user_name: JuiceShopBot - commit_user_email: 61591748+JuiceShopBot@users.noreply.github.com - commit_author: JuiceShopBot <61591748+JuiceShopBot@users.noreply.github.com> + - name: Check out Git repository + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4.2.2 + with: + token: ${{ secrets.BOT_TOKEN }} + repository: OWASP/www-project-juice-shop + branch: master + - name: Update tab_news.md + run: | + sed -i 's//\n* ${{ github.event.release.published_at }}: juice-shop [`${{ github.event.release.tag_name }}`](https:\/\/github.com\/juice-shop\/juice-shop\/releases\/tag\/${{ github.event.release.tag_name }})/' tab_news.md + - uses: stefanzweifel/git-auto-commit-action@8621497c8c39c72f3e2a999a26b4ca1b5058a842 #v5.0.1 + with: + commit_message: "Add juice-shop ${{ github.event.release.tag_name }} release notes to tab_news.md" + branch: master + commit_options: '--signoff' + # Optional commit user and author settings + commit_user_name: JuiceShopBot + commit_user_email: 61591748+JuiceShopBot@users.noreply.github.com + commit_author: JuiceShopBot <61591748+JuiceShopBot@users.noreply.github.com> diff --git a/lib/insecurity.ts b/lib/insecurity.ts index 08ee8ad..42298d4 100644 --- a/lib/insecurity.ts +++ b/lib/insecurity.ts @@ -11,7 +11,7 @@ import expressJwt from 'express-jwt' import jwt from 'jsonwebtoken' import jws from 'jws' import sanitizeHtmlLib from 'sanitize-html' -import sanitizeFilenameLib from 'sanitize-filename' +sanitizeFilenameLib from 'sanitize-filename' import * as utils from './utils' /* jslint node: true */ @@ -51,10 +51,10 @@ export const cutOffPoisonNullByte = (str: string) => { return str } -export const isAuthorized = () => expressJwt(({ secret: publicKey }) as any) +export const isAuthorized = () => expressJwt(({ secret: publicKey, algorithms: ['RS256'] }) as any) export const denyAll = () => expressJwt({ secret: '' + Math.random() } as any) export const authorize = (user = {}) => jwt.sign(user, privateKey, { expiresIn: '6h', algorithm: 'RS256' }) -export const verify = (token: string) => token ? (jws.verify as ((token: string, secret: string) => boolean))(token, publicKey) : false +export const verify = (token: string) => token ? jwt.verify(token, publicKey, { algorithms: ['RS256'] }) : false export const decode = (token: string) => { return jws.decode(token)?.payload } export const sanitizeHtml = (html: string) => sanitizeHtmlLib(html) @@ -188,7 +188,7 @@ export const appendUserId = () => { export const updateAuthenticatedUsers = () => (req: Request, res: Response, next: NextFunction) => { const token = req.cookies.token || utils.jwtFrom(req) if (token) { - jwt.verify(token, publicKey, (err: Error | null, decoded: any) => { + jwt.verify(token, publicKey, { algorithms: ['RS256'] }, (err: Error | null, decoded: any) => { if (err === null) { if (authenticatedUsers.get(token) === undefined) { authenticatedUsers.put(token, decoded) diff --git a/routes/address.ts b/routes/address.ts index 9d552a6..e9ca4f9 100644 --- a/routes/address.ts +++ b/routes/address.ts @@ -8,29 +8,41 @@ import { AddressModel } from '../models/address' export function getAddress () { return async (req: Request, res: Response) => { - const addresses = await AddressModel.findAll({ where: { UserId: req.body.UserId } }) + const userId = req.body.UserId + if (!userId) { + return res.status(401).json({ status: 'error', data: 'Unauthorized access.' }) + } + const addresses = await AddressModel.findAll({ where: { UserId: userId } }) res.status(200).json({ status: 'success', data: addresses }) } } export function getAddressById () { return async (req: Request, res: Response) => { - const address = await AddressModel.findOne({ where: { id: req.params.id, UserId: req.body.UserId } }) + const userId = req.body.UserId + if (!userId) { + return res.status(401).json({ status: 'error', data: 'Unauthorized access.' }) + } + const address = await AddressModel.findOne({ where: { id: req.params.id, UserId: userId } }) if (address != null) { res.status(200).json({ status: 'success', data: address }) } else { - res.status(400).json({ status: 'error', data: 'Malicious activity detected.' }) + res.status(404).json({ status: 'error', data: 'Address not found or unauthorized access.' }) } } } export function delAddressById () { return async (req: Request, res: Response) => { - const address = await AddressModel.destroy({ where: { id: req.params.id, UserId: req.body.UserId } }) + const userId = req.body.UserId + if (!userId) { + return res.status(401).json({ status: 'error', data: 'Unauthorized access.' }) + } + const address = await AddressModel.destroy({ where: { id: req.params.id, UserId: userId } }) if (address) { res.status(200).json({ status: 'success', data: 'Address deleted successfully.' }) } else { - res.status(400).json({ status: 'error', data: 'Malicious activity detected.' }) + res.status(404).json({ status: 'error', data: 'Address not found or unauthorized access.' }) } } } diff --git a/routes/authenticatedUsers.ts b/routes/authenticatedUsers.ts index 9ea35d8..a2fadba 100644 --- a/routes/authenticatedUsers.ts +++ b/routes/authenticatedUsers.ts @@ -4,7 +4,7 @@ */ import { type Request, type Response, type NextFunction } from 'express' import { UserModel } from '../models/user' -import { decode } from 'jsonwebtoken' +import { decode, verify } from 'jsonwebtoken' import * as security from '../lib/insecurity' async function retrieveUserList (req: Request, res: Response, next: NextFunction) { @@ -17,8 +17,12 @@ async function retrieveUserList (req: Request, res: Response, next: NextFunction const userToken = security.authenticatedUsers.tokenOf(user) let lastLoginTime: number | null = null if (userToken) { - const parsedToken = decode(userToken, { json: true }) - lastLoginTime = parsedToken ? Math.floor(new Date(parsedToken?.iat ?? 0 * 1000).getTime()) : null + try { + const parsedToken = verify(userToken, 'your-secret-key', { algorithms: ['HS256'] }) + lastLoginTime = parsedToken ? Math.floor(new Date(parsedToken.iat * 1000).getTime()) : null + } catch (err) { + console.error('Invalid token:', err) + } } return { diff --git a/routes/chatbot.ts b/routes/chatbot.ts index ff12ea3..0c57d13 100644 --- a/routes/chatbot.ts +++ b/routes/chatbot.ts @@ -236,7 +236,7 @@ export function process () { async function getUserFromJwt (token: string): Promise { return await new Promise((resolve) => { - jwt.verify(token, security.publicKey, (err: VerifyErrors | null, decoded: JwtPayload | string | undefined) => { + jwt.verify(token, security.publicKey, { algorithms: ['RS256'] }, (err: VerifyErrors | null, decoded: JwtPayload | string | undefined) => { if (err !== null || !decoded || isString(decoded)) { resolve(null) } else { diff --git a/routes/recycles.ts b/routes/recycles.ts index 4eafd96..a71b9d8 100644 --- a/routes/recycles.ts +++ b/routes/recycles.ts @@ -9,14 +9,19 @@ import { RecycleModel } from '../models/recycle' import * as utils from '../lib/utils' export const getRecycleItem = () => (req: Request, res: Response) => { + const userId = req.user?.id; // Assuming req.user is populated with the authenticated user's info RecycleModel.findAll({ where: { - id: JSON.parse(req.params.id) + id: JSON.parse(req.params.id), + UserId: userId // Ensure the recycle item belongs to the authenticated user } }).then((Recycle) => { + if (Recycle.length === 0) { + return res.status(404).send('Recycle item not found or you do not have access to it.'); + } return res.send(utils.queryResultToJson(Recycle)) }).catch((_: unknown) => { - return res.send('Error fetching recycled items. Please try again') + return res.status(500).send('Error fetching recycled items. Please try again') }) } diff --git a/routes/verify.ts b/routes/verify.ts index 6338868..2efc625 100644 --- a/routes/verify.ts +++ b/routes/verify.ts @@ -114,7 +114,7 @@ function jwtChallenge (challenge: Challenge, req: Request, algorithm: string, em return } - jwt.verify(token, security.publicKey, (err: jwt.VerifyErrors | null) => { + jwt.verify(token, security.publicKey, { algorithms: ['RS256'] }, (err: jwt.VerifyErrors | null) => { if (err === null) { challengeUtils.solveIf(challenge, () => { return hasAlgorithm(token, algorithm) && hasEmail(decoded as { data: { email: string } }, email)