@claude-flow/security 3.0.0-alpha.1 → 3.0.0-alpha.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +292 -234
  2. package/__tests__/acceptance/security-compliance.test.ts +674 -674
  3. package/__tests__/authorization-propagator.test.ts +155 -0
  4. package/__tests__/credential-generator.test.ts +310 -310
  5. package/__tests__/fixtures/configurations.ts +425 -419
  6. package/__tests__/fixtures/index.ts +21 -21
  7. package/__tests__/helpers/create-mock.ts +469 -469
  8. package/__tests__/helpers/index.ts +32 -32
  9. package/__tests__/input-validator.test.ts +382 -381
  10. package/__tests__/integration/security-flow.test.ts +606 -606
  11. package/__tests__/keychain-adapter.test.ts +60 -0
  12. package/__tests__/oauth-browser.test.ts +13 -0
  13. package/__tests__/oauth-export-surface.test.ts +21 -0
  14. package/__tests__/oauth-pkce.test.ts +37 -0
  15. package/__tests__/password-hasher.test.ts +239 -239
  16. package/__tests__/path-validator.test.ts +302 -302
  17. package/__tests__/plugin-integrity-verifier.test.ts +199 -0
  18. package/__tests__/safe-executor.test.ts +292 -292
  19. package/__tests__/token-generator.test.ts +371 -371
  20. package/__tests__/tool-output-guardrail.test.ts +256 -0
  21. package/__tests__/unit/credential-generator.test.ts +182 -182
  22. package/__tests__/unit/password-hasher.test.ts +359 -359
  23. package/__tests__/unit/path-validator.test.ts +509 -509
  24. package/__tests__/unit/safe-executor.test.ts +667 -667
  25. package/__tests__/unit/token-generator.test.ts +310 -310
  26. package/dist/CVE-REMEDIATION.d.ts +17 -6
  27. package/dist/CVE-REMEDIATION.d.ts.map +1 -1
  28. package/dist/CVE-REMEDIATION.js +328 -12
  29. package/dist/CVE-REMEDIATION.js.map +1 -1
  30. package/dist/authorization/propagator.d.ts +148 -0
  31. package/dist/authorization/propagator.d.ts.map +1 -0
  32. package/dist/authorization/propagator.js +182 -0
  33. package/dist/authorization/propagator.js.map +1 -0
  34. package/dist/credential-generator.js +9 -9
  35. package/dist/domain/services/security-domain-service.js +1 -1
  36. package/dist/domain/services/security-domain-service.js.map +1 -1
  37. package/dist/index.d.ts +9 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +21 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/keychain-adapter.d.ts +48 -0
  42. package/dist/keychain-adapter.d.ts.map +1 -0
  43. package/dist/keychain-adapter.js +0 -0
  44. package/dist/keychain-adapter.js.map +1 -0
  45. package/dist/oauth/browser.d.ts +31 -0
  46. package/dist/oauth/browser.d.ts.map +1 -0
  47. package/dist/oauth/browser.js +55 -0
  48. package/dist/oauth/browser.js.map +1 -0
  49. package/dist/oauth/callback-server.d.ts +37 -0
  50. package/dist/oauth/callback-server.d.ts.map +1 -0
  51. package/dist/oauth/callback-server.js +86 -0
  52. package/dist/oauth/callback-server.js.map +1 -0
  53. package/dist/oauth/client.d.ts +57 -0
  54. package/dist/oauth/client.d.ts.map +1 -0
  55. package/dist/oauth/client.js +120 -0
  56. package/dist/oauth/client.js.map +1 -0
  57. package/dist/oauth/pkce.d.ts +25 -0
  58. package/dist/oauth/pkce.d.ts.map +1 -0
  59. package/dist/oauth/pkce.js +36 -0
  60. package/dist/oauth/pkce.js.map +1 -0
  61. package/dist/password-hasher.d.ts.map +1 -1
  62. package/dist/password-hasher.js +8 -1
  63. package/dist/password-hasher.js.map +1 -1
  64. package/dist/plugins/integrity-verifier.d.ts +125 -0
  65. package/dist/plugins/integrity-verifier.d.ts.map +1 -0
  66. package/dist/plugins/integrity-verifier.js +186 -0
  67. package/dist/plugins/integrity-verifier.js.map +1 -0
  68. package/dist/safe-executor.d.ts +7 -0
  69. package/dist/safe-executor.d.ts.map +1 -1
  70. package/dist/safe-executor.js +21 -1
  71. package/dist/safe-executor.js.map +1 -1
  72. package/dist/tool-output-guardrail.d.ts +126 -0
  73. package/dist/tool-output-guardrail.d.ts.map +1 -0
  74. package/dist/tool-output-guardrail.js +257 -0
  75. package/dist/tool-output-guardrail.js.map +1 -0
  76. package/node_modules-incomplete-release-test/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  77. package/package.json +33 -28
  78. package/scripts/verify-oauth-exports.mjs +29 -0
  79. package/src/CVE-REMEDIATION.ts +591 -251
  80. package/src/application/index.ts +10 -10
  81. package/src/application/services/security-application-service.ts +193 -193
  82. package/src/authorization/propagator.ts +279 -0
  83. package/src/credential-generator.ts +368 -368
  84. package/src/domain/entities/security-context.ts +173 -173
  85. package/src/domain/index.ts +17 -17
  86. package/src/domain/services/security-domain-service.ts +296 -296
  87. package/src/index.ts +340 -271
  88. package/src/input-validator.ts +466 -466
  89. package/src/keychain-adapter.ts +0 -0
  90. package/src/oauth/browser.ts +58 -0
  91. package/src/oauth/callback-server.ts +97 -0
  92. package/src/oauth/client.ts +153 -0
  93. package/src/oauth/pkce.ts +45 -0
  94. package/src/password-hasher.ts +277 -270
  95. package/src/path-validator.ts +525 -525
  96. package/src/plugins/integrity-verifier.ts +265 -0
  97. package/src/safe-executor.ts +546 -525
  98. package/src/token-generator.ts +463 -463
  99. package/src/tool-output-guardrail.ts +360 -0
  100. package/tmp.json +0 -0
  101. package/tsconfig.json +9 -9
  102. package/tsconfig.tsbuildinfo +1 -1
  103. package/vitest.config.ts +20 -0
  104. package/.agentic-flow/intelligence.json +0 -16
  105. package/__tests__/coverage/base.css +0 -224
  106. package/__tests__/coverage/block-navigation.js +0 -87
  107. package/__tests__/coverage/coverage-final.json +0 -11
  108. package/__tests__/coverage/favicon.png +0 -0
  109. package/__tests__/coverage/index.html +0 -161
  110. package/__tests__/coverage/lcov-report/base.css +0 -224
  111. package/__tests__/coverage/lcov-report/block-navigation.js +0 -87
  112. package/__tests__/coverage/lcov-report/favicon.png +0 -0
  113. package/__tests__/coverage/lcov-report/index.html +0 -161
  114. package/__tests__/coverage/lcov-report/prettify.css +0 -1
  115. package/__tests__/coverage/lcov-report/prettify.js +0 -2
  116. package/__tests__/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  117. package/__tests__/coverage/lcov-report/sorter.js +0 -210
  118. package/__tests__/coverage/lcov-report/src/CVE-REMEDIATION.ts.html +0 -838
  119. package/__tests__/coverage/lcov-report/src/application/services/index.html +0 -116
  120. package/__tests__/coverage/lcov-report/src/application/services/security-application-service.ts.html +0 -664
  121. package/__tests__/coverage/lcov-report/src/credential-generator.ts.html +0 -1189
  122. package/__tests__/coverage/lcov-report/src/domain/entities/index.html +0 -116
  123. package/__tests__/coverage/lcov-report/src/domain/entities/security-context.ts.html +0 -604
  124. package/__tests__/coverage/lcov-report/src/domain/services/index.html +0 -116
  125. package/__tests__/coverage/lcov-report/src/domain/services/security-domain-service.ts.html +0 -973
  126. package/__tests__/coverage/lcov-report/src/index.html +0 -206
  127. package/__tests__/coverage/lcov-report/src/input-validator.ts.html +0 -1483
  128. package/__tests__/coverage/lcov-report/src/password-hasher.ts.html +0 -895
  129. package/__tests__/coverage/lcov-report/src/path-validator.ts.html +0 -1660
  130. package/__tests__/coverage/lcov-report/src/safe-executor.ts.html +0 -1660
  131. package/__tests__/coverage/lcov-report/src/token-generator.ts.html +0 -1474
  132. package/__tests__/coverage/lcov.info +0 -3650
  133. package/__tests__/coverage/prettify.css +0 -1
  134. package/__tests__/coverage/prettify.js +0 -2
  135. package/__tests__/coverage/sort-arrow-sprite.png +0 -0
  136. package/__tests__/coverage/sorter.js +0 -210
  137. package/__tests__/coverage/src/CVE-REMEDIATION.ts.html +0 -838
  138. package/__tests__/coverage/src/application/services/index.html +0 -116
  139. package/__tests__/coverage/src/application/services/security-application-service.ts.html +0 -664
  140. package/__tests__/coverage/src/credential-generator.ts.html +0 -1189
  141. package/__tests__/coverage/src/domain/entities/index.html +0 -116
  142. package/__tests__/coverage/src/domain/entities/security-context.ts.html +0 -604
  143. package/__tests__/coverage/src/domain/services/index.html +0 -116
  144. package/__tests__/coverage/src/domain/services/security-domain-service.ts.html +0 -973
  145. package/__tests__/coverage/src/index.html +0 -206
  146. package/__tests__/coverage/src/input-validator.ts.html +0 -1483
  147. package/__tests__/coverage/src/password-hasher.ts.html +0 -895
  148. package/__tests__/coverage/src/path-validator.ts.html +0 -1660
  149. package/__tests__/coverage/src/safe-executor.ts.html +0 -1660
  150. package/__tests__/coverage/src/token-generator.ts.html +0 -1474
@@ -1,371 +1,371 @@
1
- /**
2
- * Token Generator Tests
3
- *
4
- * Tests verify:
5
- * - Secure token generation
6
- * - Token expiration
7
- * - Signed token verification
8
- * - Timing-safe comparison
9
- */
10
-
11
- import { describe, it, expect, beforeEach } from 'vitest';
12
- import {
13
- TokenGenerator,
14
- TokenGeneratorError,
15
- createTokenGenerator,
16
- getDefaultGenerator,
17
- quickGenerate,
18
- } from '../../security/token-generator.js';
19
-
20
- describe('TokenGenerator', () => {
21
- let generator: TokenGenerator;
22
-
23
- beforeEach(() => {
24
- generator = new TokenGenerator({
25
- hmacSecret: 'test-secret-key-for-hmac-operations',
26
- defaultExpiration: 3600,
27
- });
28
- });
29
-
30
- describe('Configuration', () => {
31
- it('should use default configuration', () => {
32
- expect(() => new TokenGenerator()).not.toThrow();
33
- });
34
-
35
- it('should reject token length below 16 bytes', () => {
36
- expect(() => new TokenGenerator({
37
- defaultLength: 8,
38
- })).toThrow(TokenGeneratorError);
39
- });
40
-
41
- it('should accept custom encoding', () => {
42
- const hexGenerator = new TokenGenerator({ encoding: 'hex' });
43
- const token = hexGenerator.generate(16);
44
- expect(token).toMatch(/^[0-9a-f]+$/);
45
- });
46
- });
47
-
48
- describe('Token Generation', () => {
49
- it('should generate token of specified length', () => {
50
- const token = generator.generate(32);
51
- // Base64url encoding: 32 bytes = ~43 chars
52
- expect(token.length).toBeGreaterThan(40);
53
- });
54
-
55
- it('should generate unique tokens', () => {
56
- const tokens = new Set<string>();
57
- for (let i = 0; i < 100; i++) {
58
- tokens.add(generator.generate());
59
- }
60
- expect(tokens.size).toBe(100);
61
- });
62
-
63
- it('should generate URL-safe tokens by default', () => {
64
- const token = generator.generate();
65
- // Base64url should not contain +, /, or =
66
- expect(token).not.toMatch(/[+/=]/);
67
- });
68
- });
69
-
70
- describe('Token with Expiration', () => {
71
- it('should generate token with expiration', () => {
72
- const token = generator.generateWithExpiration(3600);
73
-
74
- expect(token.value).toBeDefined();
75
- expect(token.createdAt).toBeInstanceOf(Date);
76
- expect(token.expiresAt).toBeInstanceOf(Date);
77
- expect(token.expiresAt.getTime()).toBeGreaterThan(token.createdAt.getTime());
78
- });
79
-
80
- it('should set correct expiration time', () => {
81
- const expiration = 3600; // 1 hour
82
- const token = generator.generateWithExpiration(expiration);
83
-
84
- const expectedExpiration = Date.now() + expiration * 1000;
85
- const actualExpiration = token.expiresAt.getTime();
86
-
87
- expect(Math.abs(actualExpiration - expectedExpiration)).toBeLessThan(100);
88
- });
89
-
90
- it('should include metadata when provided', () => {
91
- const token = generator.generateWithExpiration(3600, { userId: '123' });
92
- expect(token.metadata).toEqual({ userId: '123' });
93
- });
94
- });
95
-
96
- describe('Session Token', () => {
97
- it('should generate session token', () => {
98
- const token = generator.generateSessionToken();
99
-
100
- expect(token.value).toBeDefined();
101
- expect(token.expiresAt).toBeInstanceOf(Date);
102
- });
103
- });
104
-
105
- describe('CSRF Token', () => {
106
- it('should generate CSRF token', () => {
107
- const token = generator.generateCsrfToken();
108
-
109
- expect(token.value).toBeDefined();
110
- // 30 minutes expiration
111
- const expectedExpiration = Date.now() + 1800 * 1000;
112
- expect(Math.abs(token.expiresAt.getTime() - expectedExpiration)).toBeLessThan(100);
113
- });
114
- });
115
-
116
- describe('API Token', () => {
117
- it('should generate API token with prefix', () => {
118
- const token = generator.generateApiToken('cf_');
119
-
120
- expect(token.value.startsWith('cf_')).toBe(true);
121
- });
122
-
123
- it('should set 1 year expiration', () => {
124
- const token = generator.generateApiToken();
125
-
126
- const expectedExpiration = Date.now() + 365 * 24 * 60 * 60 * 1000;
127
- expect(Math.abs(token.expiresAt.getTime() - expectedExpiration)).toBeLessThan(1000);
128
- });
129
- });
130
-
131
- describe('Verification Code', () => {
132
- it('should generate numeric code', () => {
133
- const code = generator.generateVerificationCode();
134
-
135
- expect(code.code).toMatch(/^\d{6}$/);
136
- });
137
-
138
- it('should generate code of specified length', () => {
139
- const code = generator.generateVerificationCode(8);
140
-
141
- expect(code.code).toMatch(/^\d{8}$/);
142
- });
143
-
144
- it('should set expiration', () => {
145
- const code = generator.generateVerificationCode(6, 10);
146
-
147
- const expectedExpiration = Date.now() + 10 * 60 * 1000;
148
- expect(Math.abs(code.expiresAt.getTime() - expectedExpiration)).toBeLessThan(100);
149
- });
150
-
151
- it('should track attempts', () => {
152
- const code = generator.generateVerificationCode(6, 10, 3);
153
-
154
- expect(code.attempts).toBe(0);
155
- expect(code.maxAttempts).toBe(3);
156
- });
157
- });
158
-
159
- describe('Signed Token', () => {
160
- it('should generate signed token', () => {
161
- const signed = generator.generateSignedToken({ userId: '123' });
162
-
163
- expect(signed.token).toBeDefined();
164
- expect(signed.signature).toBeDefined();
165
- expect(signed.combined).toBe(`${signed.token}.${signed.signature}`);
166
- });
167
-
168
- it('should require HMAC secret', () => {
169
- const noSecretGenerator = new TokenGenerator();
170
-
171
- expect(() => noSecretGenerator.generateSignedToken({ userId: '123' }))
172
- .toThrow(TokenGeneratorError);
173
- });
174
-
175
- it('should verify valid signed token', () => {
176
- const signed = generator.generateSignedToken({ userId: '123' });
177
- const payload = generator.verifySignedToken(signed.combined);
178
-
179
- expect(payload).not.toBeNull();
180
- expect((payload as any).userId).toBe('123');
181
- });
182
-
183
- it('should reject tampered token', () => {
184
- const signed = generator.generateSignedToken({ userId: '123' });
185
-
186
- // Tamper with the token
187
- const tampered = 'tampered' + signed.combined.slice(8);
188
- const payload = generator.verifySignedToken(tampered);
189
-
190
- expect(payload).toBeNull();
191
- });
192
-
193
- it('should reject tampered signature', () => {
194
- const signed = generator.generateSignedToken({ userId: '123' });
195
-
196
- // Tamper with signature
197
- const parts = signed.combined.split('.');
198
- const tampered = `${parts[0]}.tampered${parts[1].slice(8)}`;
199
- const payload = generator.verifySignedToken(tampered);
200
-
201
- expect(payload).toBeNull();
202
- });
203
-
204
- it('should reject expired signed token', async () => {
205
- const signed = generator.generateSignedToken({ userId: '123' }, 1); // 1 second
206
-
207
- // Wait for expiration
208
- await new Promise(resolve => setTimeout(resolve, 1100));
209
-
210
- const payload = generator.verifySignedToken(signed.combined);
211
- expect(payload).toBeNull();
212
- });
213
-
214
- it('should reject malformed token', () => {
215
- expect(generator.verifySignedToken('not.a.valid.token')).toBeNull();
216
- expect(generator.verifySignedToken('invalid')).toBeNull();
217
- expect(generator.verifySignedToken('')).toBeNull();
218
- });
219
- });
220
-
221
- describe('Token Pair', () => {
222
- it('should generate access and refresh tokens', () => {
223
- const pair = generator.generateTokenPair();
224
-
225
- expect(pair.accessToken.value).toBeDefined();
226
- expect(pair.refreshToken.value).toBeDefined();
227
- });
228
-
229
- it('should set different expirations', () => {
230
- const pair = generator.generateTokenPair();
231
-
232
- // Access token: 15 minutes
233
- const accessExpiration = Date.now() + 900 * 1000;
234
- expect(Math.abs(pair.accessToken.expiresAt.getTime() - accessExpiration)).toBeLessThan(100);
235
-
236
- // Refresh token: 7 days
237
- const refreshExpiration = Date.now() + 604800 * 1000;
238
- expect(Math.abs(pair.refreshToken.expiresAt.getTime() - refreshExpiration)).toBeLessThan(100);
239
- });
240
- });
241
-
242
- describe('Specialized Tokens', () => {
243
- it('should generate password reset token', () => {
244
- const token = generator.generatePasswordResetToken();
245
-
246
- expect(token.value).toBeDefined();
247
- // 30 minutes
248
- const expectedExpiration = Date.now() + 1800 * 1000;
249
- expect(Math.abs(token.expiresAt.getTime() - expectedExpiration)).toBeLessThan(100);
250
- });
251
-
252
- it('should generate email verification token', () => {
253
- const token = generator.generateEmailVerificationToken();
254
-
255
- expect(token.value).toBeDefined();
256
- // 24 hours
257
- const expectedExpiration = Date.now() + 86400 * 1000;
258
- expect(Math.abs(token.expiresAt.getTime() - expectedExpiration)).toBeLessThan(100);
259
- });
260
-
261
- it('should generate request ID', () => {
262
- const requestId = generator.generateRequestId();
263
-
264
- expect(requestId).toBeDefined();
265
- expect(requestId.length).toBeLessThan(20); // Shorter for logging
266
- });
267
-
268
- it('should generate correlation ID', () => {
269
- const correlationId = generator.generateCorrelationId();
270
-
271
- expect(correlationId).toBeDefined();
272
- expect(correlationId).toContain('-'); // timestamp-random format
273
- });
274
- });
275
-
276
- describe('Token Expiration Check', () => {
277
- it('should detect expired token', async () => {
278
- const token = generator.generateWithExpiration(1); // 1 second
279
-
280
- expect(generator.isExpired(token)).toBe(false);
281
-
282
- await new Promise(resolve => setTimeout(resolve, 1100));
283
-
284
- expect(generator.isExpired(token)).toBe(true);
285
- });
286
-
287
- it('should detect valid token', () => {
288
- const token = generator.generateWithExpiration(3600);
289
- expect(generator.isExpired(token)).toBe(false);
290
- });
291
- });
292
-
293
- describe('Token Comparison', () => {
294
- it('should compare equal tokens', () => {
295
- const token = generator.generate();
296
- expect(generator.compare(token, token)).toBe(true);
297
- });
298
-
299
- it('should reject different tokens', () => {
300
- const token1 = generator.generate();
301
- const token2 = generator.generate();
302
- expect(generator.compare(token1, token2)).toBe(false);
303
- });
304
-
305
- it('should reject different length tokens', () => {
306
- expect(generator.compare('short', 'longer-token')).toBe(false);
307
- });
308
-
309
- it('should use timing-safe comparison', () => {
310
- // This test verifies the comparison takes consistent time
311
- // regardless of where the mismatch occurs
312
- const token = generator.generate();
313
- const mismatchEarly = 'X' + token.slice(1);
314
- const mismatchLate = token.slice(0, -1) + 'X';
315
-
316
- // Both comparisons should work (timing consistency is internal)
317
- expect(generator.compare(token, mismatchEarly)).toBe(false);
318
- expect(generator.compare(token, mismatchLate)).toBe(false);
319
- });
320
- });
321
-
322
- describe('Factory Functions', () => {
323
- it('should create generator with factory', () => {
324
- const gen = createTokenGenerator('secret');
325
- expect(gen).toBeInstanceOf(TokenGenerator);
326
- });
327
-
328
- it('should get default generator singleton', () => {
329
- const gen1 = getDefaultGenerator();
330
- const gen2 = getDefaultGenerator();
331
- expect(gen1).toBe(gen2);
332
- });
333
- });
334
-
335
- describe('Quick Generate Functions', () => {
336
- it('should generate token', () => {
337
- const token = quickGenerate.token();
338
- expect(token).toBeDefined();
339
- });
340
-
341
- it('should generate session token', () => {
342
- const token = quickGenerate.sessionToken();
343
- expect(token.value).toBeDefined();
344
- });
345
-
346
- it('should generate CSRF token', () => {
347
- const token = quickGenerate.csrfToken();
348
- expect(token.value).toBeDefined();
349
- });
350
-
351
- it('should generate API token', () => {
352
- const token = quickGenerate.apiToken('cf_');
353
- expect(token.value.startsWith('cf_')).toBe(true);
354
- });
355
-
356
- it('should generate verification code', () => {
357
- const code = quickGenerate.verificationCode();
358
- expect(code.code).toMatch(/^\d{6}$/);
359
- });
360
-
361
- it('should generate request ID', () => {
362
- const id = quickGenerate.requestId();
363
- expect(id).toBeDefined();
364
- });
365
-
366
- it('should generate correlation ID', () => {
367
- const id = quickGenerate.correlationId();
368
- expect(id).toBeDefined();
369
- });
370
- });
371
- });
1
+ /**
2
+ * Token Generator Tests
3
+ *
4
+ * Tests verify:
5
+ * - Secure token generation
6
+ * - Token expiration
7
+ * - Signed token verification
8
+ * - Timing-safe comparison
9
+ */
10
+
11
+ import { describe, it, expect, beforeEach } from 'vitest';
12
+ import {
13
+ TokenGenerator,
14
+ TokenGeneratorError,
15
+ createTokenGenerator,
16
+ getDefaultGenerator,
17
+ quickGenerate,
18
+ } from '../src/token-generator.js';
19
+
20
+ describe('TokenGenerator', () => {
21
+ let generator: TokenGenerator;
22
+
23
+ beforeEach(() => {
24
+ generator = new TokenGenerator({
25
+ hmacSecret: 'test-secret-key-for-hmac-operations',
26
+ defaultExpiration: 3600,
27
+ });
28
+ });
29
+
30
+ describe('Configuration', () => {
31
+ it('should use default configuration', () => {
32
+ expect(() => new TokenGenerator()).not.toThrow();
33
+ });
34
+
35
+ it('should reject token length below 16 bytes', () => {
36
+ expect(() => new TokenGenerator({
37
+ defaultLength: 8,
38
+ })).toThrow(TokenGeneratorError);
39
+ });
40
+
41
+ it('should accept custom encoding', () => {
42
+ const hexGenerator = new TokenGenerator({ encoding: 'hex' });
43
+ const token = hexGenerator.generate(16);
44
+ expect(token).toMatch(/^[0-9a-f]+$/);
45
+ });
46
+ });
47
+
48
+ describe('Token Generation', () => {
49
+ it('should generate token of specified length', () => {
50
+ const token = generator.generate(32);
51
+ // Base64url encoding: 32 bytes = ~43 chars
52
+ expect(token.length).toBeGreaterThan(40);
53
+ });
54
+
55
+ it('should generate unique tokens', () => {
56
+ const tokens = new Set<string>();
57
+ for (let i = 0; i < 100; i++) {
58
+ tokens.add(generator.generate());
59
+ }
60
+ expect(tokens.size).toBe(100);
61
+ });
62
+
63
+ it('should generate URL-safe tokens by default', () => {
64
+ const token = generator.generate();
65
+ // Base64url should not contain +, /, or =
66
+ expect(token).not.toMatch(/[+/=]/);
67
+ });
68
+ });
69
+
70
+ describe('Token with Expiration', () => {
71
+ it('should generate token with expiration', () => {
72
+ const token = generator.generateWithExpiration(3600);
73
+
74
+ expect(token.value).toBeDefined();
75
+ expect(token.createdAt).toBeInstanceOf(Date);
76
+ expect(token.expiresAt).toBeInstanceOf(Date);
77
+ expect(token.expiresAt.getTime()).toBeGreaterThan(token.createdAt.getTime());
78
+ });
79
+
80
+ it('should set correct expiration time', () => {
81
+ const expiration = 3600; // 1 hour
82
+ const token = generator.generateWithExpiration(expiration);
83
+
84
+ const expectedExpiration = Date.now() + expiration * 1000;
85
+ const actualExpiration = token.expiresAt.getTime();
86
+
87
+ expect(Math.abs(actualExpiration - expectedExpiration)).toBeLessThan(100);
88
+ });
89
+
90
+ it('should include metadata when provided', () => {
91
+ const token = generator.generateWithExpiration(3600, { userId: '123' });
92
+ expect(token.metadata).toEqual({ userId: '123' });
93
+ });
94
+ });
95
+
96
+ describe('Session Token', () => {
97
+ it('should generate session token', () => {
98
+ const token = generator.generateSessionToken();
99
+
100
+ expect(token.value).toBeDefined();
101
+ expect(token.expiresAt).toBeInstanceOf(Date);
102
+ });
103
+ });
104
+
105
+ describe('CSRF Token', () => {
106
+ it('should generate CSRF token', () => {
107
+ const token = generator.generateCsrfToken();
108
+
109
+ expect(token.value).toBeDefined();
110
+ // 30 minutes expiration
111
+ const expectedExpiration = Date.now() + 1800 * 1000;
112
+ expect(Math.abs(token.expiresAt.getTime() - expectedExpiration)).toBeLessThan(100);
113
+ });
114
+ });
115
+
116
+ describe('API Token', () => {
117
+ it('should generate API token with prefix', () => {
118
+ const token = generator.generateApiToken('cf_');
119
+
120
+ expect(token.value.startsWith('cf_')).toBe(true);
121
+ });
122
+
123
+ it('should set 1 year expiration', () => {
124
+ const token = generator.generateApiToken();
125
+
126
+ const expectedExpiration = Date.now() + 365 * 24 * 60 * 60 * 1000;
127
+ expect(Math.abs(token.expiresAt.getTime() - expectedExpiration)).toBeLessThan(1000);
128
+ });
129
+ });
130
+
131
+ describe('Verification Code', () => {
132
+ it('should generate numeric code', () => {
133
+ const code = generator.generateVerificationCode();
134
+
135
+ expect(code.code).toMatch(/^\d{6}$/);
136
+ });
137
+
138
+ it('should generate code of specified length', () => {
139
+ const code = generator.generateVerificationCode(8);
140
+
141
+ expect(code.code).toMatch(/^\d{8}$/);
142
+ });
143
+
144
+ it('should set expiration', () => {
145
+ const code = generator.generateVerificationCode(6, 10);
146
+
147
+ const expectedExpiration = Date.now() + 10 * 60 * 1000;
148
+ expect(Math.abs(code.expiresAt.getTime() - expectedExpiration)).toBeLessThan(100);
149
+ });
150
+
151
+ it('should track attempts', () => {
152
+ const code = generator.generateVerificationCode(6, 10, 3);
153
+
154
+ expect(code.attempts).toBe(0);
155
+ expect(code.maxAttempts).toBe(3);
156
+ });
157
+ });
158
+
159
+ describe('Signed Token', () => {
160
+ it('should generate signed token', () => {
161
+ const signed = generator.generateSignedToken({ userId: '123' });
162
+
163
+ expect(signed.token).toBeDefined();
164
+ expect(signed.signature).toBeDefined();
165
+ expect(signed.combined).toBe(`${signed.token}.${signed.signature}`);
166
+ });
167
+
168
+ it('should require HMAC secret', () => {
169
+ const noSecretGenerator = new TokenGenerator();
170
+
171
+ expect(() => noSecretGenerator.generateSignedToken({ userId: '123' }))
172
+ .toThrow(TokenGeneratorError);
173
+ });
174
+
175
+ it('should verify valid signed token', () => {
176
+ const signed = generator.generateSignedToken({ userId: '123' });
177
+ const payload = generator.verifySignedToken(signed.combined);
178
+
179
+ expect(payload).not.toBeNull();
180
+ expect((payload as any).userId).toBe('123');
181
+ });
182
+
183
+ it('should reject tampered token', () => {
184
+ const signed = generator.generateSignedToken({ userId: '123' });
185
+
186
+ // Tamper with the token
187
+ const tampered = 'tampered' + signed.combined.slice(8);
188
+ const payload = generator.verifySignedToken(tampered);
189
+
190
+ expect(payload).toBeNull();
191
+ });
192
+
193
+ it('should reject tampered signature', () => {
194
+ const signed = generator.generateSignedToken({ userId: '123' });
195
+
196
+ // Tamper with signature
197
+ const parts = signed.combined.split('.');
198
+ const tampered = `${parts[0]}.tampered${parts[1].slice(8)}`;
199
+ const payload = generator.verifySignedToken(tampered);
200
+
201
+ expect(payload).toBeNull();
202
+ });
203
+
204
+ it('should reject expired signed token', async () => {
205
+ const signed = generator.generateSignedToken({ userId: '123' }, 1); // 1 second
206
+
207
+ // Wait for expiration
208
+ await new Promise(resolve => setTimeout(resolve, 1100));
209
+
210
+ const payload = generator.verifySignedToken(signed.combined);
211
+ expect(payload).toBeNull();
212
+ });
213
+
214
+ it('should reject malformed token', () => {
215
+ expect(generator.verifySignedToken('not.a.valid.token')).toBeNull();
216
+ expect(generator.verifySignedToken('invalid')).toBeNull();
217
+ expect(generator.verifySignedToken('')).toBeNull();
218
+ });
219
+ });
220
+
221
+ describe('Token Pair', () => {
222
+ it('should generate access and refresh tokens', () => {
223
+ const pair = generator.generateTokenPair();
224
+
225
+ expect(pair.accessToken.value).toBeDefined();
226
+ expect(pair.refreshToken.value).toBeDefined();
227
+ });
228
+
229
+ it('should set different expirations', () => {
230
+ const pair = generator.generateTokenPair();
231
+
232
+ // Access token: 15 minutes
233
+ const accessExpiration = Date.now() + 900 * 1000;
234
+ expect(Math.abs(pair.accessToken.expiresAt.getTime() - accessExpiration)).toBeLessThan(100);
235
+
236
+ // Refresh token: 7 days
237
+ const refreshExpiration = Date.now() + 604800 * 1000;
238
+ expect(Math.abs(pair.refreshToken.expiresAt.getTime() - refreshExpiration)).toBeLessThan(100);
239
+ });
240
+ });
241
+
242
+ describe('Specialized Tokens', () => {
243
+ it('should generate password reset token', () => {
244
+ const token = generator.generatePasswordResetToken();
245
+
246
+ expect(token.value).toBeDefined();
247
+ // 30 minutes
248
+ const expectedExpiration = Date.now() + 1800 * 1000;
249
+ expect(Math.abs(token.expiresAt.getTime() - expectedExpiration)).toBeLessThan(100);
250
+ });
251
+
252
+ it('should generate email verification token', () => {
253
+ const token = generator.generateEmailVerificationToken();
254
+
255
+ expect(token.value).toBeDefined();
256
+ // 24 hours
257
+ const expectedExpiration = Date.now() + 86400 * 1000;
258
+ expect(Math.abs(token.expiresAt.getTime() - expectedExpiration)).toBeLessThan(100);
259
+ });
260
+
261
+ it('should generate request ID', () => {
262
+ const requestId = generator.generateRequestId();
263
+
264
+ expect(requestId).toBeDefined();
265
+ expect(requestId.length).toBeLessThan(20); // Shorter for logging
266
+ });
267
+
268
+ it('should generate correlation ID', () => {
269
+ const correlationId = generator.generateCorrelationId();
270
+
271
+ expect(correlationId).toBeDefined();
272
+ expect(correlationId).toContain('-'); // timestamp-random format
273
+ });
274
+ });
275
+
276
+ describe('Token Expiration Check', () => {
277
+ it('should detect expired token', async () => {
278
+ const token = generator.generateWithExpiration(1); // 1 second
279
+
280
+ expect(generator.isExpired(token)).toBe(false);
281
+
282
+ await new Promise(resolve => setTimeout(resolve, 1100));
283
+
284
+ expect(generator.isExpired(token)).toBe(true);
285
+ });
286
+
287
+ it('should detect valid token', () => {
288
+ const token = generator.generateWithExpiration(3600);
289
+ expect(generator.isExpired(token)).toBe(false);
290
+ });
291
+ });
292
+
293
+ describe('Token Comparison', () => {
294
+ it('should compare equal tokens', () => {
295
+ const token = generator.generate();
296
+ expect(generator.compare(token, token)).toBe(true);
297
+ });
298
+
299
+ it('should reject different tokens', () => {
300
+ const token1 = generator.generate();
301
+ const token2 = generator.generate();
302
+ expect(generator.compare(token1, token2)).toBe(false);
303
+ });
304
+
305
+ it('should reject different length tokens', () => {
306
+ expect(generator.compare('short', 'longer-token')).toBe(false);
307
+ });
308
+
309
+ it('should use timing-safe comparison', () => {
310
+ // This test verifies the comparison takes consistent time
311
+ // regardless of where the mismatch occurs
312
+ const token = generator.generate();
313
+ const mismatchEarly = 'X' + token.slice(1);
314
+ const mismatchLate = token.slice(0, -1) + 'X';
315
+
316
+ // Both comparisons should work (timing consistency is internal)
317
+ expect(generator.compare(token, mismatchEarly)).toBe(false);
318
+ expect(generator.compare(token, mismatchLate)).toBe(false);
319
+ });
320
+ });
321
+
322
+ describe('Factory Functions', () => {
323
+ it('should create generator with factory', () => {
324
+ const gen = createTokenGenerator('secret');
325
+ expect(gen).toBeInstanceOf(TokenGenerator);
326
+ });
327
+
328
+ it('should get default generator singleton', () => {
329
+ const gen1 = getDefaultGenerator();
330
+ const gen2 = getDefaultGenerator();
331
+ expect(gen1).toBe(gen2);
332
+ });
333
+ });
334
+
335
+ describe('Quick Generate Functions', () => {
336
+ it('should generate token', () => {
337
+ const token = quickGenerate.token();
338
+ expect(token).toBeDefined();
339
+ });
340
+
341
+ it('should generate session token', () => {
342
+ const token = quickGenerate.sessionToken();
343
+ expect(token.value).toBeDefined();
344
+ });
345
+
346
+ it('should generate CSRF token', () => {
347
+ const token = quickGenerate.csrfToken();
348
+ expect(token.value).toBeDefined();
349
+ });
350
+
351
+ it('should generate API token', () => {
352
+ const token = quickGenerate.apiToken('cf_');
353
+ expect(token.value.startsWith('cf_')).toBe(true);
354
+ });
355
+
356
+ it('should generate verification code', () => {
357
+ const code = quickGenerate.verificationCode();
358
+ expect(code.code).toMatch(/^\d{6}$/);
359
+ });
360
+
361
+ it('should generate request ID', () => {
362
+ const id = quickGenerate.requestId();
363
+ expect(id).toBeDefined();
364
+ });
365
+
366
+ it('should generate correlation ID', () => {
367
+ const id = quickGenerate.correlationId();
368
+ expect(id).toBeDefined();
369
+ });
370
+ });
371
+ });