import { describe, expect, it } from 'vitest'; import { getJwtExpiry, isAccessTokenValid } from '../../src/utils/jwt.js'; /** * Build a syntactically valid JWT (header.payload.signature) with the given * payload. The signature is irrelevant; these helpers never verify it. */ function makeJwt(payload: Record): string { const header = Buffer.from(JSON.stringify({ alg: 'none', typ: 'JWT' })).toString('base64url'); const body = Buffer.from(JSON.stringify(payload)).toString('base64url'); return `${header}.${body}.sig`; } const nowSeconds = () => Math.floor(Date.now() / 1000); describe('getJwtExpiry', () => { it('returns the exp claim in seconds', () => { const exp = nowSeconds() + 3600; expect(getJwtExpiry(makeJwt({ exp }))).toBe(exp); }); it('returns null when the token is not three parts', () => { expect(getJwtExpiry('not-a-jwt')).toBeNull(); expect(getJwtExpiry('only.two')).toBeNull(); }); it('returns null when the payload is not valid JSON', () => { const header = Buffer.from('{}').toString('base64url'); expect(getJwtExpiry(`${header}.notjson.sig`)).toBeNull(); }); it('returns null when there is no numeric exp claim', () => { expect(getJwtExpiry(makeJwt({ sub: 'did:plc:test' }))).toBeNull(); expect(getJwtExpiry(makeJwt({ exp: 'soon' }))).toBeNull(); }); }); describe('isAccessTokenValid', () => { it('returns true for a token expiring comfortably in the future', () => { expect(isAccessTokenValid(makeJwt({ exp: nowSeconds() + 3600 }))).toBe(true); }); it('returns false for an already-expired token', () => { expect(isAccessTokenValid(makeJwt({ exp: nowSeconds() - 10 }))).toBe(false); }); it('returns false for a token expiring within the safety margin', () => { expect(isAccessTokenValid(makeJwt({ exp: nowSeconds() + 30 }), 60)).toBe(false); }); it('returns false for a malformed token', () => { expect(isAccessTokenValid('garbage')).toBe(false); }); });