All files / src/__tests__ auth.ts

98.25% Statements 112/114
50% Branches 2/4
97.37% Functions 37/38
99.04% Lines 103/104
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 2611x                 1x 1x 1x 1x 1x 1x 1x 1x   1x     2x 2x   1x 4x 4x 4x           4x     4x   1x 4x       1x 4x           2x   2x   1x     1x   1x     2x 2x   4x 4x   4x         4x   1x 2x   1x 1x 1x   1x 4x   1x   1x           1x       1x               1x     1x             1x           1x 1x           1x     1x 1x           1x 1x         1x 1x             1x 1x 1x       1x           1x 1x   1x 1x 1x     1x 1x 1x 1x   1x 1x     1x 1x 1x         1x 1x 1x 1x   1x 1x     1x 1x     1x 1x       1x 1x             1x 1x     1x 1x     1x 1x         1x 1x       1x               1x 1x     1x 1x     1x 1x         1x 1x        
import jwt from 'jsonwebtoken';
import {
  AuthPayload,
  AuthScope,
  AuthServer,
  IAccessToken,
  IRefreshToken
} from '../';
 
describe('Auth Server', () => {
  const ONE_MINUTE = 1000 * 60;
  const ONE_DAY = ONE_MINUTE * 60 * 24;
  const ONE_MONTH = ONE_DAY * 30;
  const ACCESS_TOKEN_COOKIE = 'abc';
  const ACCESS_TOKEN_SECRET = 'password';
  const REFRESH_TOKEN_COOKIE = 'aei';
  const refreshTokens = new Map();
 
  class AccessToken implements IAccessToken {
    public cookie: string;
 
    constructor(public Auth: AuthServer) {
      this.cookie = ACCESS_TOKEN_COOKIE;
    }
    public buildPayload({
      id,
      companyId,
      admin
    }: {
      id: string;
      companyId: string;
      admin: boolean;
    }) {
      const scope = admin
        ? this.Auth.scope.create(['admin:read', 'admin:write'])
        : '';
      return { id, companyId, scope };
    }
    public create(payload: { uId: string; cId: string; scope: string }) {
      return jwt.sign(payload, ACCESS_TOKEN_SECRET, {
        expiresIn: '20m'
      });
    }
    public verify(accessToken: string) {
      const payload = jwt.verify(accessToken, ACCESS_TOKEN_SECRET, {
        algorithms: ['HS256'],
        clockTolerance: 80 // seconds to tolerate
      });
 
      // This should never happen cause our payload is a valid JSON
      Iif (typeof payload === 'string') return {};
 
      return payload;
    }
    public getExpDate() {
      return new Date(Date.now() + ONE_MINUTE * 20);
    }
  }
 
  class RefreshToken implements IRefreshToken {
    public cookie: string;
 
    constructor(public Auth: AuthServer) {
      this.cookie = REFRESH_TOKEN_COOKIE;
    }
    public async create({ id: userId }: { id: string }) {
      const id = Date.now().toString();
 
      refreshTokens.set(id, {
        userId,
        expireAt: this.getExpDate()
      });
 
      return id;
    }
    public remove(refreshToken: string) {
      return refreshTokens.delete(refreshToken);
    }
    public async getPayload(refreshToken: string, reset: () => any) {
      reset();
      return refreshTokens.get(refreshToken);
    }
    public getExpDate() {
      return new Date(Date.now() + ONE_MONTH);
    }
  }
 
  const authPayload = new AuthPayload({
    uId: 'id',
    cId: 'companyId',
    scope: 'scope'
  });
 
  const authScope = new AuthScope({
    admin: 'a'
  });
 
  const authServer = new AuthServer({
    AccessToken,
    RefreshToken,
    payload: authPayload,
    scope: authScope
  });
 
  const expiredToken =
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1SWQiOiJ1c2VyXzEyMyIsImNJZCI6ImNvbXBhbnlfMTIzIiwic2NvcGUiOiJhOnI6dyIsImlhdCI6MTUxODE0MTIzNCwiZXhwIjoxNTE4MTQyNDM0fQ.3ZRmx08htMX5KLsv8VhBVD8vjxHzWOiDDli7JXFf83Q';
 
  // Payload to create a token
  const userPayload = {
    id: 'user_123',
    companyId: 'company_123',
    admin: true
  };
 
  // Payload got from a token
  const tokenPayload = {
    id: userPayload.id,
    companyId: userPayload.companyId,
    scope: 'a:r:w'
  };
 
  it('should set a default scope if no scope is used', () => {
    const auth = new AuthServer({
      AccessToken,
      RefreshToken,
      payload: authPayload
    });
 
    expect(auth.scope).toBeInstanceOf(AuthScope);
  });
 
  it('creates an accessToken', () => {
    expect(authServer.createAccessToken(userPayload)).toEqual({
      accessToken: expect.any(String),
      payload: tokenPayload
    });
  });
 
  it('creates a refreshToken', async () => {
    expect(typeof await authServer.createRefreshToken(userPayload)).toBe(
      'string'
    );
  });
 
  it('creates both tokens', async () => {
    expect(await authServer.createTokens(userPayload)).toEqual({
      refreshToken: expect.any(String),
      accessToken: expect.any(String),
      payload: tokenPayload
    });
  });
 
  it('gets the payload for an accessToken', async () => {
    const refreshToken = await authServer.createRefreshToken(userPayload);
    const reset = () => {
      // do nothing
    };
 
    expect(await authServer.getPayload(refreshToken, reset)).toEqual({
      userId: userPayload.id,
      expireAt: refreshTokens.get(refreshToken).expireAt
    });
  });
 
  it('Removes a refreshToken', async () => {
    const refreshToken = await authServer.createRefreshToken(userPayload);
 
    expect(authServer.removeRefreshRoken(refreshToken)).toBe(true);
    expect(authServer.removeRefreshRoken(refreshToken)).toBe(false);
    expect(authServer.removeRefreshRoken('')).toBe(false);
  });
 
  describe('Verifies an accessToken', () => {
    it('returns the payload', () => {
      const at = authServer.createAccessToken(userPayload);
      const decodedPayload = authServer.verify(at.accessToken);
 
      expect(decodedPayload).toEqual(at.payload);
      expect(decodedPayload).toEqual(tokenPayload);
    });
 
    it('throws if expired', () => {
      expect(() => {
        authServer.verify(expiredToken);
      }).toThrow();
    });
  });
 
  describe('decodes an accessToken', () => {
    it('Returns the payload', () => {
      const at = authServer.createAccessToken(userPayload);
      const decodedPayload = authServer.decode(at.accessToken);
 
      expect(decodedPayload).toEqual(at.payload);
      expect(decodedPayload).toEqual(tokenPayload);
    });
 
    it('Returns null with empty accessToken', () => {
      expect(authServer.decode('')).toBe(null);
    });
 
    it('Returns null if expired', () => {
      expect(authServer.decode(expiredToken)).toBe(null);
    });
  });
 
  describe('Gets an accessToken from a request', () => {
    const headers = {
      authorization: 'Bearer ' + expiredToken
    };
    const cookies = {
      [ACCESS_TOKEN_COOKIE]: 'x' + expiredToken
    };
 
    it('uses the headers to get the token', () => {
      expect(authServer.getAccessToken({ headers })).toBe(expiredToken);
    });
 
    it('uses the cookies to get the token', () => {
      expect(authServer.getAccessToken({ cookies })).toBe('x' + expiredToken);
    });
 
    it('always prioritizes the headers', () => {
      expect(
        authServer.getAccessToken({ headers, cookies, signedCookies: cookies })
      ).toBe(expiredToken);
    });
 
    it('should be null with empty object', () => {
      expect(authServer.getAccessToken({})).toBe(null);
    });
  });
 
  describe('Gets a refreshToken from a request', () => {
    const signedCookies = {
      [REFRESH_TOKEN_COOKIE]: 'xxx'
    };
    const cookies = {
      [REFRESH_TOKEN_COOKIE]: 'yyy'
    };
 
    it('uses the signed cookies to get the token', () => {
      expect(authServer.getRefreshToken({ signedCookies })).toBe('xxx');
    });
 
    it('uses the cookies to get the token', () => {
      expect(authServer.getRefreshToken({ cookies })).toBe('yyy');
    });
 
    it('always prioritizes the signedCookies', () => {
      expect(authServer.getRefreshToken({ signedCookies, cookies })).toBe(
        'xxx'
      );
    });
 
    it('should be null with empty object', () => {
      expect(authServer.getRefreshToken({})).toBe(null);
    });
  });
});