jwt-auth.test.js 1.93 KB
/**
 * Unit Tests — middleware/jwt-auth.js
 */
import { describe, it, expect } from 'vitest';

const jwtAuth = require('../../middleware/jwt-auth');

describe('jwt-auth', () => {
  describe('exports', () => {
    it('should export authentication middleware functions', () => {
      expect(typeof jwtAuth.requireAuth).toBe('function');
      expect(typeof jwtAuth.requireAdmin).toBe('function');
      expect(typeof jwtAuth.optionalAuth).toBe('function');
      expect(typeof jwtAuth.extractUser).toBe('function');
    });

    it('should export cookie helpers', () => {
      expect(typeof jwtAuth.signAndSetCookie).toBe('function');
      expect(typeof jwtAuth.clearCookie).toBe('function');
    });

    it('should export token extraction', () => {
      expect(typeof jwtAuth.extractUserFromToken).toBe('function');
    });

    it('should export constants', () => {
      expect(typeof jwtAuth.JWT_SECRET).toBe('string');
      expect(typeof jwtAuth.COOKIE_NAME).toBe('string');
    });
  });

  describe('extractUserFromToken', () => {
    it('should return null for invalid token', () => {
      const user = jwtAuth.extractUserFromToken('invalid-token');
      expect(user).toBeNull();
    });

    it('should return null for empty token', () => {
      expect(jwtAuth.extractUserFromToken('')).toBeNull();
      expect(jwtAuth.extractUserFromToken(null)).toBeNull();
    });
  });

  // bin/lemon.js(agent 用来 task report/dispatch 自我汇报的 CLI)跑在 claude CLI 子进程
  // 里,不跟主进程共享内存,只能靠 process.env 拿到 INTERNAL_TOKEN——commit b7b5096 之后
  // 漏了这条路径,导致所有 agent 的 task report/dispatch 全部 401。
  describe('INTERNAL_TOKEN 透传给子进程(bin/lemon.js 依赖这个)', () => {
    it('require 本模块时应把 INTERNAL_TOKEN 写进 process.env.LEMON_INTERNAL_TOKEN', () => {
      expect(process.env.LEMON_INTERNAL_TOKEN).toBe(jwtAuth.INTERNAL_TOKEN);
    });
  });
});