Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Add rate limits for auth attempts

Hakan Shehu2660f3d3a9a8
diff --git a/apps/desktop/src/main/scheduler.ts b/apps/desktop/src/main/scheduler.ts
index a7fc7373..c57599d1 100644
--- a/apps/desktop/src/main/scheduler.ts
+++ b/apps/desktop/src/main/scheduler.ts
@@ -130,6 +130,11 @@ class Scheduler {
}
private async executeJob(state: JobState) {
+ if (!this.states.has(state.id)) {
+ this.deleteJob(state);
+ return;
+ }
+
if (state.running) {
return;
}
@@ -164,6 +169,14 @@ class Scheduler {
}
}
+ private async deleteJob(state: JobState) {
+ if (state.timeout) {
+ clearTimeout(state.timeout);
+ }
+
+ this.states.delete(state.id);
+ }
+
private async scheduleJobs() {
this.schedule({ type: 'sync_servers' });
this.schedule({ type: 'sync_deleted_tokens' });
@@ -199,12 +212,12 @@ class Scheduler {
state.input.type === 'sync_account' &&
state.input.accountId === accountId
) {
- this.states.delete(jobId);
+ this.deleteJob(state);
} else if (
state.input.type === 'connect_socket' &&
state.input.accountId === accountId
) {
- this.states.delete(jobId);
+ this.deleteJob(state);
}
}
}
@@ -274,7 +287,7 @@ class Scheduler {
clearTimeout(state.timeout);
}
- this.states.delete(jobId);
+ this.deleteJob(state);
}
}
}
diff --git a/apps/desktop/src/shared/lib/http-client.ts b/apps/desktop/src/shared/lib/http-client.ts
index 4dff5d76..f7a82675 100644
--- a/apps/desktop/src/shared/lib/http-client.ts
+++ b/apps/desktop/src/shared/lib/http-client.ts
@@ -65,7 +65,7 @@ class HttpClient {
return true;
}
const status = error.response?.status ?? 0;
- return (status >= 500 && status < 600) || status === 429;
+ return status >= 500 && status < 600;
}
private buildAxiosInstance(config: HttpClientRequestConfig): AxiosInstance {
diff --git a/apps/server/src/api.ts b/apps/server/src/api.ts
index e1171785..94beed77 100644
--- a/apps/server/src/api.ts
+++ b/apps/server/src/api.ts
@@ -4,6 +4,7 @@ import express, { Request, Response } from 'express';
import http from 'http';
import { clientRouter } from '@/routes/client';
+import { ipMiddleware } from '@/middlewares/ip';
import { socketService } from '@/services/socket-service';
import { createLogger } from '@/lib/logger';
@@ -19,6 +20,7 @@ export const initApi = async () => {
})
);
app.use(cors());
+ app.use(ipMiddleware);
app.get('/', (_: Request, res: Response) => {
res.send(
diff --git a/apps/server/src/controllers/client/accounts/account-sync.ts b/apps/server/src/controllers/client/accounts/account-sync.ts
index c5bfe485..4a7558fc 100644
--- a/apps/server/src/controllers/client/accounts/account-sync.ts
+++ b/apps/server/src/controllers/client/accounts/account-sync.ts
@@ -26,6 +26,28 @@ export const accountSyncHandler = async (
});
}
+ const device = await database
+ .selectFrom('devices')
+ .selectAll()
+ .where('id', '=', res.locals.account.deviceId)
+ .executeTakeFirst();
+
+ if (!device) {
+ return ResponseBuilder.notFound(res, {
+ code: ApiErrorCode.DeviceNotFound,
+ message: 'Device not found. Check your token.',
+ });
+ }
+
+ await database
+ .updateTable('devices')
+ .set({
+ synced_at: new Date(),
+ ip: res.locals.ip,
+ })
+ .where('id', '=', device.id)
+ .execute();
+
const workspaceOutputs: WorkspaceOutput[] = [];
const users = await database
.selectFrom('users')
diff --git a/apps/server/src/controllers/client/accounts/login-email.ts b/apps/server/src/controllers/client/accounts/login-email.ts
index 95bac9a0..d58581d7 100644
--- a/apps/server/src/controllers/client/accounts/login-email.ts
+++ b/apps/server/src/controllers/client/accounts/login-email.ts
@@ -6,14 +6,32 @@ import { sha256 } from 'js-sha256';
import { database } from '@/data/database';
import { accountService } from '@/services/account-service';
import { ResponseBuilder } from '@/lib/response-builder';
+import { rateLimitService } from '@/services/rate-limit-service';
export const loginWithEmailHandler = async (
req: Request,
res: Response
): Promise<void> => {
+ const ip = res.locals.ip;
+ const isIpRateLimited = await checkIpRateLimit(ip);
+ if (isIpRateLimited) {
+ return ResponseBuilder.tooManyRequests(res, {
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
const input: EmailLoginInput = req.body;
const email = input.email.toLowerCase();
+ const isEmailRateLimited = await checkEmailRateLimit(email);
+ if (isEmailRateLimited) {
+ return ResponseBuilder.tooManyRequests(res, {
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
const account = await database
.selectFrom('accounts')
.where('email', '=', email)
@@ -47,6 +65,23 @@ export const loginWithEmailHandler = async (
});
}
- const output = await accountService.buildLoginOutput(account);
+ const output = await accountService.buildLoginOutput(account, res.locals.ip);
return ResponseBuilder.success(res, output);
};
+
+const checkIpRateLimit = async (ip: string): Promise<boolean> => {
+ const rateLimitKey = `auth_ip_${ip}`;
+ return await rateLimitService.isRateLimited(rateLimitKey, {
+ limit: 50,
+ window: 600, // 10 minutes
+ });
+};
+
+const checkEmailRateLimit = async (email: string): Promise<boolean> => {
+ const emailHash = sha256(email);
+ const rateLimitKey = `auth_email_${emailHash}`;
+ return await rateLimitService.isRateLimited(rateLimitKey, {
+ limit: 10,
+ window: 600, // 10 minutes
+ });
+};
diff --git a/apps/server/src/controllers/client/accounts/login-google.ts b/apps/server/src/controllers/client/accounts/login-google.ts
index dd9616c4..a8128997 100644
--- a/apps/server/src/controllers/client/accounts/login-google.ts
+++ b/apps/server/src/controllers/client/accounts/login-google.ts
@@ -12,12 +12,23 @@ import axios from 'axios';
import { database } from '@/data/database';
import { accountService } from '@/services/account-service';
import { ResponseBuilder } from '@/lib/response-builder';
+import { rateLimitService } from '@/services/rate-limit-service';
+
const GoogleUserInfoUrl = 'https://www.googleapis.com/oauth2/v1/userinfo';
export const loginWithGoogleHandler = async (
req: Request,
res: Response
): Promise<void> => {
+ const ip = res.locals.ip;
+ const isIpRateLimited = await checkIpRateLimit(ip);
+ if (isIpRateLimited) {
+ return ResponseBuilder.tooManyRequests(res, {
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
const input: GoogleLoginInput = req.body;
const url = `${GoogleUserInfoUrl}?access_token=${input.access_token}`;
const userInfoResponse = await axios.get(url);
@@ -61,7 +72,10 @@ export const loginWithGoogleHandler = async (
.execute();
}
- const output = await accountService.buildLoginOutput(existingAccount);
+ const output = await accountService.buildLoginOutput(
+ existingAccount,
+ res.locals.ip
+ );
return ResponseBuilder.success(res, output);
}
@@ -85,6 +99,17 @@ export const loginWithGoogleHandler = async (
});
}
- const output = await accountService.buildLoginOutput(newAccount);
+ const output = await accountService.buildLoginOutput(
+ newAccount,
+ res.locals.ip
+ );
return ResponseBuilder.success(res, output);
};
+
+const checkIpRateLimit = async (ip: string): Promise<boolean> => {
+ const rateLimitKey = `auth_ip_${ip}`;
+ return await rateLimitService.isRateLimited(rateLimitKey, {
+ limit: 50,
+ window: 600, // 10 minutes
+ });
+};
diff --git a/apps/server/src/controllers/client/accounts/register-email.ts b/apps/server/src/controllers/client/accounts/register-email.ts
index f681ad00..8f05023f 100644
--- a/apps/server/src/controllers/client/accounts/register-email.ts
+++ b/apps/server/src/controllers/client/accounts/register-email.ts
@@ -13,16 +13,34 @@ import { database } from '@/data/database';
import { SelectAccount } from '@/data/schema';
import { accountService } from '@/services/account-service';
import { ResponseBuilder } from '@/lib/response-builder';
+import { rateLimitService } from '@/services/rate-limit-service';
-const SaltRounds = 10;
+const SaltRounds = 15;
export const registerWithEmailHandler = async (
req: Request,
res: Response
): Promise<void> => {
+ const ip = res.locals.ip;
+ const isIpRateLimited = await checkIpRateLimit(ip);
+ if (isIpRateLimited) {
+ return ResponseBuilder.tooManyRequests(res, {
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
const input: EmailRegisterInput = req.body;
const email = input.email.toLowerCase();
+ const isEmailRateLimited = await checkEmailRateLimit(email);
+ if (isEmailRateLimited) {
+ return ResponseBuilder.tooManyRequests(res, {
+ code: ApiErrorCode.TooManyRequests,
+ message: 'Too many authentication attempts. Please try again later.',
+ });
+ }
+
const existingAccount = await database
.selectFrom('accounts')
.selectAll()
@@ -75,6 +93,23 @@ export const registerWithEmailHandler = async (
});
}
- const output = await accountService.buildLoginOutput(account);
+ const output = await accountService.buildLoginOutput(account, res.locals.ip);
return ResponseBuilder.success(res, output);
};
+
+const checkIpRateLimit = async (ip: string): Promise<boolean> => {
+ const rateLimitKey = `auth_ip_${ip}`;
+ return await rateLimitService.isRateLimited(rateLimitKey, {
+ limit: 50,
+ window: 600, // 10 minutes
+ });
+};
+
+const checkEmailRateLimit = async (email: string): Promise<boolean> => {
+ const emailHash = sha256(email);
+ const rateLimitKey = `auth_email_${emailHash}`;
+ return await rateLimitService.isRateLimited(rateLimitKey, {
+ limit: 10,
+ window: 600, // 10 minutes
+ });
+};
diff --git a/apps/server/src/data/migrations.ts b/apps/server/src/data/migrations.ts
index 5c551d60..5d6261f8 100644
--- a/apps/server/src/data/migrations.ts
+++ b/apps/server/src/data/migrations.ts
@@ -34,11 +34,9 @@ const createDevicesTable: Migration = {
.addColumn('type', 'integer', (col) => col.notNull())
.addColumn('version', 'varchar(30)', (col) => col.notNull())
.addColumn('platform', 'varchar(30)')
- .addColumn('cpu', 'varchar(30)')
- .addColumn('hostname', 'varchar(30)')
+ .addColumn('ip', 'varchar(45)')
.addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('last_online_at', 'timestamptz')
- .addColumn('last_active_at', 'timestamptz')
+ .addColumn('synced_at', 'timestamptz')
.execute();
await db.schema
diff --git a/apps/server/src/data/redis.ts b/apps/server/src/data/redis.ts
index 0fea673a..42ef22c7 100644
--- a/apps/server/src/data/redis.ts
+++ b/apps/server/src/data/redis.ts
@@ -19,7 +19,8 @@ export const redisConfig = {
};
export const redis = createClient({
- url: REDIS_URL,
+ url: redisConfig.url,
+ database: redisConfig.db,
});
export const initRedis = async () => {
diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.ts
index 9d657c71..761ecc21 100644
--- a/apps/server/src/data/schema.ts
+++ b/apps/server/src/data/schema.ts
@@ -42,11 +42,9 @@ interface DeviceTable {
type: ColumnType<number, number, number>;
version: ColumnType<string, string, string>;
platform: ColumnType<string | null, string | null, string | null>;
- cpu: ColumnType<string | null, string | null, string | null>;
- hostname: ColumnType<string | null, string | null, string | null>;
+ ip: ColumnType<string | null, string | null, string | null>;
created_at: ColumnType<Date, Date, never>;
- last_online_at: ColumnType<Date | null, Date | null, Date>;
- last_active_at: ColumnType<Date | null, Date | null, Date>;
+ synced_at: ColumnType<Date | null, Date | null, Date>;
}
export type SelectDevice = Selectable<DeviceTable>;
diff --git a/apps/server/src/lib/response-builder.ts b/apps/server/src/lib/response-builder.ts
index 1a881d05..99d6b1ad 100644
--- a/apps/server/src/lib/response-builder.ts
+++ b/apps/server/src/lib/response-builder.ts
@@ -26,6 +26,10 @@ export class ResponseBuilder {
ResponseBuilder.error(res, 500, error);
}
+ static tooManyRequests(res: Response, error: ApiErrorOutput): void {
+ ResponseBuilder.error(res, 429, error);
+ }
+
static success<T>(res: Response, data: T): void {
res.status(200).json(data);
}
diff --git a/apps/server/src/middlewares/ip.ts b/apps/server/src/middlewares/ip.ts
new file mode 100644
index 00000000..c917d4b4
--- /dev/null
+++ b/apps/server/src/middlewares/ip.ts
@@ -0,0 +1,16 @@
+import { NextFunction, Request, Response, RequestHandler } from 'express';
+
+export const ipMiddleware: RequestHandler = async (
+ req: Request,
+ res: Response,
+ next: NextFunction
+) => {
+ let ip = req.get('CF-Connecting-IP') || req.get('X-Forwarded-For') || req.ip;
+ ip = Array.isArray(ip) ? ip[0] : ip;
+ if (ip?.includes(',')) {
+ ip = ip.split(',')[0];
+ }
+
+ res.locals.ip = ip;
+ next();
+};
diff --git a/apps/server/src/services/account-service.ts b/apps/server/src/services/account-service.ts
index dbc0dccd..cfe40afd 100644
--- a/apps/server/src/services/account-service.ts
+++ b/apps/server/src/services/account-service.ts
@@ -12,7 +12,10 @@ import { workspaceService } from '@/services/workspace-service';
import { generateToken } from '@/lib/tokens';
class AccountService {
- public async buildLoginOutput(account: SelectAccount): Promise<LoginOutput> {
+ public async buildLoginOutput(
+ account: SelectAccount,
+ ip: string | undefined
+ ): Promise<LoginOutput> {
const users = await database
.selectFrom('users')
.where('account_id', '=', account.id)
@@ -66,6 +69,7 @@ class AccountService {
token_salt: salt,
token_generated_at: new Date(),
type: 1,
+ ip,
created_at: new Date(),
version: '0.1.0',
})
diff --git a/apps/server/src/services/rate-limit-service.ts b/apps/server/src/services/rate-limit-service.ts
new file mode 100644
index 00000000..515020f2
--- /dev/null
+++ b/apps/server/src/services/rate-limit-service.ts
@@ -0,0 +1,34 @@
+import { redis } from '@/data/redis';
+
+interface RateLimitConfig {
+ limit: number;
+ window: number;
+}
+
+class RateLimitService {
+ private defaultConfig: RateLimitConfig = {
+ limit: 10,
+ window: 300, // 5 minutes
+ };
+
+ public async isRateLimited(
+ key: string,
+ config: RateLimitConfig = this.defaultConfig
+ ): Promise<boolean> {
+ const redisKey = this.buildKey(key);
+ const attempts = await redis.incr(redisKey);
+
+ // Set expiry on first attempt
+ if (attempts === 1) {
+ await redis.expire(redisKey, config.window);
+ }
+
+ return attempts > config.limit;
+ }
+
+ private buildKey(key: string): string {
+ return `rate_limit_${key}`;
+ }
+}
+
+export const rateLimitService = new RateLimitService();
diff --git a/packages/core/src/types/api.ts b/packages/core/src/types/api.ts
index 5c6d791b..38432038 100644
--- a/packages/core/src/types/api.ts
+++ b/packages/core/src/types/api.ts
@@ -5,6 +5,7 @@ export type ApiErrorOutput = {
export enum ApiErrorCode {
AccountNotFound = 'account_not_found',
+ DeviceNotFound = 'device_not_found',
AccountMismatch = 'account_mismatch',
AccountPendingActivation = 'account_pending_activation',
EmailOrPasswordIncorrect = 'email_or_password_incorrect',
@@ -37,6 +38,7 @@ export enum ApiErrorCode {
TokenInvalid = 'token_invalid',
RootNotFound = 'root_not_found',
+ TooManyRequests = 'too_many_requests',
Unauthorized = 'unauthorized',
Forbidden = 'forbidden',
NotFound = 'not_found',