Compare commits

..

31 Commits

Author SHA1 Message Date
Ratstail91 8ab786b934 Hotfix a hotfix 2023-12-24 05:00:49 +11:00
Ratstail91 72a4b0e101 HOTFIX: kick banned accounts 2023-12-24 04:48:28 +11:00
Ratstail91 59c610bdd8 Fixed Date API bug 2023-12-24 02:48:07 +11:00
Ratstail91 1908413bd2 Updated libraries, docker engine version, docker distro version 2023-12-23 23:49:11 +11:00
Kayne Ruse 3c790f51c7 Bump 2023-06-27 04:26:58 +10:00
Kayne Ruse 44e19154ab Fixed a nasty async race condition 2023-06-27 04:25:52 +10:00
Kayne Ruse fd0c40d444 Docker behaviour changed, fixed 2023-06-26 23:19:53 +10:00
Kayne Ruse d3e90f7d5d Updated dependencies, bumped patch version 2023-06-26 23:05:26 +10:00
Kayne Ruse 98887eecce Fixed a logout bug 2023-06-26 22:26:06 +10:00
Kayne Ruse 95e6bd178e Fixed a filename typo 2023-05-27 23:56:22 +10:00
Kayne Ruse ac7c8d04ed Last patch today, I'm happy with this rn 2023-05-15 11:33:32 +10:00
Kayne Ruse fd44712e37 BUGFIX: clashing pending signups fixed 2023-05-15 11:02:51 +10:00
Kayne Ruse b3c7f7cb5e Added ip-banning middleware, under development 2023-05-15 10:38:10 +10:00
Kayne Ruse db03373892 Spam attack throttling added 2023-05-15 09:13:09 +10:00
Kayne Ruse 267ecaa705 Added a typecheck to password field 2023-05-15 08:03:54 +10:00
Kayne Ruse 3a8cfd39ed BUGFIX: force a logout if refresh token is too old 2023-05-05 03:56:24 +10:00
Kayne Ruse b157ef18ff Updated dependencies 2023-05-03 21:31:30 +10:00
Kayne Ruse 500035284f Updated depencencies, bumped version 2023-03-25 01:49:17 +11:00
Kayne Ruse c5360a70d6 Updated dependencies 2023-03-19 02:52:44 +11:00
Kayne Ruse cf4c8a0f99 Updated dependencies 2023-02-21 09:30:12 +11:00
Kayne Ruse 21527d8931 Updated dependencies, License 2023-01-12 08:08:27 +11:00
Kayne Ruse a54e802942 Bumped version number 2023-01-04 12:56:04 +00:00
Kayne Ruse f8abd9110d Switched to a slim docker distro 2023-01-04 23:51:43 +11:00
Kayne Ruse 406345ada1 Updated libraries 2022-12-31 19:02:27 +00:00
Kayne Ruse d79a70d66f Bumped version number 2022-12-01 12:07:10 +00:00
Kayne Ruse cec30620ec BUGFIX: clear out old refresh tokens 2022-12-01 12:06:20 +00:00
Kayne Ruse 763efb75bf Updated dependencies 2022-11-29 05:06:10 +00:00
Kayne Ruse 77260d5d30 Updated dependencies 2022-11-13 02:15:31 +00:00
Kayne Ruse 157bb5dd90 Updated dependencies 2022-08-01 10:39:30 +01:00
Kayne Ruse 20657fda22 Minor tweak 2022-07-26 13:37:10 +01:00
Kayne Ruse 168bc695b6 Tweaked WEB_ORIGIN 2022-07-26 11:49:34 +01:00
26 changed files with 4550 additions and 9916 deletions
+2 -1
View File
@@ -2,8 +2,9 @@ WEB_PROTOCOL=http
WEB_ADDRESS=localhost
WEB_RESET_ADDRESS=localhost/reset
WEB_PORT=3200
WEB_ORIGIN=http://localhost:3001
DB_HOSTNAME=database
DB_HOSTNAME=localhost
DB_DATABASE=auth
DB_USERNAME=auth
DB_PASSWORD=charizard
-23
View File
@@ -1,23 +0,0 @@
name: Node.js CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
name: Run test suites
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm run build --if-present
- run: npm test
+2 -2
View File
@@ -1,7 +1,7 @@
FROM node:16
FROM node:21-bookworm-slim
WORKDIR "/app"
COPY package*.json ./
COPY package*.json /app
RUN npm install --production
COPY . /app
EXPOSE 3200
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2021 Kayne Ruse, KR Game Studios
Copyright (c) 2021-2023 Kayne Ruse, KR Game Studios
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.
+7 -7
View File
@@ -29,8 +29,9 @@ const question = (prompt, def = null) => {
(async () => {
//project configuration
const appName = await question('App Name', 'auth');
const appWebOrigin = await question('Web Origin', `example.com`);
const appWebAddress = await question('Web Addr', `${appName}.${appWebOrigin}`);
const appWebProtocol = await question('Web Protocol', 'https');
const appWebAddress = await question('Web Addr', `${appName}.example.com`);
const appWebOrigin = await question('Web Origin', `${appWebProtocol}://example.com`); //TODO: clean these up properly
const postValidationHookArray = await question('Post Validation Hook Array', '');
const resetAddress = await question('Reset Addr', `example.com/reset`);
const appPort = await question('App Port', '3200');
@@ -54,8 +55,7 @@ const question = (prompt, def = null) => {
//generate the files
const ymlfile = `
version: '3'
version: '3.8'
services:
${appName}:
build:
@@ -70,7 +70,7 @@ services:
- "traefik.http.routers.${appName}router.service=${appName}service@docker"
- "traefik.http.services.${appName}service.loadbalancer.server.port=${appPort}"
environment:
- WEB_PROTOCOL=https
- WEB_PROTOCOL=${appWebProtocol}
- WEB_ORIGIN=${appWebOrigin}
- WEB_ADDRESS=${appWebAddress}
- HOOK_POST_VALIDATION_ARRAY=${postValidationHookArray}
@@ -107,7 +107,7 @@ services:
- ./startup.sql:/docker-entrypoint-initdb.d/startup.sql:ro
traefik_${appName}:
container_name: ${appName}_traefik
image: "traefik:v2.4"
image: "traefik:v2.10"
container_name: "traefik"
command:
- "--log.level=ERROR"
@@ -132,7 +132,7 @@ networks:
`;
const dockerfile = `
FROM node:16
FROM node:21-bookworm-slim
WORKDIR "/app"
COPY package*.json ./
RUN npm install --production
+4395 -9478
View File
File diff suppressed because it is too large Load Diff
+12 -13
View File
@@ -1,13 +1,12 @@
{
"name": "auth-server",
"version": "1.6.1",
"version": "1.8.2",
"description": "An API centric auth server. Uses Sequelize and mariaDB by default.",
"main": "server/server.js",
"scripts": {
"start": "node server/server.js",
"dev": "npm run watch:server",
"watch:server": "nodemon . --ext js,jsx,json --ignore 'node_modules/*'",
"test": "jest --coverage --collectCoverageFrom=server/**/*.{js,jsx}"
"watch:server": "nodemon . --ext js,jsx,json --ignore 'node_modules/*'"
},
"repository": {
"type": "git",
@@ -23,17 +22,17 @@
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^8.6.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mariadb": "^2.5.4",
"node-cron": "^2.0.3",
"node-fetch": "^2.6.6",
"nodemailer": "^6.6.3",
"sequelize": "^6.6.5"
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"mariadb": "^3.2.3",
"node-cron": "^3.0.3",
"node-fetch": "^2.7.0",
"nodemailer": "^6.9.7",
"npm": "^9.9.2",
"sequelize": "^6.35.2"
},
"devDependencies": {
"jest": "^27.5.1",
"nodemon": "^2.0.12"
"nodemon": "^3.0.2"
}
}
+5 -4
View File
@@ -11,9 +11,6 @@ router.post('/signup', require('./signup'));
router.get('/validation', require('./validation'));
router.post('/login', require('./login'));
//refresh token
router.post('/token', require('./token'));
//password recover and reset
router.post('/recover', require('./password-recover'));
router.get('/reset', require('./password-redirect'));
@@ -22,9 +19,10 @@ router.patch('/reset', require('./password-reset'));
//logouts allowed when banned, and when the token itself is invalid
router.delete('/logout', require('./logout'));
//middleware
//authenticate token
router.use(tokenAuth);
//middleware
router.use(async (req, res, next) => {
const record = await accounts.findOne({
where: {
@@ -43,6 +41,9 @@ router.use(async (req, res, next) => {
next();
});
//refresh token
router.post('/token', require('./token'));
//basic account management (needs a token)
router.get('/account', require('./account-query'));
router.patch('/account', require('./account-update'));
+1 -1
View File
@@ -49,7 +49,7 @@ const route = async (req, res) => {
}
//generate the JWTs
const { accessToken, refreshToken } = tokenGenerateRefresh(account.index, account.email, account.username, account.type, account.admin, account.mod);
const { accessToken, refreshToken } = await tokenGenerateRefresh(account.index, account.email, account.username, account.type, account.admin, account.mod);
//set the cookie
res.cookie('refreshToken', refreshToken, { path: '/', httpOnly: true, secure: true, sameSite: 'none', maxAge: 60 * 60 * 24 * 30 * 1000 }); //30 days
+45 -1
View File
@@ -19,6 +19,13 @@ const route = async (req, res) => {
return res.status(401).send(validateErr);
}
//script throttle
const throttle = await checkThrottle(req.body.email);
if (throttle) {
console.warn(`Spam Throttled\t${req.body.email} (${req.body.username})`);
return res.status(401).send(throttle);
}
//generate the password hash
const hash = await bcrypt.hash(req.body.password, await bcrypt.genSalt(11));
@@ -83,6 +90,10 @@ const validateDetails = async (body) => {
return 'Missing password';
}
if (typeof body.password != "string") {
return 'Invalid password';
}
if (body.password.length < 8) {
return 'Password too short';
}
@@ -90,8 +101,41 @@ const validateDetails = async (body) => {
return null;
};
const checkThrottle = async (email) => {
//check email delay
const prev = await pendingSignups.findOne({
where: {
email: email,
}
});
const DateOffset = ( offset ) => { //Thanks, SO!
return new Date( +new Date + offset );
}
if (!!prev && prev.updatedAt > DateOffset( -5000 )) {
return "An unknown error occurred";
}
return null;
}
const registerPendingSignup = async (body, hash, token) => {
const record = await pendingSignups.upsert({
//BUGFIX: delete existing pending signups that clash
await pendingSignups.destroy({
where: {
email: body.email
}
});
await pendingSignups.destroy({
where: {
username: body.username
}
});
//record it
const record = await pendingSignups.create({
email: body.email,
username: body.username,
hash: hash,
+1 -3
View File
@@ -1,10 +1,8 @@
const jwt = require('jsonwebtoken');
const tokenRefresh = require('../utilities/token-refresh');
//auth/token
module.exports = async (req, res) => {
return tokenRefresh(req.cookies.refreshToken || '', (err, accessToken, refreshToken) => {
return await tokenRefresh(req.cookies.refreshToken || '', (err, accessToken, refreshToken) => {
if (err) {
return res.status(err).end();
}
+1 -1
View File
@@ -44,7 +44,7 @@ const route = async (req, res) => {
hooks = JSON.parse(process.env.HOOK_POST_VALIDATION_ARRAY);
if (!Array.isArray(hooks)) {
throw 'isArray() check failed';
throw 'post validation hook isArray() check failed';
}
//authenticate the hooks
@@ -0,0 +1,17 @@
const Sequelize = require('sequelize');
const sequelize = require('..');
//DOCS: this isn't set by anything - it's a stub for now
module.exports = sequelize.define('bannedIPAddresses', {
content: {
type: 'varchar(320)',
unique: true
},
expiry: {
type: 'DATETIME',
allowNull: true,
defaultValue: null
},
});
+2 -1
View File
@@ -2,5 +2,6 @@ module.exports = {
tokens: require('./tokens'),
accounts: require('./accounts'),
pendingSignups: require('./pending-signups'),
recovery: require('./recovery')
recovery: require('./recovery'),
bannedIPAddresses: require("./banned-ip-addresses"),
};
+4 -1
View File
@@ -13,7 +13,7 @@ app.use(express.json());
app.use(cors({
credentials: true,
origin: [`${process.env.WEB_PROTOCOL}://${process.env.WEB_ORIGIN}`],
origin: [`${process.env.WEB_ORIGIN}`],
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Set-Cookie'],
exposedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'Set-Cookie'],
}));
@@ -23,6 +23,9 @@ app.use(cookieParser());
//database connection
const database = require('./database');
//ip-based management
app.use(require('./utilities/banned-ip-addresses-middleware'));
//access the admin
app.use('/admin', require('./admin'));
@@ -0,0 +1,33 @@
const { Op } = require("sequelize");
const { bannedIPAddresses } = require('../database/models');
//middleware to manage banned IP addresses
module.exports = async (req, res, next) => {
const address = req.header('x-forwarded-for') || req.socket.remoteAddress;
const record = await bannedIPAddresses.findOne({
where: {
content: address,
expiry: {
[Op.or]: {
//future or forever
[Op.gt]: Date.now(),
[Op.eq]: null,
}
}
}
});
//log the access timestamp
const date = new Date();
if (!!record) {
console.log(`IP blocked\t${address}\t\t\t${date.toTimeString()}`);
return res.status(403).send("IP address banned");
}
// console.log(`IP allowed\t${address}\t\t\t${date.toTimeString()}`);
return next();
};
+2 -2
View File
@@ -1,7 +1,7 @@
const { tokens } = require('../database/models');
module.exports = (refreshToken) => {
tokens.destroy({
module.exports = async (refreshToken) => {
await tokens.destroy({
where: {
token: refreshToken || ''
}
+2 -2
View File
@@ -2,7 +2,7 @@ const jwt = require('jsonwebtoken');
const { tokens } = require('../database/models');
//generates a JWT token based on the given arguments
module.exports = (index, email, username, type, admin, mod) => {
module.exports = async (index, email, username, type, admin, mod) => {
const content = {
index,
email,
@@ -16,7 +16,7 @@ module.exports = (index, email, username, type, admin, mod) => {
const accessToken = jwt.sign(content, process.env.SECRET_ACCESS, { expiresIn: '10m', issuer: 'auth' });
const refreshToken = jwt.sign(content, process.env.SECRET_REFRESH, { expiresIn: '30d', issuer: 'auth' });
tokens.create({ token: refreshToken, email: email });
await tokens.create({ token: refreshToken, email: email });
return { accessToken, refreshToken };
};
+4 -4
View File
@@ -19,15 +19,15 @@ module.exports = async (oldRefreshToken, callback) => {
return callback(403);
}
jwt.verify(oldRefreshToken, process.env.SECRET_REFRESH, (err, user) => {
jwt.verify(oldRefreshToken, process.env.SECRET_REFRESH, async (err, user) => {
if (err) {
return callback(403);
}
const { accessToken, refreshToken } = generate(user.index, user.email, user.username, user.type, user.admin, user.mod);
await destroy(oldRefreshToken);
destroy(oldRefreshToken);
const { accessToken, refreshToken } = await generate(user.index, user.email, user.username, user.type, user.admin, user.mod);
return callback(null, accessToken, refreshToken);
return await callback(null, accessToken, refreshToken);
});
};
-117
View File
@@ -1,117 +0,0 @@
describe('POST /auth/login', () => {
beforeEach(() => {
jest.resetModules();
//fix util with jest (used by bcrypt's compare)
jest.doMock('util', () => ({
promisify: f => async () => f()
}));
//mock out bcrypt
jest.doMock('bcryptjs', () => ({
genSalt: async amount => {
expect(amount).toBe(11);
return 'salt';
},
hash: async (password, salt) => {
expect(password).toBe('password');
return 'hashed-password';
},
compare: (lhs, rhs) => {
return lhs === rhs;
}
}));
//mock out jsonwebtoken
jest.doMock('jsonwebtoken', () => ({
sign: (content, secretAccess, opts) => {
return JSON.stringify(content);
},
verify: (token, secretAccess, callback) => {
return callback(null, JSON.parse(token));
},
}));
//mock out the sequelize library
jest.doMock('sequelize', () => {
return {
Op: {
//
}
}
});
//mock out the database object
jest.doMock('../../server/database', () => {
const mSequelize = {
authenticate: jest.fn(),
define: jest.fn(),
};
const actualSequelize = jest.requireActual('sequelize');
return { Sequelize: jest.fn(() => mSequelize), DataTypes: actualSequelize.DataTypes };
});
//mock out the database models
jest.doMock('../../server/database/models', () => ({
accounts: {
findOne: async (config) => { //can't find any (signup state)
expect(config?.where?.email).toBe('email@example.com');
return {
index: 0,
email: config?.where?.email,
username: 'username',
type: 'alpha',
admin: false,
mod: false,
};
},
update: async (values, config) => {
//Do nothing
}
},
tokens: {
create: async (record) => {
//Do nothing
}
}
}));
});
test('Basic valid login attempt', async () => {
//arguments
const req = {
body: {
email: 'email@example.com',
password: 'password',
}
};
const res = {
status: code => {
expect(code).toBe(200);
return {
json: tokens => {
//decode and analyze the JWT payload
const accessToken = JSON.parse(tokens.accessToken);
expect(accessToken.email).toBe('email@example.com');
expect(accessToken.username).toBe('username');
},
send: msg => { throw msg; },
end: () => null
}
}
}
//test
const route = require('../../server/auth/login');
const result = await route(req, res);
expect(result).toBe(null);
});
});
-98
View File
@@ -1,98 +0,0 @@
describe('POST /auth/signup', () => {
beforeEach(() => {
jest.resetModules();
//mock out bcrypt
jest.doMock('bcryptjs', () => ({
genSalt: async amount => {
expect(amount).toBe(11);
return 'salt';
},
hash: async (password, salt) => {
expect(password).toBe('password');
return 'hashed-password';
}
}));
//mock out nodemailer
jest.doMock('nodemailer', () => ({
createTransport: jest.fn(config => {
//TODO: test config?
return { //return a fake transport object
sendMail: async email => {
expect(email.to).toBe('email@example.com');
return { //return a fake info object
accepted: [ email.to ]
}
}
};
}),
}));
//mock out the sequelize library
jest.doMock('sequelize', () => {
return {
Op: {
//
}
}
});
//mock out the database object
jest.doMock('../../server/database', () => {
const mSequelize = {
authenticate: jest.fn(),
define: jest.fn(),
};
const actualSequelize = jest.requireActual('sequelize');
return { Sequelize: jest.fn(() => mSequelize), DataTypes: actualSequelize.DataTypes };
});
//mock out the database models
jest.doMock('../../server/database/models', () => ({
accounts: {
findOne: () => null //can't find any (signup state)
},
pendingSignups: {
upsert: jest.fn(async record => {
expect(record.email).toBe('email@example.com');
expect(record.username).toBe('username');
expect(record.hash).toBe('hashed-password');
expect(record.contact).toBe(true);
//token is a random UUID
})
}
}));
});
test('Basic valid signup attempt', async () => {
//arguments
const req = {
body: {
email: 'email@example.com',
username: 'username',
password: 'password',
contact: true
}
};
const res = {
status: code => {
expect(code).toBe(200);
return {
send: msg => expect(msg).toBe('Validation email sent!'),
end: () => null
}
}
}
//test
const route = require('../../server/auth/signup');
const result = await route(req, res);
expect(result).toBe(null);
});
});
-65
View File
@@ -1,65 +0,0 @@
describe('Integration Test Suite', () => {
beforeEach(() => {
jest.resetModules();
//mock dotenv
jest.doMock('dotenv', () => ({
config: () => null
}));
//mock express
jest.doMock('express', () => {
const express = () => ({
identity: 'app',
use: () => null,
get: () => null,
});
express.Router = () => ({
identity: 'Router',
use: () => null,
get: () => null,
post: () => null,
patch: () => null,
delete: () => null,
});
express.json = () => 'json';
return express;
});
//mock http
jest.doMock('http', () => ({
Server: app => {
expect(app.identity).toBe('app');
return {
listen: (port, cb) => cb()
}
}
}));
//mock sequelize
class Seq {
sync() {}
define() {}
static INTEGER() {}
};
jest.doMock('sequelize', () => {
return Seq;
});
//mock node-cron
jest.doMock('node-cron', () => {
return {
schedule: () => null
}
});
});
test('Start The Server', () => {
const serv = require('../server/server');
});
});
-87
View File
@@ -1,87 +0,0 @@
describe('token-auth', () => {
beforeEach(() => {
jest.resetModules();
//mock out jsonwebtoken
jest.doMock('jsonwebtoken', () => ({
verify: (token, secretAccess, callback) => {
if (token != 'invalid') {
expect(token).toBe('testtoken');
return callback(null, { username: 'username' });
} else {
expect(token).toBe('invalid');
return callback('Misc. error');
}
},
}));
});
test('Required Functionality', () => {
const tokenAuth = require('../../server/utilities/token-auth');
const req = {
headers: {
authorization: 'Bearer testtoken'
}
};
const res = {
status: code => {
expect(code).toBe(null);
return msg => { throw msg; };
}
};
tokenAuth(req, res, () => null);
expect(req.user.username).toBe('username');
});
test('Missing Token', () => {
const tokenAuth = require('../../server/utilities/token-auth');
const req = {
headers: {
//
}
};
const res = {
status: code => {
expect(code).toBe(401);
return {
send: msg => {
expect(msg).toBe('No token found');
return null;
}
};
}
};
tokenAuth(req, res, () => null);
});
test('Invalid Token', () => {
const tokenAuth = require('../../server/utilities/token-auth');
const req = {
headers: {
authorization: 'Bearer invalid'
}
};
const res = {
status: code => {
expect(code).toBe(403);
return {
send: msg => {
expect(msg).toBe('Misc. error');
return null;
}
};
}
};
tokenAuth(req, res, () => null);
});
});
-1
View File
@@ -1 +0,0 @@
ALTER TABLE `accounts` CHANGE `id` `index` INT( 11 ) NOT NULL AUTO_INCREMENT;
-1
View File
@@ -1 +0,0 @@
DROP TABLE tokens;
+14 -2
View File
@@ -9,6 +9,12 @@ const TokenProvider = props => {
//state to be used
const [accessToken, setAccessToken] = useState('');
//force a logout under certain conditions
const forceLogout = () => {
localStorage.removeItem("accessToken");
setAccessToken("");
};
//make the access token persist between reloads
useEffect(() => {
setAccessToken(localStorage.getItem("accessToken") || '');
@@ -25,7 +31,7 @@ const TokenProvider = props => {
let bearer = accessToken;
//if expired (10 minutes, normally)
const expired = new Date(decode(accessToken).exp * 1000) < Date.now();
const expired = new Date(decode(accessToken).exp) < Date.now() / 1000;
if (expired) {
//BUGFIX: if logging out, just skip over the refresh token
@@ -47,6 +53,9 @@ const TokenProvider = props => {
//any errors, throw them
if (!response.ok) {
if (response.status == 403) {
forceLogout();
}
throw `${response.status}: ${await response.text()}`;
}
@@ -71,7 +80,7 @@ const TokenProvider = props => {
//access the refreshed token via callback
const tokenCallback = async (cb) => {
//if expired (10 minutes, normally)
const expired = new Date(decode(accessToken).exp * 1000) < Date.now();
const expired = new Date(decode(accessToken).exp) < Date.now() / 1000;
if (expired) {
//ping the auth server for a new token
@@ -82,6 +91,9 @@ const TokenProvider = props => {
//any errors, throw them
if (!response.ok) {
if (response.status == 403) {
forceLogout();
}
throw `${response.status}: ${await response.text()}`;
}