12 Commits

Author SHA1 Message Date
49ac4f6ca4 chore(release): 1.2.0 [skip ci] 2022-08-29 17:47:08 +00:00
8e69511e3e docs: add oauth2 tag 2022-08-29 17:37:00 +00:00
7e305429b4 feat: make JWT refreshTokens more secure
Don't store the token itself in the database, store a UUID, and when refreshing the accessToken, verify the token and verify that in the payload there is a corresponding UUID stored in the database
2022-08-29 17:26:43 +00:00
b71da7dcc9 fix: on password reset, delete all refresh tokens 2022-08-29 16:32:24 +00:00
a6dd112e4a refactor: minor changes 2022-08-29 16:10:17 +00:00
ab94d1e656 ci: fix prisma:validate error in CI 2022-08-23 23:58:38 +02:00
8483cd4772 ci: usage of ubuntu-latest 2022-08-23 23:57:52 +02:00
46745e1b7e build(deps): update latest 2022-08-23 21:53:07 +00:00
50dbab7dfe chore(release): 1.1.0 [skip ci] 2022-06-29 04:34:56 +00:00
2f78604116 fix: sort public guilds with descending members count 2022-06-29 04:16:48 +00:00
4d565e4f1f build(deps): update latest 2022-06-29 03:59:30 +00:00
183377afc3 feat: update file-uploads-api to v1.1.0 2022-06-29 03:58:26 +00:00
54 changed files with 4772 additions and 4895 deletions

View File

@ -1 +1,7 @@
{ "extends": ["@commitlint/config-conventional"] }
{
"extends": ["@commitlint/config-conventional"],
"rules": {
"body-max-length": [0, "always"],
"body-max-line-length": [0, "always"]
}
}

View File

@ -12,7 +12,7 @@ services:
- 'host.docker.internal:host-gateway'
thream-database:
image: 'postgres:14.2'
image: 'postgres:14.5'
environment:
POSTGRES_USER: 'user'
POSTGRES_PASSWORD: 'password'

View File

@ -1,21 +1,21 @@
API_URL=http://localhost:8080
COMPOSE_PROJECT_NAME=thream-api
NODE_ENV=development
API_URL=http://localhost:8080
HOST=0.0.0.0
PORT=8080
DATABASE_URL=postgresql://user:password@thream-database:5432/thream
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
EMAIL_HOST=thream-maildev
EMAIL_PASSWORD=password
EMAIL_PORT=25
EMAIL_USER=no-reply@thream.fr
FILE_UPLOADS_API_KEY=apiKeySecret
FILE_UPLOADS_API_URL=http://host.docker.internal:8000
DISCORD_CLIENT_ID=
DISCORD_CLIENT_SECRET=
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
HOST=0.0.0.0
JWT_ACCESS_EXPIRES_IN=15 minutes
JWT_ACCESS_SECRET=accessTokenSecret
JWT_REFRESH_SECRET=refreshTokenSecret
NODE_ENV=development
PORT=8080

View File

@ -45,3 +45,6 @@ jobs:
uses: 'hadolint/hadolint-action@v1.6.0'
with:
dockerfile: './Dockerfile'
- name: 'prisma:validate'
run: 'cp .env.example .env && npm run prisma:validate'

View File

@ -8,7 +8,7 @@ on:
jobs:
test:
runs-on: 'macos-latest'
runs-on: 'ubuntu-latest'
steps:
- uses: 'actions/checkout@v3.0.0'

1
.gitignore vendored
View File

@ -35,3 +35,4 @@ npm-debug.log*
# misc
.DS_Store
*.hbs

View File

@ -2,5 +2,6 @@
"*": ["editorconfig-checker"],
"*.{js,jsx,ts,tsx}": ["prettier --write", "eslint --fix"],
"*.{json,jsonc,yml,yaml}": ["prettier --write"],
"*.md": ["prettier --write", "markdownlint --dot --fix"]
"*.{md,mdx}": ["prettier --write", "markdownlint-cli2 --fix"],
"prisma/schema.prisma": ["prisma validate"]
}

10
.markdownlint-cli2.jsonc Normal file
View File

@ -0,0 +1,10 @@
{
"config": {
"default": true,
"MD013": false,
"MD033": false,
"MD041": false
},
"globs": ["**/*.{md,mdx}"],
"ignores": ["**/node_modules"]
}

View File

@ -1,6 +0,0 @@
{
"default": true,
"MD013": false,
"MD033": false,
"MD041": false
}

View File

@ -1,6 +0,0 @@
build
node_modules
coverage
package.json
package-lock.json
*.hbs

14
.swcrc
View File

@ -2,21 +2,11 @@
"jsc": {
"parser": {
"syntax": "typescript",
"decorators": true,
"dynamicImport": true
},
"transform": {
"legacyDecorator": true,
"decoratorMetadata": true
},
"target": "es2022",
"loose": true
"target": "es2022"
},
"module": {
"type": "es6",
"strict": false,
"strictMode": true,
"lazy": false,
"noInterop": false
"type": "es6"
}
}

View File

@ -86,7 +86,6 @@ git commit -m "fix(services): should emit events to connected users"
- `services` : all REST API endpoints
- `tools` : configs and utilities
- `typings` : types gloablly used in the project
- `uploads` : uploaded files by users
### Services folder explained with an example

View File

@ -1,15 +1,15 @@
FROM node:16.14.2 AS dependencies
FROM node:16.17.0 AS dependencies
WORKDIR /usr/src/app
COPY ./package*.json ./
RUN npm install
FROM node:16.14.2 AS builder
FROM node:16.17.0 AS builder
WORKDIR /usr/src/app
COPY --from=dependencies /usr/src/app/node_modules ./node_modules
COPY ./ ./
RUN npm run prisma:generate && npm run build
FROM node:16.14.2 AS runner
FROM node:16.17.0 AS runner
WORKDIR /usr/src/app
ENV NODE_ENV=production
COPY --from=builder /usr/src/app/node_modules ./node_modules

View File

@ -18,7 +18,7 @@
Thream's Application Programming Interface (API) to stay close with your friends and communities.
It uses [Thream/file-uploads-api](https://github.com/Thream/file-uploads-api) [v1.0.0](https://github.com/Thream/file-uploads-api/releases/tag/v1.0.0).
It uses [Thream/file-uploads-api](https://github.com/Thream/file-uploads-api) [v1.1.0](https://github.com/Thream/file-uploads-api/releases/tag/v1.1.0).
## ⚙️ Getting Started

View File

@ -22,7 +22,7 @@ export const serviceGenerator = {
type: 'list',
name: 'tag',
message: 'tag',
choices: ['users', 'guilds', 'channels', 'messages', 'members', 'uploads']
choices: ['users', 'oauth2', 'guilds', 'channels', 'messages', 'members']
},
{
type: 'confirm',

9281
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "@thream/api",
"version": "1.0.1",
"version": "1.2.0",
"description": "Thream's application programming interface to stay close with your friends and communities.",
"private": true,
"type": "module",
@ -20,11 +20,12 @@
"generate": "plop",
"lint:commit": "commitlint",
"lint:editorconfig": "editorconfig-checker",
"lint:markdown": "markdownlint \"**/*.md\" --dot --ignore-path \".gitignore\"",
"lint:markdown": "markdownlint-cli2",
"lint:typescript": "eslint \"**/*.{js,jsx,ts,tsx}\" --ignore-path \".gitignore\"",
"lint:prettier": "prettier \".\" --check",
"lint:prettier": "prettier \".\" --check --ignore-path \".gitignore\"",
"lint:staged": "lint-staged",
"test": "cross-env NODE_ENV=test c8 tap",
"prisma:validate": "prisma validate",
"prisma:generate": "prisma generate",
"prisma:studio": "prisma studio",
"prisma:migrate:dev": "prisma migrate dev",
@ -33,69 +34,70 @@
"postinstall": "husky install"
},
"dependencies": {
"@prisma/client": "3.12.0",
"@sinclair/typebox": "0.23.4",
"@fastify/cors": "8.1.0",
"@fastify/helmet": "9.1.0",
"@fastify/multipart": "7.1.1",
"@fastify/rate-limit": "7.3.0",
"@fastify/sensible": "5.1.1",
"@fastify/swagger": "7.4.1",
"@prisma/client": "4.2.1",
"@sinclair/typebox": "0.24.28",
"@thream/socketio-jwt": "3.0.0",
"axios": "0.26.1",
"bcryptjs": "2.4.3",
"dotenv": "16.0.0",
"ejs": "3.1.6",
"fastify": "3.28.0",
"fastify-cors": "6.0.3",
"fastify-helmet": "7.0.1",
"fastify-multipart": "5.3.1",
"fastify-plugin": "3.0.1",
"fastify-rate-limit": "5.8.0",
"fastify-sensible": "3.1.2",
"fastify-swagger": "5.1.0",
"dotenv": "16.0.1",
"ejs": "3.1.8",
"fastify": "4.5.3",
"fastify-plugin": "4.2.1",
"form-data": "4.0.0",
"http-errors": "2.0.0",
"jsonwebtoken": "8.5.1",
"ms": "2.1.3",
"nodemailer": "6.7.3",
"nodemailer": "6.7.8",
"read-pkg": "7.1.0",
"socket.io": "4.4.1"
"socket.io": "4.5.1"
},
"devDependencies": {
"@commitlint/cli": "16.2.3",
"@commitlint/config-conventional": "16.2.1",
"@commitlint/cli": "17.1.2",
"@commitlint/config-conventional": "17.1.0",
"@saithodev/semantic-release-backmerge": "2.1.2",
"@semantic-release/git": "10.0.1",
"@swc/cli": "0.1.57",
"@swc/core": "1.2.164",
"@swc/core": "1.2.244",
"@types/bcryptjs": "2.4.2",
"@types/busboy": "1.5.0",
"@types/ejs": "3.1.0",
"@types/ejs": "3.1.1",
"@types/http-errors": "1.8.2",
"@types/jsonwebtoken": "8.5.8",
"@types/jsonwebtoken": "8.5.9",
"@types/ms": "0.7.31",
"@types/node": "17.0.23",
"@types/nodemailer": "6.4.4",
"@types/sinon": "10.0.11",
"@types/tap": "15.0.6",
"@typescript-eslint/eslint-plugin": "5.18.0",
"c8": "7.11.0",
"concurrently": "7.1.0",
"@types/node": "18.7.13",
"@types/nodemailer": "6.4.5",
"@types/sinon": "10.0.13",
"@types/tap": "15.0.7",
"@typescript-eslint/eslint-plugin": "5.35.1",
"@typescript-eslint/parser": "5.35.1",
"c8": "7.12.0",
"concurrently": "7.3.0",
"cross-env": "7.0.3",
"editorconfig-checker": "4.0.2",
"eslint": "8.12.0",
"eslint-config-conventions": "2.0.0",
"eslint": "8.23.0",
"eslint-config-conventions": "3.0.0",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-import": "2.26.0",
"eslint-plugin-prettier": "4.0.0",
"eslint-plugin-promise": "6.0.0",
"eslint-plugin-unicorn": "42.0.0",
"husky": "7.0.4",
"lint-staged": "12.3.7",
"markdownlint-cli": "0.31.1",
"nodemon": "2.0.15",
"plop": "3.0.5",
"prettier": "2.6.2",
"prisma": "3.12.0",
"eslint-plugin-prettier": "4.2.1",
"eslint-plugin-promise": "6.0.1",
"eslint-plugin-unicorn": "43.0.2",
"husky": "8.0.1",
"lint-staged": "13.0.3",
"markdownlint-cli2": "0.5.1",
"nodemon": "2.0.19",
"plop": "3.1.1",
"prettier": "2.7.1",
"prisma": "4.2.1",
"rimraf": "3.0.2",
"semantic-release": "19.0.2",
"sinon": "13.0.1",
"tap": "16.0.1",
"typescript": "4.6.3"
"semantic-release": "19.0.5",
"sinon": "14.0.0",
"tap": "16.3.0",
"typescript": "4.8.2"
}
}

View File

@ -1,10 +1,10 @@
import dotenv from 'dotenv'
import fastify from 'fastify'
import fastifyCors from 'fastify-cors'
import fastifySwagger from 'fastify-swagger'
import fastifyHelmet from 'fastify-helmet'
import fastifyRateLimit from 'fastify-rate-limit'
import fastifySensible from 'fastify-sensible'
import fastifyCors from '@fastify/cors'
import fastifySwagger from '@fastify/swagger'
import fastifyHelmet from '@fastify/helmet'
import fastifyRateLimit from '@fastify/rate-limit'
import fastifySensible from '@fastify/sensible'
import { services } from './services/index.js'
import { swaggerOptions } from './tools/configurations/swaggerOptions.js'
@ -15,7 +15,11 @@ export const application = fastify({
logger: process.env.NODE_ENV === 'development',
ajv: {
customOptions: {
format: 'full'
strict: 'log',
keywords: ['kind', 'modifier'],
formats: {
full: true
}
}
}
})

View File

@ -1,5 +1,8 @@
import { application } from './application.js'
import { HOST, PORT } from './tools/configurations/index.js'
const address = await application.listen(PORT, HOST)
const address = await application.listen({
port: PORT,
host: HOST
})
console.log('\u001B[36m%s\u001B[0m', `🚀 Server listening at ${address}`)

View File

@ -14,8 +14,7 @@ export const messageSchema = {
type: Type.Union(types, { default: 'text' }),
mimetype: Type.String({
maxLength: 127,
default: 'text/plain',
format: 'mimetype'
default: 'text/plain'
}),
createdAt: date.createdAt,
updatedAt: date.updatedAt,

View File

@ -6,7 +6,7 @@ import { date, id } from './utils.js'
export const refreshTokensSchema = {
id,
token: Type.String(),
token: Type.String({ format: 'uuid' }),
createdAt: date.createdAt,
updatedAt: date.updatedAt,
userId: id
@ -15,7 +15,7 @@ export const refreshTokensSchema = {
export const refreshTokenExample: RefreshToken = {
id: 1,
userId: userExample.id,
token: 'sometoken',
token: 'sometokenUUID',
createdAt: new Date(),
updatedAt: new Date()
}

View File

@ -10,6 +10,10 @@ export interface UserJWT {
currentStrategy: AuthenticationStrategy
}
export interface UserRefreshJWT extends UserJWT {
tokenUUID: string
}
export interface UserRequest {
current: User
currentStrategy: AuthenticationStrategy

View File

@ -1,6 +1,6 @@
import { Type, Static } from '@sinclair/typebox'
import { FastifyPluginAsync, FastifySchema } from 'fastify'
import fastifyMultipart from 'fastify-multipart'
import fastifyMultipart from '@fastify/multipart'
import prisma from '../../../../../tools/database/prisma.js'
import { fastifyErrors } from '../../../../../models/utils.js'

View File

@ -1,6 +1,6 @@
import { Static, Type } from '@sinclair/typebox'
import { FastifyPluginAsync, FastifySchema } from 'fastify'
import fastifyMultipart from 'fastify-multipart'
import fastifyMultipart from '@fastify/multipart'
import authenticateUser from '../../../../tools/plugins/authenticateUser.js'
import { fastifyErrors } from '../../../../models/utils.js'

View File

@ -18,7 +18,8 @@ const querySchema = Type.Object({
export type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'GET all the public guilds.',
description:
'GET all the public guilds (ordered by descending members count).',
tags: ['guilds'] as string[],
security: [
{
@ -55,7 +56,11 @@ export const getGuildsPublic: FastifyPluginAsync = async (fastify) => {
}
const guildsRequest = await prisma.guild.findMany({
...getPaginationOptions(request.query),
orderBy: { createdAt: 'desc' },
orderBy: {
members: {
_count: 'desc'
}
},
...(request.query.search != null && {
where: {
name: { contains: request.query.search }

View File

@ -50,6 +50,7 @@ export const getUserById: FastifyPluginAsync = async (fastify) => {
id: true,
name: true,
email: settings.isPublicEmail,
isConfirmed: true,
logo: true,
status: true,
biography: true,

View File

@ -1,6 +1,6 @@
import { Type } from '@sinclair/typebox'
import { FastifyPluginAsync, FastifySchema } from 'fastify'
import fastifyMultipart from 'fastify-multipart'
import fastifyMultipart from '@fastify/multipart'
import authenticateUser from '../../../../tools/plugins/authenticateUser.js'
import { fastifyErrors } from '../../../../models/utils.js'

View File

@ -14,7 +14,7 @@ type Parameters = Static<typeof parametersSchema>
const deleteServiceSchema: FastifySchema = {
description: 'DELETE a provider to authenticate with for a user.',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
security: [
{
bearerAuth: []

View File

@ -14,7 +14,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'Discord OAuth2 - add-strategy',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
security: [
{
bearerAuth: []

View File

@ -17,7 +17,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'Discord OAuth2 - callback-add-strategy',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -15,7 +15,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'Discord OAuth2 - callback',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -13,7 +13,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'Discord OAuth2 - signin',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -14,7 +14,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'GitHub OAuth2 - add-strategy',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
security: [
{
bearerAuth: []

View File

@ -17,7 +17,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'GitHub OAuth2 - callback-add-strategy',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -15,7 +15,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'GitHub OAuth2 - callback',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -13,7 +13,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'GitHub OAuth2 - signin',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -14,7 +14,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'Google OAuth2 - add-strategy',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
security: [
{
bearerAuth: []

View File

@ -17,7 +17,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'Google OAuth2 - callback-add-strategy',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -15,7 +15,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'Google OAuth2 - callback',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -13,7 +13,7 @@ type QuerySchemaType = Static<typeof querySchema>
const getServiceSchema: FastifySchema = {
description: 'Google OAuth2 - signin',
tags: ['users'] as string[],
tags: ['oauth2'] as string[],
querystring: querySchema,
response: {
200: Type.String(),

View File

@ -1,5 +1,6 @@
import tap from 'tap'
import sinon from 'sinon'
import jwt from 'jsonwebtoken'
import { application } from '../../../../application.js'
import { authenticateUserTest } from '../../../../__test__/utils/authenticateUserTest.js'
@ -13,8 +14,7 @@ await tap.test('POST /users/refresh-token', async (t) => {
})
await t.test('succeeds', async (t) => {
const { accessToken, refreshToken, refreshTokenStubValue } =
await authenticateUserTest()
const { refreshToken, refreshTokenStubValue } = await authenticateUserTest()
sinon.stub(prisma, 'refreshToken').value({
...refreshTokenStubValue,
findFirst: async () => {
@ -28,9 +28,6 @@ await tap.test('POST /users/refresh-token', async (t) => {
const response = await application.inject({
method: 'POST',
url: '/users/refresh-token',
headers: {
authorization: `Bearer ${accessToken}`
},
payload: { refreshToken }
})
const responseJson = response.json()
@ -62,6 +59,9 @@ await tap.test('POST /users/refresh-token', async (t) => {
return refreshTokenExample
}
})
sinon.stub(jwt, 'verify').value(() => {
throw new Error('Invalid token')
})
const response = await application.inject({
method: 'POST',
url: '/users/refresh-token',

View File

@ -9,7 +9,7 @@ import {
jwtSchema,
expiresIn
} from '../../../tools/utils/jwtToken.js'
import { UserJWT } from '../../../models/User.js'
import { UserRefreshJWT } from '../../../models/User.js'
import { JWT_REFRESH_SECRET } from '../../../tools/configurations/index.js'
const bodyPostRefreshTokenSchema = Type.Object({
@ -43,20 +43,20 @@ export const postRefreshTokenUser: FastifyPluginAsync = async (fastify) => {
schema: postRefreshTokenSchema,
handler: async (request, reply) => {
const { refreshToken } = request.body
const foundRefreshToken = await prisma.refreshToken.findFirst({
where: { token: refreshToken }
})
if (foundRefreshToken == null) {
throw fastify.httpErrors.forbidden()
}
try {
const userJWT = jwt.verify(
foundRefreshToken.token,
const userRefreshJWT = jwt.verify(
refreshToken,
JWT_REFRESH_SECRET
) as UserJWT
) as UserRefreshJWT
const foundRefreshToken = await prisma.refreshToken.findFirst({
where: { token: userRefreshJWT.tokenUUID }
})
if (foundRefreshToken == null) {
throw fastify.httpErrors.forbidden()
}
const accessToken = generateAccessToken({
id: userJWT.id,
currentStrategy: userJWT.currentStrategy
id: userRefreshJWT.id,
currentStrategy: userRefreshJWT.currentStrategy
})
reply.statusCode = 200
return {

View File

@ -25,6 +25,11 @@ await tap.test('PUT /users/reset-password', async (t) => {
return userExample
}
})
sinon.stub(prisma, 'refreshToken').value({
deleteMany: async () => {
return { count: 1 }
}
})
const response = await application.inject({
method: 'PUT',
url: '/users/reset-password',

View File

@ -39,7 +39,7 @@ export const putResetPasswordUser: FastifyPluginAsync = async (fastify) => {
user?.temporaryExpirationToken != null &&
user.temporaryExpirationToken.getTime() > Date.now()
if (user == null || !isValidTemporaryToken) {
throw fastify.httpErrors.badRequest('"tempToken" is invalid')
throw fastify.httpErrors.badRequest('`temporaryToken` is invalid.')
}
const hashedPassword = await bcrypt.hash(password, 12)
await prisma.user.update({
@ -52,6 +52,11 @@ export const putResetPasswordUser: FastifyPluginAsync = async (fastify) => {
temporaryExpirationToken: null
}
})
await prisma.refreshToken.deleteMany({
where: {
userId: user.id
}
})
reply.statusCode = 200
return 'The new password has been saved!'
}

View File

@ -1,9 +1,11 @@
import tap from 'tap'
import sinon from 'sinon'
import jwt from 'jsonwebtoken'
import { application } from '../../../../application.js'
import prisma from '../../../../tools/database/prisma.js'
import { refreshTokenExample } from '../../../../models/RefreshToken.js'
import { UserRefreshJWT } from '../../../../models/User.js'
await tap.test('POST /users/signout', async (t) => {
t.afterEach(() => {
@ -17,10 +19,18 @@ await tap.test('POST /users/signout', async (t) => {
},
delete: async () => {}
})
sinon.stub(jwt, 'verify').value(() => {
const value: UserRefreshJWT = {
id: 1,
tokenUUID: refreshTokenExample.token,
currentStrategy: 'Local'
}
return value
})
const response = await application.inject({
method: 'POST',
url: '/users/signout',
payload: { refreshToken: refreshTokenExample.token }
payload: { refreshToken: 'jwt token' }
})
t.equal(response.statusCode, 200)
})

View File

@ -1,12 +1,15 @@
import { Static, Type } from '@sinclair/typebox'
import { FastifyPluginAsync, FastifySchema } from 'fastify'
import jwt from 'jsonwebtoken'
import prisma from '../../../tools/database/prisma.js'
import { fastifyErrors } from '../../../models/utils.js'
import { refreshTokensSchema } from '../../../models/RefreshToken.js'
import { JWT_REFRESH_SECRET } from '../../../tools/configurations/index.js'
import { UserRefreshJWT } from '../../../models/User.js'
import { jwtSchema } from '../../../tools/utils/jwtToken.js'
const bodyPostSignoutSchema = Type.Object({
refreshToken: refreshTokensSchema.token
refreshToken: jwtSchema.refreshToken
})
type BodyPostSignoutSchemaType = Static<typeof bodyPostSignoutSchema>
@ -32,21 +35,27 @@ export const postSignoutUser: FastifyPluginAsync = async (fastify) => {
schema: postSignoutSchema,
handler: async (request, reply) => {
const { refreshToken } = request.body
const token = await prisma.refreshToken.findFirst({
where: {
token: refreshToken
try {
const userRefreshJWT = jwt.verify(
refreshToken,
JWT_REFRESH_SECRET
) as UserRefreshJWT
const foundRefreshToken = await prisma.refreshToken.findFirst({
where: { token: userRefreshJWT.tokenUUID }
})
if (foundRefreshToken == null) {
throw fastify.httpErrors.notFound()
}
})
if (token == null) {
await prisma.refreshToken.delete({
where: {
id: foundRefreshToken.id
}
})
reply.statusCode = 200
return {}
} catch {
throw fastify.httpErrors.notFound()
}
await prisma.refreshToken.delete({
where: {
id: token.id
}
})
reply.statusCode = 200
return {}
}
})
}

View File

@ -1,6 +1,6 @@
import dotenv from 'dotenv'
import { readPackage } from 'read-pkg'
import { FastifyDynamicSwaggerOptions } from 'fastify-swagger'
import { FastifyDynamicSwaggerOptions } from '@fastify/swagger'
dotenv.config()
@ -16,11 +16,11 @@ export const swaggerOptions: FastifyDynamicSwaggerOptions = {
},
tags: [
{ name: 'users' },
{ name: 'oauth2' },
{ name: 'guilds' },
{ name: 'channels' },
{ name: 'messages' },
{ name: 'members' },
{ name: 'uploads' }
{ name: 'members' }
],
components: {
securitySchemes: {

View File

@ -1,6 +1,6 @@
import dotenv from 'dotenv'
import nodemailer from 'nodemailer'
import type SMTPTransport from 'nodemailer/lib/smtp-transport.js'
import type SMTPTransport from 'nodemailer/lib/smtp-transport/index.js'
dotenv.config()
const EMAIL_PORT = parseInt(process.env.EMAIL_PORT ?? '465', 10)

View File

@ -8,7 +8,9 @@ await tap.test('tools/plugins/socket-io', async (t) => {
const PORT = 3030
const application = fastify()
await application.register(fastifySocketIo)
await application.listen(PORT)
await application.listen({
port: PORT
})
t.not(application.io, null)
await application.close()
})

View File

@ -61,5 +61,5 @@ export default fastifyPlugin(
request.user = user
})
},
{ fastify: '3.x' }
{ fastify: '4.x' }
)

View File

@ -80,10 +80,10 @@ export default fastifyPlugin(
emitToAuthorizedUsers,
emitToMembers
}
await fastify.decorate('io', io)
await fastify.addHook('onClose', (fastify) => {
fastify.decorate('io', io)
fastify.addHook('onClose', (fastify) => {
fastify.io.instance.close()
})
},
{ fastify: '3.x' }
{ fastify: '4.x' }
)

View File

@ -1,3 +1,5 @@
import { randomUUID } from 'node:crypto'
import { Type } from '@sinclair/typebox'
import jwt from 'jsonwebtoken'
import ms from 'ms'
@ -22,7 +24,7 @@ export const jwtSchema = {
refreshToken: Type.String(),
expiresIn: Type.Integer({
description:
'expiresIn is how long, in milliseconds, until the returned accessToken expires'
'expiresIn is how long, in milliseconds, until the accessToken expires'
}),
type: Type.Literal('Bearer')
}
@ -30,15 +32,20 @@ export const jwtSchema = {
export const expiresIn = ms(JWT_ACCESS_EXPIRES_IN)
export const generateAccessToken = (user: UserJWT): string => {
return jwt.sign(user, JWT_ACCESS_SECRET, {
expiresIn: JWT_ACCESS_EXPIRES_IN
})
return jwt.sign(user, JWT_ACCESS_SECRET, { expiresIn })
}
export const generateRefreshToken = async (user: UserJWT): Promise<string> => {
const refreshToken = jwt.sign(user, JWT_REFRESH_SECRET)
const tokenUUID = randomUUID()
const refreshToken = jwt.sign(
{
...user,
tokenUUID
},
JWT_REFRESH_SECRET
)
await prisma.refreshToken.create({
data: { token: refreshToken, userId: user.id }
data: { token: tokenUUID, userId: user.id }
})
return refreshToken
}

View File

@ -3,7 +3,7 @@ import fs from 'node:fs'
import axios from 'axios'
import FormData from 'form-data'
import { FastifyInstance, FastifyRequest } from 'fastify'
import { Multipart } from 'fastify-multipart'
import { Multipart } from '@fastify/multipart'
import {
FILE_UPLOADS_API_KEY,

View File

@ -3,12 +3,12 @@
"target": "ESNext",
"module": "ESNext",
"lib": ["ESNext"],
"moduleResolution": "node",
"moduleResolution": "Node",
"outDir": "./build",
"rootDir": "./src",
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"esModuleInterop": true
},
"exclude": ["node_modules", "generators"]
}
}