File size: 10,822 Bytes
1f5ea39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import { describe, it, expect, vi } from 'vitest';

vi.mock('../../../src/db/database', () => ({
  db: { prepare: () => ({ get: vi.fn(), all: vi.fn(), run: vi.fn() }) },
  canAccessTrip: vi.fn(),
}));
vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret', ENCRYPTION_KEY: '0'.repeat(64) }));
vi.mock('../../../src/services/mfaCrypto', () => ({ encryptMfaSecret: vi.fn(), decryptMfaSecret: vi.fn() }));
vi.mock('../../../src/services/apiKeyCrypto', () => ({
  decrypt_api_key: vi.fn((v) => v),
  maybe_encrypt_api_key: vi.fn((v) => v),
  encrypt_api_key: vi.fn((v) => v),
}));
vi.mock('../../../src/services/permissions', () => ({ getAllPermissions: vi.fn(() => ({})), checkPermission: vi.fn() }));
vi.mock('../../../src/services/ephemeralTokens', () => ({ createEphemeralToken: vi.fn() }));
vi.mock('../../../src/mcp', () => ({ revokeUserSessions: vi.fn() }));
vi.mock('../../../src/scheduler', () => ({ startTripReminders: vi.fn(), buildCronExpression: vi.fn() }));

import {
  utcSuffix,
  stripUserForClient,
  maskKey,
  avatarUrl,
  normalizeBackupCode,
  hashBackupCode,
  generateBackupCodes,
  parseBackupCodeHashes,
} from '../../../src/services/authService';
import type { User } from '../../../src/types';

// ── utcSuffix ────────────────────────────────────────────────────────────────

describe('utcSuffix', () => {
  it('returns null for null', () => {
    expect(utcSuffix(null)).toBeNull();
  });

  it('returns null for undefined', () => {
    expect(utcSuffix(undefined)).toBeNull();
  });

  it('returns null for empty string', () => {
    expect(utcSuffix('')).toBeNull();
  });

  it('returns timestamp unchanged when already ending with Z', () => {
    expect(utcSuffix('2024-01-01T12:00:00Z')).toBe('2024-01-01T12:00:00Z');
  });

  it('replaces space with T and appends Z for SQLite-style datetime', () => {
    expect(utcSuffix('2024-01-01 12:00:00')).toBe('2024-01-01T12:00:00Z');
  });

  it('appends Z when T is present but Z is missing', () => {
    expect(utcSuffix('2024-06-15T08:30:00')).toBe('2024-06-15T08:30:00Z');
  });
});

// ── stripUserForClient ───────────────────────────────────────────────────────

function makeUser(overrides: Partial<User> = {}): User {
  return {
    id: 1,
    username: 'alice',
    email: 'alice@example.com',
    role: 'user',
    password_hash: 'supersecret',
    maps_api_key: 'maps-key',
    openweather_api_key: 'weather-key',
    unsplash_api_key: 'unsplash-key',
    mfa_secret: 'totpsecret',
    mfa_backup_codes: '["hash1","hash2"]',
    mfa_enabled: 0,
    must_change_password: 0,
    avatar: null,
    created_at: '2024-01-01 00:00:00',
    updated_at: '2024-06-01 00:00:00',
    last_login: null,
    ...overrides,
  } as unknown as User;
}

describe('stripUserForClient', () => {
  it('SEC-008: omits password_hash', () => {
    const result = stripUserForClient(makeUser());
    expect(result).not.toHaveProperty('password_hash');
  });

  it('SEC-008: omits maps_api_key', () => {
    const result = stripUserForClient(makeUser());
    expect(result).not.toHaveProperty('maps_api_key');
  });

  it('SEC-008: omits openweather_api_key', () => {
    const result = stripUserForClient(makeUser());
    expect(result).not.toHaveProperty('openweather_api_key');
  });

  it('SEC-008: omits unsplash_api_key', () => {
    const result = stripUserForClient(makeUser());
    expect(result).not.toHaveProperty('unsplash_api_key');
  });

  it('SEC-008: omits mfa_secret', () => {
    const result = stripUserForClient(makeUser());
    expect(result).not.toHaveProperty('mfa_secret');
  });

  it('SEC-008: omits mfa_backup_codes', () => {
    const result = stripUserForClient(makeUser());
    expect(result).not.toHaveProperty('mfa_backup_codes');
  });

  it('preserves non-sensitive fields', () => {
    const result = stripUserForClient(makeUser({ username: 'alice', email: 'alice@example.com', role: 'user' }));
    expect(result.id).toBe(1);
    expect(result.username).toBe('alice');
    expect(result.email).toBe('alice@example.com');
    expect(result.role).toBe('user');
  });

  it('normalizes mfa_enabled integer 1 to true', () => {
    const result = stripUserForClient(makeUser({ mfa_enabled: 1 } as any));
    expect(result.mfa_enabled).toBe(true);
  });

  it('normalizes mfa_enabled integer 0 to false', () => {
    const result = stripUserForClient(makeUser({ mfa_enabled: 0 } as any));
    expect(result.mfa_enabled).toBe(false);
  });

  it('normalizes mfa_enabled boolean true to true', () => {
    const result = stripUserForClient(makeUser({ mfa_enabled: true } as any));
    expect(result.mfa_enabled).toBe(true);
  });

  it('normalizes must_change_password integer 1 to true', () => {
    const result = stripUserForClient(makeUser({ must_change_password: 1 } as any));
    expect(result.must_change_password).toBe(true);
  });

  it('normalizes must_change_password integer 0 to false', () => {
    const result = stripUserForClient(makeUser({ must_change_password: 0 } as any));
    expect(result.must_change_password).toBe(false);
  });

  it('converts created_at through utcSuffix', () => {
    const result = stripUserForClient(makeUser({ created_at: '2024-01-01 00:00:00' }));
    expect(result.created_at).toBe('2024-01-01T00:00:00Z');
  });

  it('converts updated_at through utcSuffix', () => {
    const result = stripUserForClient(makeUser({ updated_at: '2024-06-01 12:00:00' }));
    expect(result.updated_at).toBe('2024-06-01T12:00:00Z');
  });

  it('passes null last_login through as null', () => {
    const result = stripUserForClient(makeUser({ last_login: null }));
    expect(result.last_login).toBeNull();
  });
});

// ── maskKey ──────────────────────────────────────────────────────────────────

describe('maskKey', () => {
  it('returns null for null', () => {
    expect(maskKey(null)).toBeNull();
  });

  it('returns null for undefined', () => {
    expect(maskKey(undefined)).toBeNull();
  });

  it('returns null for empty string', () => {
    expect(maskKey('')).toBeNull();
  });

  it('returns -------- for keys with 8 or fewer characters', () => {
    expect(maskKey('abcd1234')).toBe('--------');
    expect(maskKey('short')).toBe('--------');
    expect(maskKey('a')).toBe('--------');
  });

  it('returns ---- + last 4 chars for keys longer than 8 characters', () => {
    expect(maskKey('abcdefghijkl')).toBe('----ijkl');
    expect(maskKey('sk-test-12345678')).toBe('----5678');
  });
});

// ── avatarUrl ────────────────────────────────────────────────────────────────

describe('avatarUrl', () => {
  it('returns /uploads/avatars/<filename> when avatar is set', () => {
    expect(avatarUrl({ avatar: 'photo.jpg' })).toBe('/uploads/avatars/photo.jpg');
  });

  it('returns null when avatar is null', () => {
    expect(avatarUrl({ avatar: null })).toBeNull();
  });

  it('returns null when avatar is undefined', () => {
    expect(avatarUrl({})).toBeNull();
  });
});

// ── normalizeBackupCode ──────────────────────────────────────────────────────

describe('normalizeBackupCode', () => {
  it('uppercases the input', () => {
    expect(normalizeBackupCode('abcd1234')).toBe('ABCD1234');
  });

  it('strips non-alphanumeric characters', () => {
    expect(normalizeBackupCode('AB-CD 12!34')).toBe('ABCD1234');
  });

  it('handles code with dashes (normal backup code format)', () => {
    expect(normalizeBackupCode('A1B2-C3D4')).toBe('A1B2C3D4');
  });

  it('returns empty string for empty input', () => {
    expect(normalizeBackupCode('')).toBe('');
  });
});

// ── hashBackupCode ───────────────────────────────────────────────────────────

describe('hashBackupCode', () => {
  it('returns a 64-character hex string', () => {
    const hash = hashBackupCode('A1B2-C3D4');
    expect(hash).toMatch(/^[0-9a-f]{64}$/);
  });

  it('is deterministic: same input always produces same output', () => {
    expect(hashBackupCode('A1B2-C3D4')).toBe(hashBackupCode('A1B2-C3D4'));
  });

  it('normalizes before hashing: dashed and plain form produce the same hash', () => {
    expect(hashBackupCode('A1B2-C3D4')).toBe(hashBackupCode('a1b2c3d4'));
  });
});

// ── generateBackupCodes ──────────────────────────────────────────────────────

describe('generateBackupCodes', () => {
  it('returns 10 codes by default', () => {
    const codes = generateBackupCodes();
    expect(codes).toHaveLength(10);
  });

  it('respects a custom count', () => {
    expect(generateBackupCodes(5)).toHaveLength(5);
    expect(generateBackupCodes(20)).toHaveLength(20);
  });

  it('each code matches the XXXX-XXXX uppercase hex pattern', () => {
    const codes = generateBackupCodes();
    for (const code of codes) {
      expect(code).toMatch(/^[0-9A-F]{4}-[0-9A-F]{4}$/);
    }
  });

  it('generates no duplicate codes', () => {
    const codes = generateBackupCodes(10);
    expect(new Set(codes).size).toBe(10);
  });
});

// ── parseBackupCodeHashes ────────────────────────────────────────────────────

describe('parseBackupCodeHashes', () => {
  it('returns [] for null', () => {
    expect(parseBackupCodeHashes(null)).toEqual([]);
  });

  it('returns [] for undefined', () => {
    expect(parseBackupCodeHashes(undefined)).toEqual([]);
  });

  it('returns [] for empty string', () => {
    expect(parseBackupCodeHashes('')).toEqual([]);
  });

  it('returns [] for invalid JSON', () => {
    expect(parseBackupCodeHashes('not-json')).toEqual([]);
  });

  it('returns [] for JSON that is not an array', () => {
    expect(parseBackupCodeHashes('{"key":"value"}')).toEqual([]);
  });

  it('filters out non-string entries', () => {
    expect(parseBackupCodeHashes('[1, "abc", null, true]')).toEqual(['abc']);
  });

  it('returns all strings from a valid JSON string array', () => {
    expect(parseBackupCodeHashes('["hash1","hash2","hash3"]')).toEqual(['hash1', 'hash2', 'hash3']);
  });
});