-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathutils.test.ts
More file actions
2325 lines (1979 loc) · 80 KB
/
utils.test.ts
File metadata and controls
2325 lines (1979 loc) · 80 KB
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright © 2024 Hardcore Engineering Inc.
//
// Licensed under the Eclipse Public License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may
// obtain a copy of the License at https://www.eclipse.org/legal/epl-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
import {
AccountRole,
type AccountUuid,
type Branding,
type MeasureContext,
type Person,
type PersonId,
type PersonUuid,
SocialIdType,
systemAccountUuid,
type WorkspaceUuid
} from '@hcengineering/core'
import {
generateWorkspaceUrl,
cleanEmail,
isEmail,
isShallowEqual,
getRolePower,
getEndpoints,
_getRegions,
EndpointKind,
getEndpoint,
hashWithSalt,
verifyPassword,
getAllTransactors,
wrap,
isOtpValid,
sendOtpEmail,
sendOtp,
generateUniqueOtp,
getEmailSocialId,
confirmEmail,
sendEmailConfirmation,
GUEST_ACCOUNT,
selectWorkspace,
signUpByEmail,
getAccount,
getWorkspaceById,
getWorkspaceInfoWithStatusById,
updateArchiveInfo,
cleanExpiredOtp,
getWorkspaces,
verifyAllowedServices,
getPersonName,
getInviteEmail,
getFrontUrl,
getMailUrl,
getSocialIdByKey,
getWorkspaceInvite,
loginOrSignUpWithProvider,
sendEmail,
addSocialIdBase,
doReleaseSocialId
} from '../utils'
// eslint-disable-next-line import/no-named-default
import platform, { getMetadata, PlatformError, Severity, Status } from '@hcengineering/platform'
import { decodeTokenVerbose, generateToken, TokenError } from '@hcengineering/server-token'
import { randomBytes } from 'crypto'
import { type AccountDB, AccountEventType, type Workspace } from '../types'
import { accountPlugin } from '../plugin'
// Mock platform with minimum required functionality
jest.mock('@hcengineering/platform', () => {
const actual = jest.requireActual('@hcengineering/platform')
return {
...actual,
...actual.default,
getMetadata: jest.fn(),
addEventListener: jest.fn(),
translate: jest.fn((id, params) => `${id} << ${JSON.stringify(params)}`)
}
})
// Mock server-token
jest.mock('@hcengineering/server-token', () => ({
TokenError: jest.requireActual('@hcengineering/server-token').TokenError,
decodeTokenVerbose: jest.fn(),
generateToken: jest.fn()
}))
// Mock analytics
jest.mock('@hcengineering/analytics', () => ({
Analytics: {
handleError: jest.fn()
}
}))
describe('account utils', () => {
describe('cleanEmail', () => {
test.each([
[' Test@Example.com ', 'test@example.com', 'should trim spaces and convert to lowercase'],
['USER@DOMAIN.COM', 'user@domain.com', 'should convert uppercase to lowercase'],
['normal@email.com', 'normal@email.com', 'should keep already normalized email unchanged'],
['Mixed.Case@Example.COM', 'mixed.case@example.com', 'should normalize mixed case email'],
[' spaced@email.com ', 'spaced@email.com', 'should trim multiple spaces']
])('%s -> %s (%s)', (input, expected) => {
expect(cleanEmail(input)).toBe(expected)
})
})
describe('isEmail', () => {
test.each([
['test@example.com', true, 'basic valid email'],
['user.name@domain.com', true, 'email with dot in local part'],
['user+tag@domain.co.uk', true, 'email with plus and subdomain'],
['small@domain.museum', true, 'email with long TLD'],
['user@subdomain.domain.com', true, 'email with multiple subdomains'],
['user-name@domain.com', true, 'email with hyphen in local part'],
['user123@domain.com', true, 'email with numbers'],
['user.name+tag@domain.com', true, 'email with dot and plus'],
['not-an-email', false, 'string without @ symbol'],
['@missing-user.com', false, 'missing local part'],
['missing-domain@', false, 'missing domain part'],
['spaces in@email.com', false, 'spaces in local part'],
['missing@domain', false, 'incomplete domain'],
['.invalid@email.com', false, 'leading dot in local part'],
['invalid@email.', false, 'trailing dot in domain'],
['invalid@@email.com', false, 'double @ symbol'],
['invalid@.com', false, 'missing domain part before dot'],
['invalid.@domain.com', false, 'trailing dot in local part'],
['invalid..email@domain.com', false, 'consecutive dots in local part'],
['invalid@domain..com', false, 'consecutive dots in domain'],
['invalid@-domain.com', false, 'leading hyphen in domain'],
['invalid@domain-.com', false, 'trailing hyphen in domain'],
['very.unusual."@".unusual.com@example.com', false, 'invalid special characters'],
[' space@domain.com', false, 'leading space'],
['space@domain.com ', false, 'trailing space']
])('%s -> %s (%s)', (input, expected) => {
expect(isEmail(input)).toBe(expected)
})
})
describe('isShallowEqual', () => {
test.each([
[{ a: 1, b: 2, c: 'test' }, { a: 1, b: 2, c: 'test' }, true, 'identical objects should be equal'],
[
{ a: 1, b: 2, c: 'test' },
{ a: 1, b: 2, c: 'different' },
false,
'objects with different values should not be equal'
],
[{ a: 1, b: 2 }, { a: 1, c: 2 }, false, 'objects with different keys should not be equal'],
[{ a: 1, b: 2 }, { a: 1, b: 2, c: 3 }, false, 'objects with different number of keys should not be equal'],
[
{ x: null, y: undefined },
{ x: null, y: undefined },
true,
'objects with null and undefined values should be equal'
],
[{ a: 1 }, { a: '1' }, false, 'objects with different value types should not be equal'],
[{}, {}, true, 'empty objects should be equal']
])('%# %s', (obj1, obj2, expected, description) => {
expect(isShallowEqual(obj1, obj2)).toBe(expected)
})
})
describe('generateWorkspaceUrl', () => {
test.each([
// Basic cases
['Simple Project', 'simpleproject', 'removes spaces between words'],
['UPPERCASE', 'uppercase', 'converts uppercase to lowercase'],
['lowercase', 'lowercase', 'preserves already lowercase text'],
['Test Workspace', 'testworkspace', 'basic workspace name'],
// Number handling
['123Project', 'project', 'removes numbers from the beginning of string'],
['Project123', 'project123', 'preserves numbers at the end of string'],
['Pro123ject', 'pro123ject', 'preserves numbers in the middle of string'],
['Workspace 123', 'workspace123', 'workspace with numbers'],
// Special characters and hyphens
['My-Project', 'my-project', 'preserves hyphens between words'],
['My_Project', 'myproject', 'removes underscores between words'],
['Project@#$%', 'project', 'removes all special characters'],
['workspace-with-hyphens', 'workspace-with-hyphens', 'preserves existing hyphens'],
['--test--', 'test', 'removes leading and trailing hyphens'],
// Complex combinations
['My-Awesome-Project-123', 'my-awesome-project-123', 'preserves hyphens and numbers in complex strings'],
['123-Project-456', 'project-456', 'removes leading numbers but preserves hyphens and trailing numbers'],
['@#$My&&Project!!', 'myproject', 'removes all special characters while preserving alphanumeric content'],
['Multiple Spaces', 'multiplespaces', 'collapses multiple spaces'],
['a.b.c', 'abc', 'removes dots'],
['UPPER.case.123', 'uppercase123', 'handles mixed case with dots and numbers'],
// Edge cases
['', '', 'handles empty string'],
['123456', '', 'handles numbers only'],
['@#$%^&', '', 'handles special characters only'],
[' ', '', 'handles spaces only'],
['a-b-c-1-2-3', 'a-b-c-1-2-3', 'preserves alternating letters, numbers, and hyphens'],
['---Project---', 'project', 'removes redundant hyphens'],
['Project!!!Name!!!123', 'projectname123', 'removes exclamation marks'],
['!@#Project123Name!@#', 'project123name', 'removes surrounding special characters'],
[' spaces ', 'spaces', 'trims leading and trailing spaces']
])('%s -> %s (%s)', (input, expected, description) => {
expect(generateWorkspaceUrl(input)).toBe(expected)
})
})
describe('getRolePower', () => {
it('should maintain correct power hierarchy', () => {
const owner = getRolePower(AccountRole.Owner)
const maintainer = getRolePower(AccountRole.Maintainer)
const user = getRolePower(AccountRole.User)
const guest = getRolePower(AccountRole.Guest)
const docGuest = getRolePower(AccountRole.DocGuest)
// Verify hierarchy
expect(owner).toBeGreaterThan(maintainer)
expect(maintainer).toBeGreaterThan(user)
expect(user).toBeGreaterThan(guest)
expect(guest).toBeGreaterThan(docGuest)
})
})
describe('transactor utils', () => {
describe('getEndpoints', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test.each([
['http://localhost:3000', ['http://localhost:3000'], 'single endpoint'],
[
'http://localhost:3000,http://localhost:3001',
['http://localhost:3000', 'http://localhost:3001'],
'multiple endpoints'
],
[
'http://internal:3000;http://external:3000;us',
['http://internal:3000;http://external:3000;us'],
'endpoint with internal, external urls and region'
],
[
' http://localhost:3000 , http://localhost:3001 ',
['http://localhost:3000', 'http://localhost:3001'],
'endpoints with whitespace'
],
[
'http://localhost:3000,,,http://localhost:3001',
['http://localhost:3000', 'http://localhost:3001'],
'endpoints with empty entries'
]
])('should parse "%s" into %j (%s)', (input, expected) => {
;(getMetadata as jest.Mock).mockReturnValue(input)
expect(getEndpoints()).toEqual(expected)
})
test('should throw error when no transactors provided', () => {
;(getMetadata as jest.Mock).mockReturnValue(undefined)
expect(() => getEndpoints()).toThrow('Please provide transactor endpoint url')
})
test('should throw error when empty transactors string provided', () => {
;(getMetadata as jest.Mock).mockReturnValue('')
expect(() => getEndpoints()).toThrow('Please provide transactor endpoint url')
})
test('should throw error when only commas provided', () => {
;(getMetadata as jest.Mock).mockReturnValue(',,,')
expect(() => getEndpoints()).toThrow('Please provide transactor endpoint url')
})
})
describe('_getRegions', () => {
const originalEnv = process.env
beforeEach(() => {
jest.clearAllMocks()
process.env = { ...originalEnv }
})
afterAll(() => {
process.env = originalEnv
})
test.each<[string, string | undefined, { region: string, name: string }[], string]>([
[
'http://internal:3000;http://external:3000;us',
undefined,
[{ region: 'us', name: '' }],
'single region from transactor'
],
[
'http://internal:3000;http://external:3000;us,http://internal:3001;http://external:3001;eu',
undefined,
[
{ region: 'us', name: '' },
{ region: 'eu', name: '' }
],
'multiple regions from transactors'
],
[
'http://internal:3000;http://external:3000;us',
'us|United States',
[{ region: 'us', name: 'United States' }],
'region with name from env'
],
[
'http://internal:3000;http://external:3000;us,http://internal:3001;http://external:3001;eu',
'us|United States;eu|European Union',
[
{ region: 'us', name: 'United States' },
{ region: 'eu', name: 'European Union' }
],
'multiple regions with names from env'
],
[
'http://internal:3000;http://external:3000;us',
'eu|European Union',
[
{ region: 'eu', name: 'European Union' },
{ region: 'us', name: '' }
],
'combines regions from env and transactors'
]
])(
'should handle transactors="%s" and REGION_INFO="%s" (%s)',
(transactors, regionInfo, expected, description) => {
;(getMetadata as jest.Mock).mockReturnValue(transactors)
if (regionInfo !== undefined) {
process.env.REGION_INFO = regionInfo
} else {
delete process.env.REGION_INFO
}
expect(_getRegions()).toEqual(expected)
}
)
})
describe('getEndpoint', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test.each([
[
'workspace1',
'us',
EndpointKind.Internal,
'http://internal:3000;http://external:3000;us',
'http://internal:3000',
'single endpoint internal'
],
[
'workspace1',
'us',
EndpointKind.External,
'http://internal:3000;http://external:3000;us',
'http://external:3000',
'single endpoint external'
],
[
'workspace1',
'eu',
EndpointKind.Internal,
'http://internal:3000;http://external:3000;us,http://internal:3001;http://external:3001;eu',
'http://internal:3001',
'multiple endpoints choose by region internal'
],
[
'workspace1',
'eu',
EndpointKind.External,
'http://internal:3000;http://external:3000;us,http://internal:3001;http://external:3001;eu',
'http://external:3001',
'multiple endpoints choose by region external'
]
])(
'should handle workspace="%s" region="%s" kind=%s (%s)',
(workspace, region, kind, transactors, expected, description) => {
;(getMetadata as jest.Mock).mockReturnValue(transactors)
expect(getEndpoint(workspace as WorkspaceUuid, region, kind)).toBe(expected)
}
)
test('should fall back to default region if requested region not found', () => {
const transactors = 'http://internal:3000;http://external:3000;'
;(getMetadata as jest.Mock).mockReturnValue(transactors)
expect(getEndpoint('workspace1' as WorkspaceUuid, 'nonexistent', EndpointKind.Internal)).toBe(
'http://internal:3000'
)
})
test('should throw error when no transactors available', () => {
;(getMetadata as jest.Mock).mockReturnValue('http://internal:3000;http://external:3000;us')
expect(() => getEndpoint('workspace1' as WorkspaceUuid, 'nonexistent', EndpointKind.Internal)).toThrow(
'Please provide transactor endpoint url'
)
})
})
describe('getAllTransactors', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test.each([
[
'http://internal:3000;http://external:3000;us',
EndpointKind.Internal,
['http://internal:3000'],
'single internal endpoint'
],
[
'http://internal:3000;http://external:3000;us',
EndpointKind.External,
['http://external:3000'],
'single external endpoint'
],
[
'http://internal:3000;http://external:3000;us,http://internal:3001;http://external:3001;eu',
EndpointKind.Internal,
['http://internal:3000', 'http://internal:3001'],
'multiple internal endpoints'
],
[';http://external:3000;us', EndpointKind.Internal, [''], 'empty internal url']
])('should get all %s endpoints for "%s" (%s)', (transactors, kind, expected, description) => {
;(getMetadata as jest.Mock).mockReturnValue(transactors)
expect(getAllTransactors(kind)).toEqual(expected)
})
test.each([
[undefined, 'undefined transactors'],
['', 'empty transactors'],
[',,,', 'only commas']
])('should throw error for %s', (transactors, description) => {
;(getMetadata as jest.Mock).mockReturnValue(transactors)
expect(() => getAllTransactors(EndpointKind.Internal)).toThrow('Please provide transactor endpoint url')
})
})
})
describe('password utils', () => {
describe('hashWithSalt', () => {
test.each([
['simple', 'basic password'],
['p@ssw0rd!123', 'complex password'],
['', 'empty password'],
['a'.repeat(100), 'long password'],
['🔑password', 'password with emoji'],
[' password ', 'password with spaces']
])('should hash "%s" consistently (%s)', (password, description) => {
const salt = randomBytes(32)
const hash1 = hashWithSalt(password, salt)
const hash2 = hashWithSalt(password, salt)
// Same password + salt should produce same hash
expect(Buffer.compare(hash1 as any, hash2 as any)).toBe(0)
})
test('should produce different hashes for different salts', () => {
const password = 'password123'
const salt1 = randomBytes(32)
const salt2 = randomBytes(32)
const hash1 = hashWithSalt(password, salt1)
const hash2 = hashWithSalt(password, salt2)
// Same password with different salts should produce different hashes
expect(Buffer.compare(hash1 as any, hash2 as any)).not.toBe(0)
})
test('should produce different hashes for different passwords', () => {
const salt = randomBytes(32)
const hash1 = hashWithSalt('password1', salt)
const hash2 = hashWithSalt('password2', salt)
// Different passwords with same salt should produce different hashes
expect(Buffer.compare(hash1 as any, hash2 as any)).not.toBe(0)
})
})
describe('verifyPassword', () => {
test.each([
['correct password', 'password123', true],
['wrong password', 'wrongpass', false],
['empty password', '', false],
['long password', 'a'.repeat(100), true],
['password with spaces', ' password123 ', true],
['password with special chars', 'p@ssw0rd!123', true]
])('should verify %s', (description, password, shouldMatch) => {
const salt = randomBytes(32)
const hash = shouldMatch ? hashWithSalt(password, salt) : hashWithSalt('different', salt)
expect(verifyPassword(password, hash, salt)).toBe(shouldMatch)
})
test.each([
['null hash', 'password123', null, randomBytes(32)],
['null salt', 'password123', randomBytes(32), null],
['null both', 'password123', null, null]
])('should handle %s', (description, password, hash, salt) => {
expect(verifyPassword(password, hash, salt)).toBe(false)
})
})
})
describe('wrap', () => {
const mockCtx = {
error: jest.fn()
} as unknown as MeasureContext
const mockDb = {} as unknown as AccountDB
const mockBranding = null
beforeEach(() => {
jest.clearAllMocks()
})
test('should handle successful execution', async () => {
const mockResult = { data: 'test' }
const mockMethod = jest.fn().mockResolvedValue(mockResult)
const wrappedMethod = wrap(mockMethod)
const request = { id: 'req1', params: { param1: 'value1', param2: 'value2' } }
const result = await wrappedMethod(mockCtx, mockDb, mockBranding, request, 'token')
expect(result).toEqual({ id: 'req1', result: mockResult })
expect(mockMethod).toHaveBeenCalledWith(
mockCtx,
mockDb,
mockBranding,
'token',
{
param1: 'value1',
param2: 'value2'
},
undefined
)
})
test('should handle token parameter', async () => {
const mockResult = { data: 'test' }
const mockMethod = jest.fn().mockResolvedValue(mockResult)
const wrappedMethod = wrap(mockMethod)
const request = { id: 'req1', params: { param1: 'value1' } }
const result = await wrappedMethod(mockCtx, mockDb, mockBranding, request, 'token')
expect(result).toEqual({ id: 'req1', result: mockResult })
expect(mockMethod).toHaveBeenCalledWith(mockCtx, mockDb, mockBranding, 'token', { param1: 'value1' }, undefined)
})
test('should handle PlatformError', async () => {
const errorStatus = new Status(Severity.ERROR, 'test-error' as any, {})
const mockMethod = jest.fn().mockRejectedValue(new PlatformError(errorStatus))
Object.defineProperty(mockMethod, 'name', { value: 'mockAccMethod' })
const wrappedMethod = wrap(mockMethod)
const request = { id: 'req1', params: [] }
const result = await wrappedMethod(mockCtx, mockDb, mockBranding, request, 'token')
expect(result).toEqual({ error: errorStatus })
expect(mockCtx.error).toHaveBeenCalledWith('Error while processing account method', {
status: errorStatus,
method: 'mockAccMethod'
})
})
test('should handle TokenError', async () => {
const mockMethod = jest.fn().mockRejectedValue(new TokenError('test error'))
const wrappedMethod = wrap(mockMethod)
const request = { id: 'req1', params: [] }
const result = await wrappedMethod(mockCtx, mockDb, mockBranding, request, 'token')
expect(result).toEqual({
error: new Status(Severity.ERROR, platform.status.Unauthorized, {})
})
})
test('should handle internal server error', async () => {
const error = new Error('unexpected error')
const mockMethod = jest.fn().mockRejectedValue(error)
Object.defineProperty(mockMethod, 'name', { value: 'mockAccMethod' })
const wrappedMethod = wrap(mockMethod)
const request = { id: 'req1', params: [] }
const result = await wrappedMethod(mockCtx, mockDb, mockBranding, request, 'token')
expect(result.error.code).toBe(platform.status.InternalServerError)
expect(mockCtx.error).toHaveBeenCalledWith('Error while processing account method', {
status: expect.any(Status),
origErr: error,
method: 'mockAccMethod'
})
})
test('should not report non-internal errors to analytics', async () => {
const errorStatus = new Status(Severity.ERROR, 'known-error' as any, {})
const mockMethod = jest.fn().mockRejectedValue(new PlatformError(errorStatus))
const wrappedMethod = wrap(mockMethod)
const request = { id: 'req1', params: [] }
await wrappedMethod(mockCtx, mockDb, mockBranding, request, 'token')
})
test('should handle timezone parameter', async () => {
const mockResult = { data: 'test' }
const mockMethod = jest.fn().mockResolvedValue(mockResult)
const wrappedMethod = wrap(mockMethod)
const mockTimezone = 'America/New_York'
const request = { id: 'req1', params: { param1: 'value1' } }
const result = await wrappedMethod(mockCtx, mockDb, mockBranding, request, 'token', { timezone: mockTimezone })
expect(result).toEqual({ id: 'req1', result: mockResult })
expect(mockMethod).toHaveBeenCalledWith(
mockCtx,
mockDb,
mockBranding,
'token',
{ param1: 'value1' },
{ timezone: mockTimezone }
)
})
})
describe('with mocked fetch', () => {
const mockFetch = jest.fn(() => Promise.resolve({ ok: true }))
beforeEach(() => {
jest.clearAllMocks()
global.fetch = mockFetch as any
})
afterEach(() => {
jest.clearAllMocks()
})
describe('otp utils', () => {
const mockCtx = {
error: jest.fn()
} as unknown as MeasureContext
const mockBranding: Branding = {
language: 'en',
title: 'Test App'
}
const mockDb = {
otp: {
findOne: jest.fn(),
find: jest.fn(),
insertOne: jest.fn()
}
} as unknown as AccountDB
const sesUrl = 'https://ses.example.com'
const sesAuth = 'test-auth-token'
const originalConsoleError = console.error
beforeEach(() => {
jest.clearAllMocks()
console.error = jest.fn()
;(getMetadata as jest.Mock).mockImplementation((key) => {
switch (key) {
case accountPlugin.metadata.OtpRetryDelaySec:
return 30
case accountPlugin.metadata.OtpTimeToLiveSec:
return 60
case accountPlugin.metadata.MAIL_URL:
return sesUrl
case accountPlugin.metadata.MAIL_AUTH_TOKEN:
return sesAuth
case accountPlugin.metadata.ProductName:
return 'Test Product'
default:
return undefined
}
})
})
afterEach(() => {
jest.clearAllMocks()
console.error = originalConsoleError
})
describe('generateUniqueOtp', () => {
test('should generate 6-digit numeric code', async () => {
;(mockDb.otp.findOne as jest.Mock).mockResolvedValue(null)
const code = await generateUniqueOtp(mockDb)
expect(code).toMatch(/^\d{6}$/)
expect(mockDb.otp.findOne).toHaveBeenCalledWith({ code })
})
test('should retry if code exists', async () => {
;(mockDb.otp.findOne as jest.Mock)
.mockResolvedValueOnce({ code: '123456' })
.mockResolvedValueOnce({ code: '234567' })
.mockResolvedValueOnce(null)
const code = await generateUniqueOtp(mockDb)
expect(code).toMatch(/^\d{6}$/)
expect(mockDb.otp.findOne).toHaveBeenCalledTimes(3)
})
})
const socialIdId = '333444555' as PersonId
describe('sendOtp', () => {
const mockSocialId = {
_id: socialIdId,
personUuid: '123456-uuid' as PersonUuid,
type: SocialIdType.EMAIL,
value: 'test@example.com',
key: 'email:test@example.com'
}
test('should return existing OTP if not expired', async () => {
const now = Date.now()
const mockOtpData = {
code: '123456',
expiresOn: now + 60000,
createdOn: now - 15000
}
;(mockDb.otp.find as jest.Mock).mockResolvedValue([mockOtpData])
const result = await sendOtp(mockCtx, mockDb, mockBranding, mockSocialId)
expect(result).toEqual({
sent: true,
retryOn: mockOtpData.createdOn + 30000
})
expect(mockDb.otp.insertOne).not.toHaveBeenCalled()
})
test('should generate and send new OTP if expired', async () => {
;(mockDb.otp.find as jest.Mock).mockResolvedValue([])
;(mockDb.otp.findOne as jest.Mock).mockResolvedValue(null)
const result = await sendOtp(mockCtx, mockDb, mockBranding, mockSocialId)
expect(result).toEqual({
sent: true,
retryOn: expect.any(Number)
})
expect(mockDb.otp.insertOne).toHaveBeenCalledWith({
socialId: mockSocialId._id,
code: expect.any(String),
expiresOn: expect.any(Number),
createdOn: expect.any(Number)
})
})
test('should throw error for unsupported social id type', async () => {
const invalidSocialId = {
_id: '999888777' as PersonId,
personUuid: '123456-uuid' as PersonUuid,
type: 'INVALID' as SocialIdType,
value: 'test',
key: 'invalid:test'
}
await expect(sendOtp(mockCtx, mockDb, mockBranding, invalidSocialId)).rejects.toThrow(
'Unsupported OTP social id type'
)
})
})
describe('sendOtpEmail', () => {
beforeEach(() => {
const mockFetch = jest.fn()
mockFetch.mockResolvedValue({ ok: true })
global.fetch = mockFetch
})
test('should send email with OTP', async () => {
await sendOtpEmail(mockCtx, mockBranding, '123456', 'test@example.com')
expect(global.fetch).toHaveBeenCalledWith(`${sesUrl}/send`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${sesAuth}`
},
body: expect.stringContaining('123456')
})
})
test('should handle missing SES URL', async () => {
;(getMetadata as jest.Mock).mockReturnValue(undefined)
await sendOtpEmail(mockCtx, mockBranding, '123456', 'test@example.com')
expect(mockCtx.error).toHaveBeenCalledWith('Please provide email service url to enable email otp')
expect(global.fetch).not.toHaveBeenCalled()
})
})
describe('isOtpValid', () => {
test('should return true for valid non-expired OTP', async () => {
const mockOtpData = {
expiresOn: Date.now() + 60000
}
;(mockDb.otp.findOne as jest.Mock).mockResolvedValue(mockOtpData)
const result = await isOtpValid(mockDb, socialIdId, '123456')
expect(result).toBe(true)
})
test('should return false for expired OTP', async () => {
const mockOtpData = {
expiresOn: Date.now() - 1000
}
;(mockDb.otp.findOne as jest.Mock).mockResolvedValue(mockOtpData)
const result = await isOtpValid(mockDb, socialIdId, '123456')
expect(result).toBe(false)
})
test('should return false for non-existent OTP', async () => {
;(mockDb.otp.findOne as jest.Mock).mockResolvedValue(null)
const result = await isOtpValid(mockDb, socialIdId, '123456')
expect(result).toBe(false)
})
})
})
describe('email confirmation utils', () => {
const mockCtx = {
error: jest.fn(),
info: jest.fn()
} as unknown as MeasureContext
const mockBranding: Branding = {
language: 'en',
title: 'Test App',
front: 'https://app.example.com'
}
const mockDb = {
socialId: {
findOne: jest.fn(),
update: jest.fn()
}
} as unknown as AccountDB
beforeEach(() => {
jest.clearAllMocks()
mockFetch.mockResolvedValue({ ok: true })
;(getMetadata as jest.Mock).mockImplementation((key) => {
switch (key) {
case accountPlugin.metadata.MAIL_URL:
return 'https://ses.example.com'
case accountPlugin.metadata.MAIL_AUTH_TOKEN:
return 'test-auth-token'
case accountPlugin.metadata.ProductName:
return 'Test Product'
case accountPlugin.metadata.FrontURL:
return 'https://app.example.com'
default:
return undefined
}
})
})
afterEach(() => {
jest.clearAllMocks()
})
describe('sendEmailConfirmation', () => {
const account = 'test-account-id' as PersonUuid
const email = 'test@example.com'
test('should send confirmation email with correct link', async () => {
await sendEmailConfirmation(mockCtx, mockBranding, account, email)
expect(mockFetch).toHaveBeenCalledWith(
'https://ses.example.com/send',
expect.objectContaining({
method: 'post',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer test-auth-token'
},
body: expect.stringContaining('https://app.example.com/login/confirm')
})
)
})
test('should throw error if MAIL_URL is missing', async () => {
;(getMetadata as jest.Mock).mockReturnValue(undefined)
await expect(sendEmailConfirmation(mockCtx, mockBranding, account, email)).rejects.toThrow(
new PlatformError(new Status(Severity.ERROR, platform.status.InternalServerError, {}))
)
expect(mockCtx.error).toHaveBeenCalledWith('Please provide MAIL_URL to enable email confirmations.')
})
test('should use branding front URL if available', async () => {
const brandingWithFront = {
...mockBranding,
front: 'https://custom.example.com'
}
await sendEmailConfirmation(mockCtx, brandingWithFront, account, email)
expect(mockFetch).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
body: expect.stringContaining('https://custom.example.com/login/confirm')
})
)
})
})
describe('confirmEmail', () => {
const account = 'test-account-id'
const email = 'test@example.com'
test('should confirm unverified email', async () => {
const mockSocialId = {
_id: '1000000001' as PersonId,
key: 'email:test@example.com',
type: SocialIdType.EMAIL,
value: email,
verifiedOn: null
}
;(mockDb.socialId.findOne as jest.Mock).mockResolvedValue(mockSocialId)
await confirmEmail(mockCtx, mockDb, account, email)
expect(mockDb.socialId.update).toHaveBeenCalledWith(
{ _id: mockSocialId._id },
{ verifiedOn: expect.any(Number) }
)
})
test('should throw error if email not found', async () => {
;(mockDb.socialId.findOne as jest.Mock).mockResolvedValue(null)
await expect(confirmEmail(mockCtx, mockDb, account, email)).rejects.toThrow(
new PlatformError(
new Status(Severity.ERROR, platform.status.SocialIdNotFound, {
value: email,
type: SocialIdType.EMAIL
})
)
)
})
test('should throw error if email already confirmed', async () => {
const mockSocialId = {
key: 'email:test@example.com',
type: SocialIdType.EMAIL,
value: email,
verifiedOn: Date.now()
}
;(mockDb.socialId.findOne as jest.Mock).mockResolvedValue(mockSocialId)
await expect(confirmEmail(mockCtx, mockDb, account, email)).rejects.toThrow(
new PlatformError(
new Status(Severity.ERROR, platform.status.SocialIdAlreadyConfirmed, {
socialId: email,
type: SocialIdType.EMAIL
})
)
)
})
test('should normalize email before confirmation', async () => {
const mockSocialId = {
key: 'email:test@example.com',
type: SocialIdType.EMAIL,
value: 'test@example.com',
verifiedOn: null
}
;(mockDb.socialId.findOne as jest.Mock).mockResolvedValue(mockSocialId)
await confirmEmail(mockCtx, mockDb, account, ' TEST@EXAMPLE.COM ')
expect(mockDb.socialId.findOne).toHaveBeenCalledWith({
type: SocialIdType.EMAIL,