mirror of
https://github.com/colanode/colanode.git
synced 2025-12-29 00:25:03 +01:00
Add a prefix for device tokens
This commit is contained in:
@@ -4,6 +4,8 @@ import { database } from '@/data/database';
|
||||
import { uuid } from '@/lib/utils';
|
||||
import { RequestAccount } from '@/types/api';
|
||||
|
||||
const DEVICE_TOKEN_PREFIX = 'cnd_';
|
||||
|
||||
interface GenerateTokenResult {
|
||||
token: string;
|
||||
salt: string;
|
||||
@@ -27,8 +29,8 @@ type VerifyTokenResult =
|
||||
export const generateToken = (deviceId: string): GenerateTokenResult => {
|
||||
const salt = uuid();
|
||||
const secret = uuid() + uuid();
|
||||
const token = deviceId + secret;
|
||||
const hash = sha256(secret + salt);
|
||||
const token = DEVICE_TOKEN_PREFIX + deviceId + secret;
|
||||
|
||||
return {
|
||||
token,
|
||||
@@ -37,9 +39,14 @@ export const generateToken = (deviceId: string): GenerateTokenResult => {
|
||||
};
|
||||
};
|
||||
|
||||
export const parseToken = (token: string): TokenData => {
|
||||
const deviceId = token.slice(0, 28);
|
||||
const secret = token.slice(28);
|
||||
export const parseToken = (token: string): TokenData | null => {
|
||||
if (!token.startsWith(DEVICE_TOKEN_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const tokenWithoutPrefix = token.slice(DEVICE_TOKEN_PREFIX.length);
|
||||
const deviceId = tokenWithoutPrefix.slice(0, 28);
|
||||
const secret = tokenWithoutPrefix.slice(28);
|
||||
return {
|
||||
deviceId,
|
||||
secret,
|
||||
|
||||
@@ -20,6 +20,13 @@ export const authMiddleware: RequestHandler = async (
|
||||
}
|
||||
|
||||
const tokenData = parseToken(token);
|
||||
if (!tokenData) {
|
||||
return ResponseBuilder.unauthorized(res, {
|
||||
code: ApiErrorCode.TokenInvalid,
|
||||
message: 'Token is invalid or expired',
|
||||
});
|
||||
}
|
||||
|
||||
const isRateLimited = await rateLimitService.isDeviceApiRateLimitted(
|
||||
tokenData.deviceId
|
||||
);
|
||||
|
||||
@@ -51,6 +51,11 @@ class SocketService {
|
||||
}
|
||||
|
||||
const tokenData = parseToken(token);
|
||||
if (!tokenData) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
const isRateLimited = await rateLimitService.isDeviceSocketRateLimitted(
|
||||
tokenData.deviceId
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user