Files
FitOS/api/test/unit/jwt.test.ts
2026-09-04 19:06:19 +02:00

66 lines
2.2 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import jwt from 'jsonwebtoken';
import {
REFRESH_COOKIE,
signAccessToken,
signRefreshToken,
verifyAccessToken,
verifyRefreshToken,
} from '../../src/lib/jwt.js';
import { config } from '../../src/config.js';
describe('jwt', () => {
it('signs and verifies an access token with payload', () => {
const token = signAccessToken('user-1', 3);
const payload = verifyAccessToken(token);
expect(payload).toMatchObject({ sub: 'user-1', tv: 3, type: 'access' });
expect(payload.exp).toBeGreaterThan(payload.iat);
});
it('signs and verifies a refresh token with payload', () => {
const token = signRefreshToken('user-2', 0);
const payload = verifyRefreshToken(token);
expect(payload).toMatchObject({ sub: 'user-2', tv: 0, type: 'refresh' });
});
it('rejects a refresh-typed token verified as access token', () => {
// signed with the access secret so the signature check passes and the type check fires
const token = jwt.sign({ sub: 'user-1', tv: 0, type: 'refresh' }, config.jwt.accessSecret, {
expiresIn: 60,
});
expect(() => verifyAccessToken(token)).toThrow('invalid token type');
});
it('rejects an access-typed token verified as refresh token', () => {
const token = jwt.sign({ sub: 'user-1', tv: 0, type: 'access' }, config.jwt.refreshSecret, {
expiresIn: 60,
});
expect(() => verifyRefreshToken(token)).toThrow('invalid token type');
});
it('rejects a refresh token (different secret) on the access endpoint', () => {
const token = signRefreshToken('user-1', 0);
expect(() => verifyAccessToken(token)).toThrow();
});
it('rejects a token signed with a different secret', () => {
const token = jwt.sign(
{ sub: 'user-1', tv: 0, type: 'access' },
'other-secret',
{ expiresIn: 60 },
);
expect(() => verifyAccessToken(token)).toThrow();
});
it('rejects an expired access token', () => {
const token = jwt.sign({ sub: 'user-1', tv: 0, type: 'access' }, config.jwt.accessSecret, {
expiresIn: -10,
});
expect(() => verifyAccessToken(token)).toThrow(/expired/);
});
it('exposes the refresh cookie name', () => {
expect(REFRESH_COOKIE).toBe('fitos_refresh');
});
});