@flusys/nestjs-shared 6.0.2 → 6.1.0

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 (63) hide show
  1. package/cjs/classes/api-controller.class.spec.js +684 -0
  2. package/cjs/classes/api-service.class.spec.js +809 -0
  3. package/cjs/classes/handle-custome-db.spec.js +82 -0
  4. package/cjs/classes/hybrid-cache.class.spec.js +168 -0
  5. package/cjs/classes/winston.logger.class.spec.js +330 -0
  6. package/cjs/decorators/api-response.decorator.spec.js +126 -0
  7. package/cjs/decorators/current-user.decorator.spec.js +74 -0
  8. package/cjs/decorators/log-action.decorator.spec.js +353 -0
  9. package/cjs/decorators/public.decorator.spec.js +50 -0
  10. package/cjs/decorators/require-permission.decorator.spec.js +147 -0
  11. package/cjs/exceptions/base-app.exception.spec.js +157 -0
  12. package/cjs/exceptions/permission.exception.spec.js +82 -0
  13. package/cjs/filters/global-exception.filter.spec.js +440 -0
  14. package/cjs/guards/jwt-auth.guard.spec.js +75 -0
  15. package/cjs/guards/optional-jwt-auth.guard.spec.js +55 -0
  16. package/cjs/guards/permission.guard.spec.js +358 -0
  17. package/cjs/interceptors/delete-empty-id-from-body.interceptor.spec.js +107 -0
  18. package/cjs/interceptors/idempotency.interceptor.spec.js +116 -0
  19. package/cjs/interceptors/response-meta.interceptor.spec.js +89 -0
  20. package/cjs/interceptors/set-user-field-on-body.interceptor.spec.js +128 -0
  21. package/cjs/interceptors/slug.interceptor.spec.js +110 -0
  22. package/cjs/middlewares/logger.middleware.spec.js +462 -0
  23. package/cjs/modules/cache/cache.module.spec.js +48 -0
  24. package/cjs/modules/datasource/multi-tenant-datasource.service.spec.js +381 -0
  25. package/cjs/modules/utils/utils.service.spec.js +169 -0
  26. package/cjs/utils/date-time.util.spec.js +84 -0
  27. package/cjs/utils/html-sanitizer.util.spec.js +76 -0
  28. package/cjs/utils/permission-cache-key.util.spec.js +88 -0
  29. package/cjs/utils/query-helpers.util.spec.js +209 -0
  30. package/cjs/utils/request.util.spec.js +249 -0
  31. package/cjs/utils/string.util.spec.js +63 -0
  32. package/fesm/classes/api-controller.class.spec.js +680 -0
  33. package/fesm/classes/api-service.class.spec.js +805 -0
  34. package/fesm/classes/handle-custome-db.spec.js +78 -0
  35. package/fesm/classes/hybrid-cache.class.spec.js +164 -0
  36. package/fesm/classes/winston.logger.class.spec.js +327 -0
  37. package/fesm/decorators/api-response.decorator.spec.js +122 -0
  38. package/fesm/decorators/current-user.decorator.spec.js +73 -0
  39. package/fesm/decorators/log-action.decorator.spec.js +349 -0
  40. package/fesm/decorators/public.decorator.spec.js +46 -0
  41. package/fesm/decorators/require-permission.decorator.spec.js +143 -0
  42. package/fesm/exceptions/base-app.exception.spec.js +153 -0
  43. package/fesm/exceptions/permission.exception.spec.js +78 -0
  44. package/fesm/filters/global-exception.filter.spec.js +436 -0
  45. package/fesm/guards/jwt-auth.guard.spec.js +71 -0
  46. package/fesm/guards/optional-jwt-auth.guard.spec.js +51 -0
  47. package/fesm/guards/permission.guard.spec.js +354 -0
  48. package/fesm/interceptors/delete-empty-id-from-body.interceptor.spec.js +103 -0
  49. package/fesm/interceptors/idempotency.interceptor.spec.js +112 -0
  50. package/fesm/interceptors/response-meta.interceptor.spec.js +85 -0
  51. package/fesm/interceptors/set-user-field-on-body.interceptor.spec.js +124 -0
  52. package/fesm/interceptors/slug.interceptor.spec.js +106 -0
  53. package/fesm/middlewares/logger.middleware.spec.js +459 -0
  54. package/fesm/modules/cache/cache.module.spec.js +44 -0
  55. package/fesm/modules/datasource/multi-tenant-datasource.service.spec.js +377 -0
  56. package/fesm/modules/utils/utils.service.spec.js +165 -0
  57. package/fesm/utils/date-time.util.spec.js +80 -0
  58. package/fesm/utils/html-sanitizer.util.spec.js +72 -0
  59. package/fesm/utils/permission-cache-key.util.spec.js +84 -0
  60. package/fesm/utils/query-helpers.util.spec.js +205 -0
  61. package/fesm/utils/request.util.spec.js +245 -0
  62. package/fesm/utils/string.util.spec.js +59 -0
  63. package/package.json +2 -2
@@ -0,0 +1,72 @@
1
+ import { escapeHtml, escapeHtmlVariables } from './html-sanitizer.util';
2
+ describe('html-sanitizer.util', ()=>{
3
+ describe('escapeHtml', ()=>{
4
+ it('should escape all special HTML characters', ()=>{
5
+ expect(escapeHtml('<script>alert("xss")</script>')).toBe('&lt;script&gt;alert(&quot;xss&quot;)&lt;&#x2F;script&gt;');
6
+ });
7
+ it('should escape ampersands', ()=>{
8
+ expect(escapeHtml('a & b')).toBe('a &amp; b');
9
+ });
10
+ it('should escape single quotes, backticks, and equals signs', ()=>{
11
+ expect(escapeHtml(`a='b' c=\`d\``)).toBe('a&#x3D;&#x27;b&#x27; c&#x3D;&#x60;d&#x60;');
12
+ });
13
+ it('should return an empty string for empty input', ()=>{
14
+ expect(escapeHtml('')).toBe('');
15
+ });
16
+ it('should return input unchanged when it has no special characters', ()=>{
17
+ expect(escapeHtml('Hello World 123')).toBe('Hello World 123');
18
+ });
19
+ it('should return non-string input coerced via nullish fallback', ()=>{
20
+ expect(escapeHtml(null)).toBe('');
21
+ expect(escapeHtml(undefined)).toBe('');
22
+ });
23
+ it('should return non-string, truthy input unchanged (not throw)', ()=>{
24
+ // e.g. a number passed at runtime despite the TS signature
25
+ expect(escapeHtml(42)).toBe(42);
26
+ });
27
+ });
28
+ describe('escapeHtmlVariables', ()=>{
29
+ it('should escape string values', ()=>{
30
+ expect(escapeHtmlVariables({
31
+ name: '<b>bold</b>'
32
+ })).toEqual({
33
+ name: '&lt;b&gt;bold&lt;&#x2F;b&gt;'
34
+ });
35
+ });
36
+ it('should convert numbers and booleans to strings without escaping', ()=>{
37
+ expect(escapeHtmlVariables({
38
+ count: 5,
39
+ active: true
40
+ })).toEqual({
41
+ count: '5',
42
+ active: 'true'
43
+ });
44
+ });
45
+ it('should stringify and escape object/array values', ()=>{
46
+ const result = escapeHtmlVariables({
47
+ meta: {
48
+ a: '<x>'
49
+ }
50
+ });
51
+ expect(result.meta).toBe(escapeHtml(JSON.stringify({
52
+ a: '<x>'
53
+ })));
54
+ });
55
+ it('should convert null/undefined values to empty string', ()=>{
56
+ expect(escapeHtmlVariables({
57
+ a: null,
58
+ b: undefined
59
+ })).toEqual({
60
+ a: '',
61
+ b: ''
62
+ });
63
+ });
64
+ it('should return an empty object for null/non-object input', ()=>{
65
+ expect(escapeHtmlVariables(null)).toEqual({});
66
+ expect(escapeHtmlVariables(undefined)).toEqual({});
67
+ });
68
+ it('should return an empty object for an empty input object', ()=>{
69
+ expect(escapeHtmlVariables({})).toEqual({});
70
+ });
71
+ });
72
+ });
@@ -0,0 +1,84 @@
1
+ import { buildPermissionCacheKey, DEFAULT_COMPANY_PERMISSION_KEY_FORMAT, DEFAULT_USER_PERMISSION_KEY_FORMAT } from './permission-cache-key.util';
2
+ describe('permission-cache-key.util', ()=>{
3
+ describe('buildPermissionCacheKey', ()=>{
4
+ it('should build a user-scoped key when no config is provided', ()=>{
5
+ const key = buildPermissionCacheKey({
6
+ userId: 'user-1'
7
+ });
8
+ expect(key).toBe(DEFAULT_USER_PERMISSION_KEY_FORMAT.replace('{userId}', 'user-1'));
9
+ });
10
+ it('should build a user-scoped key when company feature is disabled', ()=>{
11
+ const key = buildPermissionCacheKey({
12
+ userId: 'user-1',
13
+ companyId: 'company-1'
14
+ }, {
15
+ enableCompanyFeature: false
16
+ });
17
+ expect(key).toBe(DEFAULT_USER_PERMISSION_KEY_FORMAT.replace('{userId}', 'user-1'));
18
+ });
19
+ it('should build a user-scoped key when company feature enabled but no companyId given', ()=>{
20
+ const key = buildPermissionCacheKey({
21
+ userId: 'user-1'
22
+ }, {
23
+ enableCompanyFeature: true
24
+ });
25
+ expect(key).toBe(DEFAULT_USER_PERMISSION_KEY_FORMAT.replace('{userId}', 'user-1'));
26
+ });
27
+ it('should build a company-scoped key when company feature is enabled and companyId is present', ()=>{
28
+ const key = buildPermissionCacheKey({
29
+ userId: 'user-1',
30
+ companyId: 'company-1',
31
+ branchId: 'branch-1'
32
+ }, {
33
+ enableCompanyFeature: true
34
+ });
35
+ expect(key).toBe(DEFAULT_COMPANY_PERMISSION_KEY_FORMAT.replace('{userId}', 'user-1').replace('{companyId}', 'company-1').replace('{branchId}', 'branch-1'));
36
+ });
37
+ it('should default branchId placeholder to "null" when branchId is missing', ()=>{
38
+ const key = buildPermissionCacheKey({
39
+ userId: 'user-1',
40
+ companyId: 'company-1'
41
+ }, {
42
+ enableCompanyFeature: true
43
+ });
44
+ expect(key).toContain(':branch:null:');
45
+ });
46
+ it('should default branchId placeholder to "null" when branchId is explicitly null', ()=>{
47
+ const key = buildPermissionCacheKey({
48
+ userId: 'user-1',
49
+ companyId: 'company-1',
50
+ branchId: null
51
+ }, {
52
+ enableCompanyFeature: true
53
+ });
54
+ expect(key).toContain(':branch:null:');
55
+ });
56
+ it('should use a custom userPermissionKeyFormat when provided', ()=>{
57
+ const key = buildPermissionCacheKey({
58
+ userId: 'user-1'
59
+ }, {
60
+ userPermissionKeyFormat: 'custom:{userId}'
61
+ });
62
+ expect(key).toBe('custom:user-1');
63
+ });
64
+ it('should use a custom companyPermissionKeyFormat when provided', ()=>{
65
+ const key = buildPermissionCacheKey({
66
+ userId: 'user-1',
67
+ companyId: 'company-1'
68
+ }, {
69
+ enableCompanyFeature: true,
70
+ companyPermissionKeyFormat: 'custom:{companyId}:{userId}:{branchId}'
71
+ });
72
+ expect(key).toBe('custom:company-1:user-1:null');
73
+ });
74
+ it('should treat an empty-string companyId as no company scope', ()=>{
75
+ const key = buildPermissionCacheKey({
76
+ userId: 'user-1',
77
+ companyId: ''
78
+ }, {
79
+ enableCompanyFeature: true
80
+ });
81
+ expect(key).toBe(DEFAULT_USER_PERMISSION_KEY_FORMAT.replace('{userId}', 'user-1'));
82
+ });
83
+ });
84
+ });
@@ -0,0 +1,205 @@
1
+ import { BadRequestException } from '@nestjs/common';
2
+ import { buildMockUser } from '@test-utils/mocks/logged-user.mock';
3
+ import { applyCompanyFilter, buildCompanyWhereCondition, hasCompanyId, validateCompanyOwnership } from './query-helpers.util';
4
+ function createMockQueryBuilder() {
5
+ return {
6
+ andWhere: jest.fn().mockReturnThis()
7
+ };
8
+ }
9
+ describe('query-helpers.util', ()=>{
10
+ describe('applyCompanyFilter', ()=>{
11
+ it('should apply the company filter when feature enabled and user has companyId', ()=>{
12
+ const query = createMockQueryBuilder();
13
+ const user = buildMockUser({
14
+ companyId: 'company-1'
15
+ });
16
+ applyCompanyFilter(query, {
17
+ isCompanyFeatureEnabled: true,
18
+ entityAlias: 'file'
19
+ }, user);
20
+ expect(query.andWhere).toHaveBeenCalledWith('file.companyId = :companyId', {
21
+ companyId: 'company-1'
22
+ });
23
+ });
24
+ it('should use a custom column name when provided', ()=>{
25
+ const query = createMockQueryBuilder();
26
+ const user = buildMockUser({
27
+ companyId: 'company-1'
28
+ });
29
+ applyCompanyFilter(query, {
30
+ isCompanyFeatureEnabled: true,
31
+ entityAlias: 'file',
32
+ columnName: 'company_id'
33
+ }, user);
34
+ expect(query.andWhere).toHaveBeenCalledWith('file.company_id = :companyId', {
35
+ companyId: 'company-1'
36
+ });
37
+ });
38
+ it('should not apply filter when feature disabled', ()=>{
39
+ const query = createMockQueryBuilder();
40
+ const user = buildMockUser({
41
+ companyId: 'company-1'
42
+ });
43
+ applyCompanyFilter(query, {
44
+ isCompanyFeatureEnabled: false,
45
+ entityAlias: 'file'
46
+ }, user);
47
+ expect(query.andWhere).not.toHaveBeenCalled();
48
+ });
49
+ it('should not apply filter when user is null', ()=>{
50
+ const query = createMockQueryBuilder();
51
+ applyCompanyFilter(query, {
52
+ isCompanyFeatureEnabled: true,
53
+ entityAlias: 'file'
54
+ }, null);
55
+ expect(query.andWhere).not.toHaveBeenCalled();
56
+ });
57
+ it('should not apply filter when user has no companyId', ()=>{
58
+ const query = createMockQueryBuilder();
59
+ const user = buildMockUser({
60
+ companyId: undefined
61
+ });
62
+ applyCompanyFilter(query, {
63
+ isCompanyFeatureEnabled: true,
64
+ entityAlias: 'file'
65
+ }, user);
66
+ expect(query.andWhere).not.toHaveBeenCalled();
67
+ });
68
+ it('should return the same query builder instance', ()=>{
69
+ const query = createMockQueryBuilder();
70
+ const result = applyCompanyFilter(query, {
71
+ isCompanyFeatureEnabled: false,
72
+ entityAlias: 'file'
73
+ }, null);
74
+ expect(result).toBe(query);
75
+ });
76
+ });
77
+ describe('buildCompanyWhereCondition', ()=>{
78
+ it('should add companyId when feature enabled and user has one', ()=>{
79
+ const user = buildMockUser({
80
+ companyId: 'company-1'
81
+ });
82
+ const result = buildCompanyWhereCondition({
83
+ id: '1'
84
+ }, true, user);
85
+ expect(result).toEqual({
86
+ id: '1',
87
+ companyId: 'company-1'
88
+ });
89
+ });
90
+ it('should return base where unchanged when feature disabled', ()=>{
91
+ const user = buildMockUser({
92
+ companyId: 'company-1'
93
+ });
94
+ const result = buildCompanyWhereCondition({
95
+ id: '1'
96
+ }, false, user);
97
+ expect(result).toEqual({
98
+ id: '1'
99
+ });
100
+ });
101
+ it('should return base where unchanged when user is null', ()=>{
102
+ const result = buildCompanyWhereCondition({
103
+ id: '1'
104
+ }, true, null);
105
+ expect(result).toEqual({
106
+ id: '1'
107
+ });
108
+ });
109
+ it('should return base where unchanged when user has no companyId', ()=>{
110
+ const user = buildMockUser({
111
+ companyId: undefined
112
+ });
113
+ const result = buildCompanyWhereCondition({
114
+ id: '1'
115
+ }, true, user);
116
+ expect(result).toEqual({
117
+ id: '1'
118
+ });
119
+ });
120
+ });
121
+ describe('hasCompanyId', ()=>{
122
+ it('should return true for an object with a companyId property', ()=>{
123
+ expect(hasCompanyId({
124
+ companyId: 'company-1'
125
+ })).toBe(true);
126
+ });
127
+ it('should return true even when companyId is explicitly undefined but present', ()=>{
128
+ expect(hasCompanyId({
129
+ companyId: undefined
130
+ })).toBe(true);
131
+ });
132
+ it('should return false for an object without a companyId property', ()=>{
133
+ expect(hasCompanyId({
134
+ id: '1'
135
+ })).toBe(false);
136
+ });
137
+ it('should return false for null', ()=>{
138
+ expect(hasCompanyId(null)).toBe(false);
139
+ });
140
+ it('should return false for non-object values', ()=>{
141
+ expect(hasCompanyId('string')).toBe(false);
142
+ expect(hasCompanyId(42)).toBe(false);
143
+ });
144
+ });
145
+ describe('validateCompanyOwnership', ()=>{
146
+ it('should not throw when feature disabled', ()=>{
147
+ const user = buildMockUser({
148
+ companyId: 'company-1'
149
+ });
150
+ expect(()=>validateCompanyOwnership({
151
+ companyId: 'company-2'
152
+ }, user, false, 'Entity')).not.toThrow();
153
+ });
154
+ it('should not throw when user is null', ()=>{
155
+ expect(()=>validateCompanyOwnership({
156
+ companyId: 'company-2'
157
+ }, null, true, 'Entity')).not.toThrow();
158
+ });
159
+ it('should not throw when entity has no companyId', ()=>{
160
+ const user = buildMockUser({
161
+ companyId: 'company-1'
162
+ });
163
+ expect(()=>validateCompanyOwnership({
164
+ id: '1'
165
+ }, user, true, 'Entity')).not.toThrow();
166
+ });
167
+ it('should not throw when entity companyId is falsy', ()=>{
168
+ const user = buildMockUser({
169
+ companyId: 'company-1'
170
+ });
171
+ expect(()=>validateCompanyOwnership({
172
+ companyId: null
173
+ }, user, true, 'Entity')).not.toThrow();
174
+ });
175
+ it('should not throw when entity companyId matches user companyId', ()=>{
176
+ const user = buildMockUser({
177
+ companyId: 'company-1'
178
+ });
179
+ expect(()=>validateCompanyOwnership({
180
+ companyId: 'company-1'
181
+ }, user, true, 'Entity')).not.toThrow();
182
+ });
183
+ it('should throw BadRequestException when entity belongs to a different company', ()=>{
184
+ const user = buildMockUser({
185
+ companyId: 'company-1'
186
+ });
187
+ expect(()=>validateCompanyOwnership({
188
+ companyId: 'company-2'
189
+ }, user, true, 'Email configuration')).toThrow(BadRequestException);
190
+ });
191
+ it('should include the entity name in the thrown exception message', ()=>{
192
+ const user = buildMockUser({
193
+ companyId: 'company-1'
194
+ });
195
+ try {
196
+ validateCompanyOwnership({
197
+ companyId: 'company-2'
198
+ }, user, true, 'Email configuration');
199
+ fail('expected to throw');
200
+ } catch (error) {
201
+ expect(error.getResponse().message).toContain('Email configuration');
202
+ }
203
+ });
204
+ });
205
+ });
@@ -0,0 +1,245 @@
1
+ const isProductionMock = jest.fn();
2
+ const getOriginsMock = jest.fn();
3
+ jest.mock('@flusys/nestjs-core/config', ()=>({
4
+ envConfig: {
5
+ isProduction: ()=>isProductionMock(),
6
+ getOrigins: ()=>getOriginsMock()
7
+ }
8
+ }));
9
+ import { buildCookieOptions, buildFrontendUrl, extractFrontendUrl, isBrowserRequest, parseDurationToMs } from './request.util';
10
+ function buildRequest(overrides = {}) {
11
+ return {
12
+ headers: {},
13
+ hostname: 'app.example.com',
14
+ secure: false,
15
+ get: jest.fn((name)=>overrides.headers?.[name.toLowerCase()]),
16
+ ...overrides
17
+ };
18
+ }
19
+ describe('request.util', ()=>{
20
+ beforeEach(()=>{
21
+ isProductionMock.mockReset().mockReturnValue(false);
22
+ getOriginsMock.mockReset().mockReturnValue([]);
23
+ });
24
+ describe('isBrowserRequest', ()=>{
25
+ it('should return true when x-client-type header is "browser"', ()=>{
26
+ const req = buildRequest({
27
+ headers: {
28
+ 'x-client-type': 'browser'
29
+ }
30
+ });
31
+ expect(isBrowserRequest(req)).toBe(true);
32
+ });
33
+ it('should return true when x-client-type header is "web"', ()=>{
34
+ const req = buildRequest({
35
+ headers: {
36
+ 'x-client-type': 'WEB'
37
+ }
38
+ });
39
+ expect(isBrowserRequest(req)).toBe(true);
40
+ });
41
+ it('should return false when x-client-type header is a non-browser value', ()=>{
42
+ const req = buildRequest({
43
+ headers: {
44
+ 'x-client-type': 'mobile'
45
+ }
46
+ });
47
+ expect(isBrowserRequest(req)).toBe(false);
48
+ });
49
+ it('should return true when accept header includes text/html', ()=>{
50
+ const req = buildRequest({
51
+ headers: {
52
+ accept: 'text/html,application/xhtml+xml'
53
+ }
54
+ });
55
+ expect(isBrowserRequest(req)).toBe(true);
56
+ });
57
+ it('should return true for a recognized browser user-agent', ()=>{
58
+ const req = buildRequest({
59
+ headers: {
60
+ 'user-agent': 'Mozilla/5.0 Chrome/100.0 Safari/537.36'
61
+ }
62
+ });
63
+ expect(isBrowserRequest(req)).toBe(true);
64
+ });
65
+ it('should return false for Postman user-agent even if it matches browser patterns', ()=>{
66
+ const req = buildRequest({
67
+ headers: {
68
+ 'user-agent': 'PostmanRuntime/7.0 chrome'
69
+ }
70
+ });
71
+ expect(isBrowserRequest(req)).toBe(false);
72
+ });
73
+ it('should return false when no headers indicate a browser', ()=>{
74
+ const req = buildRequest({
75
+ headers: {
76
+ 'user-agent': 'curl/7.79.1'
77
+ }
78
+ });
79
+ expect(isBrowserRequest(req)).toBe(false);
80
+ });
81
+ });
82
+ describe('buildCookieOptions', ()=>{
83
+ it('should mark cookies secure and sameSite strict in production', ()=>{
84
+ isProductionMock.mockReturnValue(true);
85
+ const req = buildRequest({
86
+ headers: {}
87
+ });
88
+ const options = buildCookieOptions(req);
89
+ expect(options.secure).toBe(true);
90
+ expect(options.sameSite).toBe('strict');
91
+ });
92
+ it('should mark cookies insecure and sameSite lax in dev with no forwarded proto', ()=>{
93
+ isProductionMock.mockReturnValue(false);
94
+ const req = buildRequest({
95
+ headers: {}
96
+ });
97
+ const options = buildCookieOptions(req);
98
+ expect(options.secure).toBe(false);
99
+ expect(options.sameSite).toBe('lax');
100
+ });
101
+ it('should treat x-forwarded-proto: https as secure', ()=>{
102
+ isProductionMock.mockReturnValue(false);
103
+ const req = buildRequest({
104
+ headers: {
105
+ 'x-forwarded-proto': 'https'
106
+ }
107
+ });
108
+ const options = buildCookieOptions(req);
109
+ expect(options.secure).toBe(true);
110
+ expect(options.sameSite).toBe('strict');
111
+ });
112
+ it('should treat an https origin header as secure', ()=>{
113
+ isProductionMock.mockReturnValue(false);
114
+ const req = buildRequest({
115
+ headers: {
116
+ origin: 'https://app.example.com'
117
+ }
118
+ });
119
+ const options = buildCookieOptions(req);
120
+ expect(options.secure).toBe(true);
121
+ });
122
+ it('should treat req.secure as secure', ()=>{
123
+ isProductionMock.mockReturnValue(false);
124
+ const req = buildRequest({
125
+ headers: {},
126
+ secure: true
127
+ });
128
+ const options = buildCookieOptions(req);
129
+ expect(options.secure).toBe(true);
130
+ });
131
+ it('should not set a domain for a localhost hostname', ()=>{
132
+ isProductionMock.mockReturnValue(false);
133
+ const req = buildRequest({
134
+ headers: {},
135
+ hostname: 'localhost'
136
+ });
137
+ const options = buildCookieOptions(req);
138
+ expect(options.domain).toBeUndefined();
139
+ });
140
+ it('should not set a domain for a bare two-part hostname', ()=>{
141
+ isProductionMock.mockReturnValue(false);
142
+ const req = buildRequest({
143
+ headers: {},
144
+ hostname: 'example.com'
145
+ });
146
+ const options = buildCookieOptions(req);
147
+ expect(options.domain).toBeUndefined();
148
+ });
149
+ it('should set a leading-dot domain for a subdomain hostname', ()=>{
150
+ isProductionMock.mockReturnValue(false);
151
+ const req = buildRequest({
152
+ headers: {},
153
+ hostname: 'app.example.com'
154
+ });
155
+ const options = buildCookieOptions(req);
156
+ expect(options.domain).toBe('.example.com');
157
+ });
158
+ });
159
+ describe('parseDurationToMs', ()=>{
160
+ it('should parse seconds', ()=>{
161
+ expect(parseDurationToMs('30s')).toBe(30 * 1000);
162
+ });
163
+ it('should parse minutes', ()=>{
164
+ expect(parseDurationToMs('15m')).toBe(15 * 60 * 1000);
165
+ });
166
+ it('should parse hours', ()=>{
167
+ expect(parseDurationToMs('2h')).toBe(2 * 60 * 60 * 1000);
168
+ });
169
+ it('should parse days', ()=>{
170
+ expect(parseDurationToMs('7d')).toBe(7 * 24 * 60 * 60 * 1000);
171
+ });
172
+ it('should parse weeks', ()=>{
173
+ expect(parseDurationToMs('2w')).toBe(2 * 7 * 24 * 60 * 60 * 1000);
174
+ });
175
+ it('should return the default when the string does not match the pattern', ()=>{
176
+ expect(parseDurationToMs('garbage')).toBe(7 * 24 * 60 * 60 * 1000);
177
+ });
178
+ it('should return a custom default when provided and pattern does not match', ()=>{
179
+ expect(parseDurationToMs('garbage', 12345)).toBe(12345);
180
+ });
181
+ });
182
+ describe('extractFrontendUrl', ()=>{
183
+ it('should return the matched allowed origin when the request origin starts with it', ()=>{
184
+ getOriginsMock.mockReturnValue([
185
+ 'https://app.example.com'
186
+ ]);
187
+ const req = buildRequest({
188
+ headers: {
189
+ origin: 'https://app.example.com'
190
+ },
191
+ get: jest.fn((name)=>{
192
+ if (name === 'origin') return 'https://app.example.com';
193
+ return undefined;
194
+ })
195
+ });
196
+ expect(extractFrontendUrl(req)).toBe('https://app.example.com');
197
+ });
198
+ it('should fall back to referer when origin header is absent', ()=>{
199
+ getOriginsMock.mockReturnValue([
200
+ 'https://app.example.com'
201
+ ]);
202
+ const req = buildRequest({
203
+ get: jest.fn((name)=>{
204
+ if (name === 'referer') return 'https://app.example.com/some/path';
205
+ return undefined;
206
+ })
207
+ });
208
+ expect(extractFrontendUrl(req)).toBe('https://app.example.com');
209
+ });
210
+ it('should fall back to protocol + host when no origin matches an allowed origin', ()=>{
211
+ getOriginsMock.mockReturnValue([
212
+ 'https://other.example.com'
213
+ ]);
214
+ const req = buildRequest({
215
+ get: jest.fn((name)=>{
216
+ if (name === 'host') return 'app.example.com';
217
+ return undefined;
218
+ }),
219
+ protocol: 'https'
220
+ });
221
+ expect(extractFrontendUrl(req)).toBe('https://app.example.com');
222
+ });
223
+ it('should throw when no origin/referer matches and no host header is present', ()=>{
224
+ getOriginsMock.mockReturnValue([]);
225
+ const req = buildRequest({
226
+ get: jest.fn(()=>undefined)
227
+ });
228
+ expect(()=>extractFrontendUrl(req)).toThrow('Unable to determine frontend URL from request');
229
+ });
230
+ });
231
+ describe('buildFrontendUrl', ()=>{
232
+ it('should append the path to the resolved frontend base URL', ()=>{
233
+ getOriginsMock.mockReturnValue([
234
+ 'https://app.example.com'
235
+ ]);
236
+ const req = buildRequest({
237
+ get: jest.fn((name)=>{
238
+ if (name === 'origin') return 'https://app.example.com';
239
+ return undefined;
240
+ })
241
+ });
242
+ expect(buildFrontendUrl(req, '/reset-password?token=abc')).toBe('https://app.example.com/reset-password?token=abc');
243
+ });
244
+ });
245
+ });
@@ -0,0 +1,59 @@
1
+ import { generateSlug, generateUniqueSlug } from './string.util';
2
+ describe('string.util', ()=>{
3
+ describe('generateSlug', ()=>{
4
+ it('should lowercase and hyphenate a plain string', ()=>{
5
+ expect(generateSlug('My Company Name')).toBe('my-company-name');
6
+ });
7
+ it('should strip special characters', ()=>{
8
+ expect(generateSlug('Hello World!')).toBe('hello-world');
9
+ });
10
+ it('should collapse repeated whitespace and hyphens', ()=>{
11
+ expect(generateSlug('Foo Bar--Baz')).toBe('foo-bar-baz');
12
+ });
13
+ it('should trim leading/trailing hyphens produced by punctuation', ()=>{
14
+ expect(generateSlug(' -Hello- ')).toBe('hello');
15
+ });
16
+ it('should truncate to maxLength', ()=>{
17
+ expect(generateSlug('abcdefghij', 5)).toBe('abcde');
18
+ });
19
+ it('should return an empty string for input that is only special characters', ()=>{
20
+ expect(generateSlug('!!!???')).toBe('');
21
+ });
22
+ });
23
+ describe('generateUniqueSlug', ()=>{
24
+ it('should return the base slug when there are no collisions', async ()=>{
25
+ const findMatchingSlugs = jest.fn().mockResolvedValue([]);
26
+ const slug = await generateUniqueSlug('My Company', findMatchingSlugs);
27
+ expect(slug).toBe('my-company');
28
+ expect(findMatchingSlugs).toHaveBeenCalledWith('my-company');
29
+ });
30
+ it('should return the base slug when only suffixed variants exist', async ()=>{
31
+ const findMatchingSlugs = jest.fn().mockResolvedValue([
32
+ 'my-company-1'
33
+ ]);
34
+ const slug = await generateUniqueSlug('My Company', findMatchingSlugs);
35
+ expect(slug).toBe('my-company');
36
+ });
37
+ it('should append the next available numeric suffix on collision', async ()=>{
38
+ const findMatchingSlugs = jest.fn().mockResolvedValue([
39
+ 'my-company',
40
+ 'my-company-1',
41
+ 'my-company-2'
42
+ ]);
43
+ const slug = await generateUniqueSlug('My Company', findMatchingSlugs);
44
+ expect(slug).toBe('my-company-3');
45
+ });
46
+ it('should fall back to a random suffix when all 9999 slots are taken', async ()=>{
47
+ const taken = [
48
+ 'my-company',
49
+ ...Array.from({
50
+ length: 9999
51
+ }, (_, i)=>`my-company-${i + 1}`)
52
+ ];
53
+ const findMatchingSlugs = jest.fn().mockResolvedValue(taken);
54
+ const slug = await generateUniqueSlug('My Company', findMatchingSlugs);
55
+ expect(slug).toMatch(/^my-company-[a-z0-9]+$/);
56
+ expect(taken).not.toContain(slug);
57
+ });
58
+ });
59
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flusys/nestjs-shared",
3
- "version": "6.0.2",
3
+ "version": "6.1.0",
4
4
  "description": "Common shared utilities for Flusys NestJS applications",
5
5
  "main": "cjs/index.js",
6
6
  "module": "fesm/index.js",
@@ -112,6 +112,6 @@
112
112
  "rxjs": "^7.8.0"
113
113
  },
114
114
  "dependencies": {
115
- "@flusys/nestjs-core": "6.0.2"
115
+ "@flusys/nestjs-core": "6.1.0"
116
116
  }
117
117
  }