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