Files
DataStack/core/auth/jwt.ts
T

75 lines
1.9 KiB
TypeScript
Raw Normal View History

2026-10-23 19:56:38 -07:00
import jwt from "jsonwebtoken";
2026-10-23 11:43:49 -05:00
export interface ClientTokenPayload {
clientId: string;
name?: string;
rateLimit?: number;
iat?: number;
exp?: number;
}
2026-10-23 19:56:38 -07:00
const DEFAULT_SECRET = process.env.DATASTACK_JWT_SECRET || "";
2026-10-23 11:43:49 -05:00
export class AuthService {
private static secret: string = DEFAULT_SECRET;
public static setSecret(newSecret: string) {
if (newSecret && newSecret.trim().length > 0) {
this.secret = newSecret.trim();
}
}
public static getSecret(): string {
return this.secret;
}
/**
* Generates a signed JWT for client SDK authentication.
*/
2026-10-23 19:56:38 -07:00
public static generateClientToken(
payload: { clientId: string; name?: string; rateLimit?: number },
expiresIn = "30d",
): string {
if (!this.secret) {
throw new Error(
"DATASTACK_JWT_SECRET must be configured before generating client tokens.",
);
}
2026-10-23 11:43:49 -05:00
return jwt.sign(
{
clientId: payload.clientId,
name: payload.name || payload.clientId,
rateLimit: payload.rateLimit || 100,
},
this.secret,
2026-10-23 19:56:38 -07:00
{ expiresIn: expiresIn as jwt.SignOptions["expiresIn"] },
2026-10-23 11:43:49 -05:00
);
}
/**
* Verifies and decodes incoming token from Socket.IO handshake.
*/
2026-10-23 19:56:38 -07:00
public static verifyClientToken(token: string): {
valid: boolean;
payload?: ClientTokenPayload;
error?: string;
} {
if (!this.secret) {
return { valid: false, error: "DATASTACK_JWT_SECRET is not configured." };
}
2026-10-23 11:43:49 -05:00
try {
2026-10-23 19:56:38 -07:00
const cleanToken = token.startsWith("Bearer ")
? token.slice(7).trim()
: token.trim();
2026-10-23 11:43:49 -05:00
const decoded = jwt.verify(cleanToken, this.secret) as ClientTokenPayload;
return { valid: true, payload: decoded };
} catch (err: unknown) {
2026-10-23 19:56:38 -07:00
const message = err instanceof Error ? err.message : "Invalid token";
2026-10-23 11:43:49 -05:00
return { valid: false, error: message };
}
}
}
export default AuthService;