@rebasepro/server-core 0.7.0 → 0.9.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 (300) hide show
  1. package/README.md +2 -2
  2. package/dist/api/ast-schema-editor.d.ts +21 -0
  3. package/dist/api/collections_for_test/callbacks_test_collection.d.ts +2 -0
  4. package/dist/api/errors.d.ts +53 -0
  5. package/dist/api/index.d.ts +7 -0
  6. package/dist/api/logs-routes.d.ts +37 -0
  7. package/dist/api/openapi-generator.d.ts +16 -0
  8. package/dist/api/rest/api-generator.d.ts +68 -0
  9. package/{src/api/rest/index.ts → dist/api/rest/index.d.ts} +0 -1
  10. package/dist/api/rest/query-parser.d.ts +6 -0
  11. package/dist/api/schema-editor-routes.d.ts +3 -0
  12. package/dist/api/types.d.ts +56 -0
  13. package/dist/auth/adapter-middleware.d.ts +43 -0
  14. package/dist/auth/admin-roles-route.d.ts +18 -0
  15. package/dist/auth/admin-user-ops.d.ts +79 -0
  16. package/dist/auth/admin-users-route.d.ts +28 -0
  17. package/dist/auth/api-keys/api-key-middleware.d.ts +39 -0
  18. package/{src/auth/api-keys/api-key-permission-guard.ts → dist/auth/api-keys/api-key-permission-guard.d.ts} +2 -34
  19. package/dist/auth/api-keys/api-key-routes.d.ts +20 -0
  20. package/dist/auth/api-keys/api-key-store.d.ts +35 -0
  21. package/{src/auth/api-keys/api-key-types.ts → dist/auth/api-keys/api-key-types.d.ts} +0 -6
  22. package/{src/auth/api-keys/index.ts → dist/auth/api-keys/index.d.ts} +2 -22
  23. package/dist/auth/apple-oauth.d.ts +30 -0
  24. package/{src/auth/auth-hooks.ts → dist/auth/auth-hooks.d.ts} +15 -73
  25. package/dist/auth/bitbucket-oauth.d.ts +11 -0
  26. package/dist/auth/builtin-auth-adapter.d.ts +55 -0
  27. package/dist/auth/cookie-utils.d.ts +32 -0
  28. package/{src/auth/crypto-utils.ts → dist/auth/crypto-utils.d.ts} +1 -16
  29. package/dist/auth/custom-auth-adapter.d.ts +39 -0
  30. package/dist/auth/discord-oauth.d.ts +14 -0
  31. package/dist/auth/facebook-oauth.d.ts +14 -0
  32. package/dist/auth/github-oauth.d.ts +15 -0
  33. package/dist/auth/gitlab-oauth.d.ts +13 -0
  34. package/dist/auth/google-oauth.d.ts +47 -0
  35. package/{src/auth/index.ts → dist/auth/index.d.ts} +4 -22
  36. package/{src/auth/interfaces.ts → dist/auth/interfaces.d.ts} +20 -89
  37. package/dist/auth/jwt.d.ts +67 -0
  38. package/dist/auth/linkedin-oauth.d.ts +18 -0
  39. package/dist/auth/magic-link-routes.d.ts +32 -0
  40. package/dist/auth/mfa-crypto.d.ts +23 -0
  41. package/dist/auth/mfa-routes.d.ts +7 -0
  42. package/dist/auth/mfa.d.ts +49 -0
  43. package/dist/auth/microsoft-oauth.d.ts +16 -0
  44. package/dist/auth/middleware.d.ts +158 -0
  45. package/dist/auth/password.d.ts +22 -0
  46. package/dist/auth/rate-limiter.d.ts +50 -0
  47. package/dist/auth/reset-password-admin.d.ts +29 -0
  48. package/dist/auth/rls-scope.d.ts +31 -0
  49. package/dist/auth/routes.d.ts +66 -0
  50. package/dist/auth/session-routes.d.ts +29 -0
  51. package/dist/auth/slack-oauth.d.ts +12 -0
  52. package/dist/auth/spotify-oauth.d.ts +12 -0
  53. package/dist/auth/twitter-oauth.d.ts +18 -0
  54. package/dist/collections/BackendCollectionRegistry.d.ts +13 -0
  55. package/dist/collections/loader.d.ts +5 -0
  56. package/dist/cron/cron-loader.d.ts +18 -0
  57. package/dist/cron/cron-routes.d.ts +14 -0
  58. package/dist/cron/cron-scheduler.d.ts +106 -0
  59. package/dist/cron/cron-store.d.ts +32 -0
  60. package/dist/cron/define-cron.d.ts +28 -0
  61. package/{src/cron/index.ts → dist/cron/index.d.ts} +1 -0
  62. package/dist/db/interfaces.d.ts +18 -0
  63. package/dist/dynamic-import-Dvh-K5fl.js +22 -0
  64. package/dist/dynamic-import-Dvh-K5fl.js.map +1 -0
  65. package/dist/email/index.d.ts +6 -0
  66. package/dist/email/smtp-email-service.d.ts +30 -0
  67. package/dist/email/templates.d.ts +50 -0
  68. package/{src/email/types.ts → dist/email/types.d.ts} +40 -36
  69. package/dist/env.d.ts +102 -0
  70. package/dist/functions/define-function.d.ts +55 -0
  71. package/dist/functions/function-loader.d.ts +18 -0
  72. package/dist/functions/function-routes.d.ts +10 -0
  73. package/{src/functions/index.ts → dist/functions/index.d.ts} +2 -0
  74. package/dist/history/history-routes.d.ts +23 -0
  75. package/{src/history/index.ts → dist/history/index.d.ts} +0 -1
  76. package/dist/index.d.ts +35 -0
  77. package/dist/index.es.js +18184 -0
  78. package/dist/index.es.js.map +1 -0
  79. package/dist/index.umd.js +48629 -0
  80. package/dist/index.umd.js.map +1 -0
  81. package/dist/init/docs.d.ts +4 -0
  82. package/dist/init/health.d.ts +2 -0
  83. package/dist/init/middlewares.d.ts +10 -0
  84. package/dist/init/shutdown.d.ts +65 -0
  85. package/dist/init/storage.d.ts +5 -0
  86. package/dist/init.d.ts +344 -0
  87. package/dist/jwt-BwIn8xmk.js +4200 -0
  88. package/dist/jwt-BwIn8xmk.js.map +1 -0
  89. package/dist/logger-BYU66ENZ.js +94 -0
  90. package/dist/logger-BYU66ENZ.js.map +1 -0
  91. package/dist/ms-DnYXB-Wd.js +162 -0
  92. package/dist/ms-DnYXB-Wd.js.map +1 -0
  93. package/dist/openapi-generator-Z9oYWLf_.js +586 -0
  94. package/dist/openapi-generator-Z9oYWLf_.js.map +1 -0
  95. package/dist/schema-editor-routes-D3ef8zu1.js +219 -0
  96. package/dist/schema-editor-routes-D3ef8zu1.js.map +1 -0
  97. package/dist/serve-spa.d.ts +36 -0
  98. package/dist/services/driver-registry.d.ts +78 -0
  99. package/dist/services/routed-realtime-service.d.ts +43 -0
  100. package/dist/services/webhook-service.d.ts +29 -0
  101. package/dist/singleton.d.ts +51 -0
  102. package/dist/src-B4OLmNVa.js +437 -0
  103. package/dist/src-B4OLmNVa.js.map +1 -0
  104. package/dist/src-B5WkP1Rv.js +24778 -0
  105. package/dist/src-B5WkP1Rv.js.map +1 -0
  106. package/dist/storage/GCSStorageController.d.ts +43 -0
  107. package/dist/storage/LocalStorageController.d.ts +46 -0
  108. package/dist/storage/S3StorageController.d.ts +40 -0
  109. package/dist/storage/image-transform.d.ts +50 -0
  110. package/{src/storage/index.ts → dist/storage/index.d.ts} +6 -21
  111. package/dist/storage/routes.d.ts +70 -0
  112. package/dist/storage/storage-registry.d.ts +78 -0
  113. package/dist/storage/tus-handler.d.ts +53 -0
  114. package/{src/storage/types.ts → dist/storage/types.d.ts} +32 -38
  115. package/dist/types/index.d.ts +11 -0
  116. package/dist/utils/dev-port.d.ts +45 -0
  117. package/dist/utils/dynamic-import.d.ts +25 -0
  118. package/dist/utils/logger.d.ts +31 -0
  119. package/dist/utils/logging.d.ts +9 -0
  120. package/dist/utils/request-id.d.ts +4 -0
  121. package/dist/utils/request-logger.d.ts +19 -0
  122. package/{src/utils/sql.ts → dist/utils/sql.d.ts} +5 -16
  123. package/package.json +49 -22
  124. package/coverage/clover.xml +0 -3739
  125. package/coverage/coverage-final.json +0 -31
  126. package/coverage/lcov-report/base.css +0 -224
  127. package/coverage/lcov-report/block-navigation.js +0 -87
  128. package/coverage/lcov-report/favicon.png +0 -0
  129. package/coverage/lcov-report/index.html +0 -266
  130. package/coverage/lcov-report/prettify.css +0 -1
  131. package/coverage/lcov-report/prettify.js +0 -2
  132. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  133. package/coverage/lcov-report/sorter.js +0 -210
  134. package/coverage/lcov-report/src/api/ast-schema-editor.ts.html +0 -952
  135. package/coverage/lcov-report/src/api/errors.ts.html +0 -472
  136. package/coverage/lcov-report/src/api/graphql/graphql-schema-generator.ts.html +0 -1069
  137. package/coverage/lcov-report/src/api/graphql/index.html +0 -116
  138. package/coverage/lcov-report/src/api/index.html +0 -176
  139. package/coverage/lcov-report/src/api/openapi-generator.ts.html +0 -565
  140. package/coverage/lcov-report/src/api/rest/api-generator.ts.html +0 -994
  141. package/coverage/lcov-report/src/api/rest/index.html +0 -131
  142. package/coverage/lcov-report/src/api/rest/query-parser.ts.html +0 -550
  143. package/coverage/lcov-report/src/api/schema-editor-routes.ts.html +0 -202
  144. package/coverage/lcov-report/src/api/server.ts.html +0 -823
  145. package/coverage/lcov-report/src/auth/admin-routes.ts.html +0 -973
  146. package/coverage/lcov-report/src/auth/index.html +0 -176
  147. package/coverage/lcov-report/src/auth/jwt.ts.html +0 -574
  148. package/coverage/lcov-report/src/auth/middleware.ts.html +0 -745
  149. package/coverage/lcov-report/src/auth/password.ts.html +0 -310
  150. package/coverage/lcov-report/src/auth/services.ts.html +0 -2074
  151. package/coverage/lcov-report/src/collections/index.html +0 -116
  152. package/coverage/lcov-report/src/collections/loader.ts.html +0 -232
  153. package/coverage/lcov-report/src/db/auth-schema.ts.html +0 -523
  154. package/coverage/lcov-report/src/db/data-transformer.ts.html +0 -1753
  155. package/coverage/lcov-report/src/db/entityService.ts.html +0 -700
  156. package/coverage/lcov-report/src/db/index.html +0 -146
  157. package/coverage/lcov-report/src/db/services/EntityFetchService.ts.html +0 -4048
  158. package/coverage/lcov-report/src/db/services/EntityPersistService.ts.html +0 -883
  159. package/coverage/lcov-report/src/db/services/RelationService.ts.html +0 -3121
  160. package/coverage/lcov-report/src/db/services/entity-helpers.ts.html +0 -442
  161. package/coverage/lcov-report/src/db/services/index.html +0 -176
  162. package/coverage/lcov-report/src/db/services/index.ts.html +0 -124
  163. package/coverage/lcov-report/src/generate-drizzle-schema-logic.ts.html +0 -1960
  164. package/coverage/lcov-report/src/index.html +0 -116
  165. package/coverage/lcov-report/src/services/driver-registry.ts.html +0 -631
  166. package/coverage/lcov-report/src/services/index.html +0 -131
  167. package/coverage/lcov-report/src/services/postgresDataDriver.ts.html +0 -3025
  168. package/coverage/lcov-report/src/storage/LocalStorageController.ts.html +0 -1189
  169. package/coverage/lcov-report/src/storage/S3StorageController.ts.html +0 -970
  170. package/coverage/lcov-report/src/storage/index.html +0 -161
  171. package/coverage/lcov-report/src/storage/storage-registry.ts.html +0 -646
  172. package/coverage/lcov-report/src/storage/types.ts.html +0 -451
  173. package/coverage/lcov-report/src/utils/drizzle-conditions.ts.html +0 -3082
  174. package/coverage/lcov-report/src/utils/index.html +0 -116
  175. package/coverage/lcov.info +0 -7179
  176. package/jest.config.cjs +0 -19
  177. package/src/api/ast-schema-editor.ts +0 -289
  178. package/src/api/collections_for_test/callbacks_test_collection.ts +0 -61
  179. package/src/api/errors.ts +0 -278
  180. package/src/api/graphql/graphql-schema-generator.ts +0 -383
  181. package/src/api/graphql/index.ts +0 -2
  182. package/src/api/index.ts +0 -11
  183. package/src/api/logs-routes.ts +0 -132
  184. package/src/api/openapi-generator.ts +0 -727
  185. package/src/api/rest/api-generator-count.test.ts +0 -126
  186. package/src/api/rest/api-generator.ts +0 -747
  187. package/src/api/rest/query-parser.ts +0 -300
  188. package/src/api/schema-editor-routes.ts +0 -41
  189. package/src/api/server.ts +0 -271
  190. package/src/api/types.ts +0 -104
  191. package/src/auth/adapter-middleware.ts +0 -114
  192. package/src/auth/admin-roles-route.ts +0 -36
  193. package/src/auth/admin-user-ops.ts +0 -236
  194. package/src/auth/admin-users-route.ts +0 -302
  195. package/src/auth/api-keys/api-key-middleware.ts +0 -133
  196. package/src/auth/api-keys/api-key-routes.ts +0 -193
  197. package/src/auth/api-keys/api-key-store.ts +0 -340
  198. package/src/auth/apple-oauth.ts +0 -122
  199. package/src/auth/bitbucket-oauth.ts +0 -84
  200. package/src/auth/builtin-auth-adapter.ts +0 -380
  201. package/src/auth/custom-auth-adapter.ts +0 -86
  202. package/src/auth/discord-oauth.ts +0 -85
  203. package/src/auth/facebook-oauth.ts +0 -74
  204. package/src/auth/github-oauth.ts +0 -112
  205. package/src/auth/gitlab-oauth.ts +0 -72
  206. package/src/auth/google-oauth.ts +0 -223
  207. package/src/auth/jwt.ts +0 -208
  208. package/src/auth/linkedin-oauth.ts +0 -83
  209. package/src/auth/magic-link-routes.ts +0 -167
  210. package/src/auth/mfa-crypto.ts +0 -91
  211. package/src/auth/mfa-routes.ts +0 -323
  212. package/src/auth/mfa.ts +0 -161
  213. package/src/auth/microsoft-oauth.ts +0 -90
  214. package/src/auth/middleware.ts +0 -369
  215. package/src/auth/password.ts +0 -77
  216. package/src/auth/rate-limiter.ts +0 -225
  217. package/src/auth/reset-password-admin.ts +0 -160
  218. package/src/auth/rls-scope.ts +0 -58
  219. package/src/auth/routes.ts +0 -802
  220. package/src/auth/session-routes.ts +0 -353
  221. package/src/auth/slack-oauth.ts +0 -73
  222. package/src/auth/spotify-oauth.ts +0 -69
  223. package/src/auth/twitter-oauth.ts +0 -128
  224. package/src/collections/BackendCollectionRegistry.ts +0 -20
  225. package/src/collections/loader.ts +0 -50
  226. package/src/cron/cron-loader.ts +0 -84
  227. package/src/cron/cron-routes.test.ts +0 -265
  228. package/src/cron/cron-routes.ts +0 -85
  229. package/src/cron/cron-scheduler.test.ts +0 -559
  230. package/src/cron/cron-scheduler.ts +0 -581
  231. package/src/cron/cron-store.ts +0 -166
  232. package/src/db/interfaces.ts +0 -60
  233. package/src/email/index.ts +0 -19
  234. package/src/email/smtp-email-service.ts +0 -123
  235. package/src/email/templates.ts +0 -470
  236. package/src/env.ts +0 -227
  237. package/src/functions/function-loader.ts +0 -116
  238. package/src/functions/function-routes.ts +0 -31
  239. package/src/history/history-routes.ts +0 -129
  240. package/src/index.ts +0 -70
  241. package/src/init/docs.ts +0 -47
  242. package/src/init/health.ts +0 -37
  243. package/src/init/middlewares.ts +0 -61
  244. package/src/init/shutdown.ts +0 -56
  245. package/src/init/storage.ts +0 -57
  246. package/src/init.ts +0 -1041
  247. package/src/serve-spa.ts +0 -89
  248. package/src/services/driver-registry.ts +0 -183
  249. package/src/services/routed-realtime-service.ts +0 -113
  250. package/src/services/webhook-service.ts +0 -155
  251. package/src/singleton.ts +0 -70
  252. package/src/storage/LocalStorageController.ts +0 -389
  253. package/src/storage/S3StorageController.ts +0 -300
  254. package/src/storage/image-transform.ts +0 -218
  255. package/src/storage/routes.ts +0 -368
  256. package/src/storage/storage-registry.ts +0 -188
  257. package/src/storage/tus-handler.ts +0 -315
  258. package/src/types/index.ts +0 -27
  259. package/src/utils/dev-port.ts +0 -196
  260. package/src/utils/logger.ts +0 -143
  261. package/src/utils/logging.ts +0 -40
  262. package/src/utils/request-id.ts +0 -40
  263. package/src/utils/request-logger.ts +0 -72
  264. package/test/api-generator.test.ts +0 -588
  265. package/test/api-key-permission-guard.test.ts +0 -144
  266. package/test/ast-schema-editor.test.ts +0 -89
  267. package/test/auth-middleware-hono.test.ts +0 -556
  268. package/test/auth-routes.test.ts +0 -1098
  269. package/test/backend-hooks-data.test.ts +0 -477
  270. package/test/custom-auth-adapter.test.ts +0 -189
  271. package/test/driver-registry.test.ts +0 -282
  272. package/test/email-templates.test.ts +0 -174
  273. package/test/env.test.ts +0 -128
  274. package/test/error-propagation.test.ts +0 -226
  275. package/test/errors-hono.test.ts +0 -133
  276. package/test/errors.test.ts +0 -155
  277. package/test/function-loader.test.ts +0 -127
  278. package/test/graphql-schema-generator.test.ts +0 -554
  279. package/test/jwt-security.test.ts +0 -182
  280. package/test/jwt.test.ts +0 -326
  281. package/test/mfa.test.ts +0 -197
  282. package/test/middleware.test.ts +0 -305
  283. package/test/multi-datasource-routing.test.ts +0 -113
  284. package/test/password.test.ts +0 -165
  285. package/test/query-parser.test.ts +0 -233
  286. package/test/rate-limiter.test.ts +0 -102
  287. package/test/reset-password-admin.test.ts +0 -113
  288. package/test/routed-realtime-service.test.ts +0 -86
  289. package/test/safe-compare.test.ts +0 -66
  290. package/test/singleton.test.ts +0 -59
  291. package/test/smtp-email-service.test.ts +0 -169
  292. package/test/storage-local.test.ts +0 -271
  293. package/test/storage-registry.test.ts +0 -282
  294. package/test/storage-routes.test.ts +0 -222
  295. package/test/storage-s3.test.ts +0 -304
  296. package/test/transform-auth-response.test.ts +0 -305
  297. package/test/webhook-service.test.ts +0 -260
  298. package/tsconfig.json +0 -54
  299. package/tsconfig.prod.json +0 -23
  300. package/vite.config.ts +0 -86
@@ -1,304 +0,0 @@
1
- import { describe, it, expect, beforeEach, afterEach, jest as vi } from "@jest/globals";
2
- import { S3StorageController } from "../src/storage/S3StorageController";
3
-
4
- // Mock the AWS SDK before importing the controller
5
- vi.mock("@aws-sdk/client-s3", () => ({
6
- S3Client: vi.fn().mockImplementation(function() {
7
- return { send: vi.fn() };
8
- }),
9
- PutObjectCommand: vi.fn(),
10
- GetObjectCommand: vi.fn(),
11
- DeleteObjectCommand: vi.fn(),
12
- ListObjectsV2Command: vi.fn(),
13
- HeadObjectCommand: vi.fn()
14
- }));
15
-
16
- vi.mock("@aws-sdk/s3-request-presigner", () => ({
17
- getSignedUrl: vi.fn().mockResolvedValue("https://presigned-url.example.com")
18
- }));
19
-
20
- import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand, ListObjectsV2Command } from "@aws-sdk/client-s3";
21
- import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
22
-
23
- describe("S3StorageController", () => {
24
- let controller: S3StorageController;
25
- let mockSend: vi.Mock;
26
-
27
- const defaultConfig = {
28
- bucket: "test-bucket",
29
- region: "us-east-1",
30
- accessKeyId: "test-access-key",
31
- secretAccessKey: "test-secret-key"
32
- };
33
-
34
- beforeEach(() => {
35
- vi.clearAllMocks();
36
- mockSend = vi.fn();
37
- vi.mocked(S3Client).mockImplementation(function() {
38
- return { send: mockSend };
39
- } as any);
40
- controller = new S3StorageController(defaultConfig);
41
- });
42
-
43
- describe("constructor", () => {
44
- it("should initialize S3 client with credentials", () => {
45
- expect(S3Client).toHaveBeenCalledWith(expect.objectContaining({
46
- region: "us-east-1",
47
- credentials: {
48
- accessKeyId: "test-access-key",
49
- secretAccessKey: "test-secret-key"
50
- }
51
- }));
52
- });
53
-
54
- it("should initialize with endpoint for S3-compatible services", () => {
55
- vi.clearAllMocks();
56
- new S3StorageController({
57
- ...defaultConfig,
58
- endpoint: "https://minio.example.com",
59
- forcePathStyle: true
60
- });
61
-
62
- expect(S3Client).toHaveBeenCalledWith(expect.objectContaining({
63
- endpoint: "https://minio.example.com",
64
- forcePathStyle: true
65
- }));
66
- });
67
-
68
- it("should return 's3' as type", () => {
69
- expect(controller.getType()).toBe("s3");
70
- });
71
- });
72
-
73
- describe("putObject", () => {
74
- it("should upload file using PutObjectCommand", async () => {
75
- const content = Buffer.from("Test content");
76
- const file = new File([content], "test.txt", { type: "text/plain" });
77
-
78
- mockSend.mockResolvedValueOnce({});
79
-
80
- const result = await controller.putObject({
81
- file,
82
- key: "uploads/test.txt"
83
- });
84
-
85
- expect(PutObjectCommand).toHaveBeenCalledWith(expect.objectContaining({
86
- Bucket: "test-bucket",
87
- Key: "uploads/test.txt",
88
- ContentType: "text/plain"
89
- }));
90
- expect(mockSend).toHaveBeenCalled();
91
- expect(result.key).toBe("uploads/test.txt");
92
- });
93
-
94
- it("should include metadata in upload", async () => {
95
- const file = new File(["content"], "test.txt", { type: "text/plain" });
96
-
97
- mockSend.mockResolvedValueOnce({});
98
-
99
- await controller.putObject({
100
- file,
101
- key: "uploads/test.txt",
102
- metadata: { customKey: "customValue" }
103
- });
104
-
105
- expect(PutObjectCommand).toHaveBeenCalledWith(expect.objectContaining({
106
- Metadata: expect.objectContaining({
107
- customKey: "customValue" // Keys are passed as-is, S3 handles casing
108
- })
109
- }));
110
- });
111
-
112
- it("should use custom bucket when specified", async () => {
113
- const file = new File(["content"], "test.txt", { type: "text/plain" });
114
-
115
- mockSend.mockResolvedValueOnce({});
116
-
117
- await controller.putObject({
118
- file,
119
- key: "uploads/test.txt",
120
- bucket: "custom-bucket"
121
- });
122
-
123
- expect(PutObjectCommand).toHaveBeenCalledWith(expect.objectContaining({
124
- Bucket: "custom-bucket"
125
- }));
126
- });
127
- });
128
-
129
- describe("getSignedUrl", () => {
130
- it("should generate presigned URL", async () => {
131
- mockSend.mockResolvedValueOnce({
132
- ContentType: "text/plain",
133
- ContentLength: 100,
134
- LastModified: new Date(),
135
- Metadata: {}
136
- });
137
-
138
- const result = await controller.getSignedUrl("uploads/test.txt");
139
-
140
- expect(getSignedUrl).toHaveBeenCalled();
141
- expect(result.url).toBe("https://presigned-url.example.com");
142
- });
143
-
144
- it("should include metadata in download config", async () => {
145
- const lastModified = new Date("2024-01-15T10:00:00Z");
146
- mockSend.mockResolvedValueOnce({
147
- ContentType: "image/png",
148
- ContentLength: 5000,
149
- LastModified: lastModified,
150
- Metadata: { originalName: "photo.png" }
151
- });
152
-
153
- const result = await controller.getSignedUrl("images/photo.png");
154
-
155
- expect(result.metadata).toBeDefined();
156
- expect(result.metadata?.contentType).toBe("image/png");
157
- });
158
- });
159
-
160
- describe("getObject", () => {
161
- it("should return null for non-existent file", async () => {
162
- const error = new Error("NoSuchKey");
163
- (error as any).name = "NoSuchKey";
164
- mockSend.mockRejectedValueOnce(error);
165
-
166
- const result = await controller.getObject("nonexistent.txt");
167
-
168
- expect(result).toBeNull();
169
- });
170
- });
171
-
172
- describe("deleteObject", () => {
173
- it("should delete file from S3", async () => {
174
- mockSend.mockResolvedValueOnce({});
175
-
176
- await controller.deleteObject("uploads/test.txt");
177
-
178
- expect(DeleteObjectCommand).toHaveBeenCalledWith(expect.objectContaining({
179
- Bucket: "test-bucket",
180
- Key: "uploads/test.txt"
181
- }));
182
- });
183
-
184
- it("should not throw for non-existent file", async () => {
185
- mockSend.mockResolvedValueOnce({});
186
-
187
- await expect(controller.deleteObject("nonexistent.txt")).resolves.not.toThrow();
188
- });
189
- });
190
-
191
- describe("list", () => {
192
- it("should list objects in S3 bucket", async () => {
193
- mockSend.mockResolvedValueOnce({
194
- Contents: [
195
- { Key: "uploads/file1.txt",
196
- Size: 100,
197
- LastModified: new Date() },
198
- { Key: "uploads/file2.txt",
199
- Size: 200,
200
- LastModified: new Date() }
201
- ],
202
- CommonPrefixes: [],
203
- IsTruncated: false
204
- });
205
-
206
- const result = await controller.listObjects("uploads");
207
-
208
- expect(ListObjectsV2Command).toHaveBeenCalledWith(expect.objectContaining({
209
- Bucket: "test-bucket",
210
- Prefix: "uploads" // Implementation doesn't add trailing slash
211
- }));
212
- expect(result.items).toHaveLength(2);
213
- });
214
-
215
- it("should handle pagination with maxResults", async () => {
216
- mockSend.mockResolvedValueOnce({
217
- Contents: [
218
- { Key: "uploads/file1.txt",
219
- Size: 100,
220
- LastModified: new Date() }
221
- ],
222
- CommonPrefixes: [],
223
- IsTruncated: true,
224
- NextContinuationToken: "token123"
225
- });
226
-
227
- const result = await controller.listObjects("uploads", { maxResults: 1 });
228
-
229
- expect(ListObjectsV2Command).toHaveBeenCalledWith(expect.objectContaining({
230
- MaxKeys: 1
231
- }));
232
- expect(result.nextPageToken).toBe("token123");
233
- });
234
-
235
- it("should include common prefixes as subdirectories", async () => {
236
- mockSend.mockResolvedValueOnce({
237
- Contents: [],
238
- CommonPrefixes: [
239
- { Prefix: "uploads/images/" },
240
- { Prefix: "uploads/documents/" }
241
- ],
242
- IsTruncated: false
243
- });
244
-
245
- const result = await controller.listObjects("uploads");
246
-
247
- expect(result.prefixes).toHaveLength(2);
248
- });
249
-
250
- it("should use pageToken for continuation", async () => {
251
- mockSend.mockResolvedValueOnce({
252
- Contents: [],
253
- CommonPrefixes: [],
254
- IsTruncated: false
255
- });
256
-
257
- await controller.listObjects("uploads", { pageToken: "continue-token" });
258
-
259
- expect(ListObjectsV2Command).toHaveBeenCalledWith(expect.objectContaining({
260
- ContinuationToken: "continue-token"
261
- }));
262
- });
263
- });
264
-
265
- describe("validateFile", () => {
266
- it("should accept valid file", () => {
267
- const file = new File(["content"], "valid.txt", { type: "text/plain" });
268
-
269
- expect(() => {
270
- (controller as any).validateFile(file);
271
- }).not.toThrow();
272
- });
273
-
274
- it("should reject file exceeding max size", () => {
275
- const smallController = new S3StorageController({
276
- ...defaultConfig,
277
- maxFileSize: 10 // 10 bytes
278
- });
279
-
280
- const largeContent = Buffer.alloc(100);
281
- const file = new File([largeContent], "large.txt", { type: "text/plain" });
282
-
283
- expect(() => {
284
- (smallController as any).validateFile(file);
285
- }).toThrow(/exceeds/i);
286
- });
287
- });
288
-
289
- describe("flattenMetadata", () => {
290
- it("should flatten nested metadata to strings", () => {
291
- const metadata = {
292
- simple: "value",
293
- number: 42,
294
- nested: { key: "value" }
295
- };
296
-
297
- const flattened = (controller as any).flattenMetadata(metadata);
298
-
299
- expect(flattened.simple).toBe("value");
300
- expect(flattened.number).toBe("42");
301
- expect(typeof flattened.nested).toBe("string");
302
- });
303
- });
304
- });
@@ -1,305 +0,0 @@
1
- /**
2
- * transformAuthResponse Hook — Integration Tests
3
- *
4
- * Tests the `transformAuthResponse` hook across login, register, refresh,
5
- * and error handling scenarios. Services are mocked following the same
6
- * pattern as auth-routes.test.ts.
7
- */
8
-
9
- import { Hono } from "hono";
10
- import type { HonoEnv } from "../src/api/types";
11
- import { errorHandler } from "../src/api/errors";
12
- import { createAuthRoutes, AuthModuleConfig } from "../src/auth/routes";
13
- import type { AuthRepository } from "../src/auth/interfaces";
14
- import { configureJwt, hashRefreshToken } from "../src/auth/jwt";
15
- import type { AuthHooks } from "../src/auth/auth-hooks";
16
- import type { AuthResponsePayload, TransformAuthResponseContext } from "@rebasepro/types";
17
-
18
- // ── Mocks ───────────────────────────────────────────────────────────────────
19
-
20
- jest.mock("../src/auth/password");
21
-
22
- jest.mock("../src/utils/logger", () => {
23
- return {
24
- logger: {
25
- info: jest.fn(),
26
- warn: jest.fn(),
27
- error: jest.fn(),
28
- debug: jest.fn(),
29
- child: jest.fn().mockReturnThis()
30
- }
31
- };
32
- });
33
-
34
- // Bypass rate limiters — they share state across tests and cause 429s
35
- jest.mock("../src/auth/rate-limiter", () => {
36
- const passthrough = async (_c: unknown, next: () => Promise<void>) => next();
37
- return {
38
- createRateLimiter: () => passthrough,
39
- defaultAuthLimiter: passthrough,
40
- strictAuthLimiter: passthrough
41
- };
42
- });
43
-
44
- import { validatePasswordStrength, hashPassword, verifyPassword } from "../src/auth/password";
45
- import { logger } from "../src/utils/logger";
46
-
47
- // ── Helpers ─────────────────────────────────────────────────────────────────
48
-
49
- const TEST_SECRET = "integration-test-secret-key-that-is-definitely-32-chars-long!!";
50
-
51
- function mockUser(overrides: Partial<{ id: string; email: string; passwordHash: string | null; displayName: string | null; photoUrl: string | null; provider: string; emailVerified: boolean; emailVerificationToken: string | null }> = {}) {
52
- return {
53
- id: overrides.id ?? "user-1",
54
- email: overrides.email ?? "test@example.com",
55
- passwordHash: "passwordHash" in overrides ? overrides.passwordHash : "salt:hash",
56
- displayName: overrides.displayName ?? "Test User",
57
- photoUrl: overrides.photoUrl ?? null,
58
- emailVerified: overrides.emailVerified ?? false,
59
- emailVerificationToken: overrides.emailVerificationToken ?? null,
60
- emailVerificationSentAt: null,
61
- createdAt: new Date(),
62
- updatedAt: new Date()
63
- };
64
- }
65
-
66
- function mockRole(id: string, isAdmin = false) {
67
- return { id,
68
- name: id.charAt(0).toUpperCase() + id.slice(1),
69
- isAdmin,
70
- defaultPermissions: null,
71
- collectionPermissions: null };
72
- }
73
-
74
- let mockAuthRepo: jest.Mocked<AuthRepository>;
75
-
76
- function createApp(opts: { authHooks?: AuthHooks } = {}) {
77
- mockAuthRepo = {
78
- getUserByEmail: jest.fn().mockResolvedValue(null),
79
- getUserByIdentity: jest.fn().mockResolvedValue(null),
80
- linkUserIdentity: jest.fn().mockResolvedValue(undefined),
81
- getUserIdentities: jest.fn().mockResolvedValue([]),
82
- getUserById: jest.fn().mockResolvedValue(null),
83
- createUser: jest.fn().mockImplementation((data) =>
84
- Promise.resolve(mockUser({ email: data.email,
85
- displayName: data.displayName,
86
- passwordHash: data.passwordHash }))
87
- ),
88
- listUsers: jest.fn().mockResolvedValue([]),
89
- getUserRoles: jest.fn().mockResolvedValue([mockRole("editor")]),
90
- getUserRoleIds: jest.fn().mockResolvedValue(["editor"]),
91
- assignDefaultRole: jest.fn().mockResolvedValue(undefined),
92
- setUserRoles: jest.fn().mockResolvedValue(undefined),
93
- updateUser: jest.fn().mockImplementation((id, data) =>
94
- Promise.resolve(mockUser({ id,
95
- ...data }))
96
- ),
97
- deleteUser: jest.fn().mockResolvedValue(undefined),
98
- updatePassword: jest.fn().mockResolvedValue(undefined),
99
- setEmailVerified: jest.fn().mockResolvedValue(undefined),
100
- setVerificationToken: jest.fn().mockResolvedValue(undefined),
101
- getUserByVerificationToken: jest.fn().mockResolvedValue(null),
102
- getUserWithRoles: jest.fn().mockImplementation(async (userId) => {
103
- const user = mockUser({ id: userId });
104
- return { user,
105
- roles: [mockRole("editor")] };
106
- }),
107
- createRefreshToken: jest.fn().mockResolvedValue(undefined),
108
- findRefreshTokenByHash: jest.fn().mockResolvedValue(null),
109
- deleteRefreshToken: jest.fn().mockResolvedValue(undefined),
110
- deleteAllRefreshTokensForUser: jest.fn().mockResolvedValue(undefined),
111
- listRefreshTokensForUser: jest.fn().mockResolvedValue([]),
112
- deleteRefreshTokenById: jest.fn().mockResolvedValue(undefined),
113
- createPasswordResetToken: jest.fn().mockResolvedValue(undefined),
114
- findValidPasswordResetToken: jest.fn().mockResolvedValue(null),
115
- markPasswordResetTokenUsed: jest.fn().mockResolvedValue(undefined),
116
- deleteExpiredPasswordResetTokens: jest.fn().mockResolvedValue(undefined)
117
- } as unknown as jest.Mocked<AuthRepository>;
118
-
119
- // Password mocks
120
- (validatePasswordStrength as jest.Mock).mockReturnValue({ valid: true,
121
- errors: [] });
122
- (hashPassword as jest.Mock).mockResolvedValue("hashed-pw");
123
- (verifyPassword as jest.Mock).mockResolvedValue(true);
124
-
125
- const config: AuthModuleConfig = {
126
- authRepo: mockAuthRepo,
127
- allowRegistration: true,
128
- authHooks: opts.authHooks
129
- };
130
-
131
- const app = new Hono<HonoEnv>();
132
- app.onError(errorHandler);
133
- app.route("/auth", createAuthRoutes(config));
134
- return app;
135
- }
136
-
137
- function json(body: Record<string, unknown>) {
138
- return {
139
- method: "POST" as const,
140
- headers: { "Content-Type": "application/json" },
141
- body: JSON.stringify(body)
142
- };
143
- }
144
-
145
- // ═══════════════════════════════════════════════════════════════════════════
146
- // TESTS
147
- // ═══════════════════════════════════════════════════════════════════════════
148
-
149
- describe("transformAuthResponse hook", () => {
150
- beforeAll(() => {
151
- configureJwt({ secret: TEST_SECRET,
152
- accessExpiresIn: "1h" });
153
- });
154
-
155
- beforeEach(() => {
156
- jest.clearAllMocks();
157
- });
158
-
159
- // ── Registration ────────────────────────────────────────────────────
160
-
161
- describe("POST /auth/register", () => {
162
- it("calls transformAuthResponse with the response and 'register' method", async () => {
163
- const transformHook = jest.fn(async (response: AuthResponsePayload) => ({
164
- ...response,
165
- tokens: { ...response.tokens, firebaseToken: "custom-firebase-token" }
166
- }));
167
- const app = createApp({ authHooks: { transformAuthResponse: transformHook } });
168
-
169
- const res = await app.request("/auth/register", json({ email: "new@test.com", password: "StrongPass1" }));
170
- expect(res.status).toBe(201);
171
- const body = await res.json() as Record<string, unknown>;
172
- const tokens = body.tokens as Record<string, unknown>;
173
-
174
- // Verify the hook was called
175
- expect(transformHook).toHaveBeenCalledTimes(1);
176
-
177
- // Verify context
178
- const context = transformHook.mock.calls[0][1] as TransformAuthResponseContext;
179
- expect(context.method).toBe("register");
180
- expect(context.userId).toBeTruthy();
181
- expect(context.request).toBeInstanceOf(Request);
182
-
183
- // Verify the custom field was injected
184
- expect(tokens.firebaseToken).toBe("custom-firebase-token");
185
- // Original fields still present
186
- expect(tokens.accessToken).toBeTruthy();
187
- expect(tokens.refreshToken).toBeTruthy();
188
- });
189
- });
190
-
191
- // ── Login ────────────────────────────────────────────────────────────
192
-
193
- describe("POST /auth/login", () => {
194
- it("calls transformAuthResponse with 'login' method", async () => {
195
- const transformHook = jest.fn(async (response: AuthResponsePayload) => ({
196
- ...response,
197
- tokens: { ...response.tokens, externalToken: "ext-123" }
198
- }));
199
- const app = createApp({ authHooks: { transformAuthResponse: transformHook } });
200
-
201
- // Setup: user exists
202
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(mockUser());
203
-
204
- const res = await app.request("/auth/login", json({ email: "test@example.com", password: "StrongPass1" }));
205
- expect(res.status).toBe(200);
206
- const body = await res.json() as Record<string, unknown>;
207
- const tokens = body.tokens as Record<string, unknown>;
208
-
209
- expect(transformHook).toHaveBeenCalledTimes(1);
210
- const context = transformHook.mock.calls[0][1] as TransformAuthResponseContext;
211
- expect(context.method).toBe("login");
212
- expect(tokens.externalToken).toBe("ext-123");
213
- });
214
- });
215
-
216
- // ── Refresh ──────────────────────────────────────────────────────────
217
-
218
- describe("POST /auth/refresh", () => {
219
- it("calls transformAuthResponse with 'refresh' method (tokens-only response)", async () => {
220
- const transformHook = jest.fn(async (response: AuthResponsePayload) => ({
221
- ...response,
222
- tokens: { ...response.tokens, refreshedExternalToken: "refreshed-ext" }
223
- }));
224
- const app = createApp({ authHooks: { transformAuthResponse: transformHook } });
225
-
226
- // Setup: valid refresh token exists
227
- const rawRefreshToken = "a".repeat(80);
228
- const hashedToken = hashRefreshToken(rawRefreshToken);
229
- mockAuthRepo.findRefreshTokenByHash.mockResolvedValueOnce({
230
- id: "rt-1",
231
- userId: "user-1",
232
- tokenHash: hashedToken,
233
- expiresAt: new Date(Date.now() + 86400000), // 1 day from now
234
- createdAt: new Date(),
235
- userAgent: "test",
236
- ipAddress: "127.0.0.1"
237
- });
238
- mockAuthRepo.getUserRoleIds.mockResolvedValueOnce(["editor"]);
239
-
240
- const res = await app.request("/auth/refresh", json({ refreshToken: rawRefreshToken }));
241
- expect(res.status).toBe(200);
242
- const body = await res.json() as Record<string, unknown>;
243
- const tokens = body.tokens as Record<string, unknown>;
244
-
245
- expect(transformHook).toHaveBeenCalledTimes(1);
246
-
247
- // Verify refresh context
248
- const hookResponse = transformHook.mock.calls[0][0] as AuthResponsePayload;
249
- const context = transformHook.mock.calls[0][1] as TransformAuthResponseContext;
250
- expect(context.method).toBe("refresh");
251
- expect(hookResponse.user).toBeUndefined(); // refresh has no user
252
- expect(tokens.refreshedExternalToken).toBe("refreshed-ext");
253
- });
254
- });
255
-
256
- // ── Error handling ───────────────────────────────────────────────────
257
-
258
- describe("error handling", () => {
259
- it("returns untransformed response when hook throws", async () => {
260
- const transformHook = jest.fn(async () => {
261
- throw new Error("External service down");
262
- });
263
- const app = createApp({ authHooks: { transformAuthResponse: transformHook } });
264
-
265
- const res = await app.request("/auth/register", json({ email: "new@test.com", password: "StrongPass1" }));
266
- expect(res.status).toBe(201);
267
- const body = await res.json() as Record<string, unknown>;
268
- const tokens = body.tokens as Record<string, unknown>;
269
- const user = body.user as Record<string, unknown>;
270
-
271
- // Response is still valid (untransformed fallback)
272
- expect(tokens.accessToken).toBeTruthy();
273
- expect(tokens.refreshToken).toBeTruthy();
274
- expect(user.email).toBe("new@test.com");
275
-
276
- // Error was logged
277
- expect(logger.error).toHaveBeenCalledWith(
278
- "[AuthHooks] transformAuthResponse error",
279
- expect.objectContaining({ error: "External service down" })
280
- );
281
- });
282
- });
283
-
284
- // ── Opt-in behavior ──────────────────────────────────────────────────
285
-
286
- describe("opt-in behavior", () => {
287
- it("does not alter response when hook is not provided", async () => {
288
- const app = createApp(); // no hooks
289
-
290
- const res = await app.request("/auth/register", json({ email: "new@test.com", password: "StrongPass1" }));
291
- expect(res.status).toBe(201);
292
- const body = await res.json() as Record<string, unknown>;
293
- const tokens = body.tokens as Record<string, unknown>;
294
- const user = body.user as Record<string, unknown>;
295
-
296
- // Standard response, no extra fields
297
- expect(tokens.accessToken).toBeTruthy();
298
- expect(tokens.refreshToken).toBeTruthy();
299
- expect(user.email).toBe("new@test.com");
300
- expect(Object.keys(tokens as object)).toEqual(
301
- expect.arrayContaining(["accessToken", "refreshToken", "accessTokenExpiresAt"])
302
- );
303
- });
304
- });
305
- });