@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,1098 +0,0 @@
1
- /**
2
- * Auth Routes — Integration Tests
3
- *
4
- * Tests the full Hono request → route handler → JSON response cycle.
5
- * Services are mocked so we can exercise the HTTP layer in isolation while
6
- * still verifying business logic (first-user bootstrap, token rotation, etc.).
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, generateAccessToken, hashRefreshToken } from "../src/auth/jwt";
15
-
16
- // ── Mocks ───────────────────────────────────────────────────────────────────
17
-
18
- jest.mock("../src/auth/password");
19
-
20
- jest.mock("../src/utils/logger", () => {
21
- return {
22
- logger: {
23
- info: jest.fn(),
24
- warn: jest.fn(),
25
- error: jest.fn(),
26
- debug: jest.fn(),
27
- child: jest.fn().mockReturnThis()
28
- }
29
- };
30
- });
31
-
32
- // Bypass rate limiters — they share state across tests and cause 429s
33
- jest.mock("../src/auth/rate-limiter", () => {
34
- const passthrough = async (_c: unknown, next: () => Promise<void>) => next();
35
- return {
36
- createRateLimiter: () => passthrough,
37
- defaultAuthLimiter: passthrough,
38
- strictAuthLimiter: passthrough
39
- };
40
- });
41
-
42
- import { hashPassword, verifyPassword, validatePasswordStrength } from "../src/auth/password";
43
- import { logger } from "../src/utils/logger";
44
- import { z } from "zod";
45
-
46
- // ── Helpers ─────────────────────────────────────────────────────────────────
47
-
48
- const TEST_SECRET = "integration-test-secret-key-that-is-definitely-32-chars-long!!";
49
-
50
- function mockUser(overrides: Partial<{ id: string; email: string; passwordHash: string | null; displayName: string | null; photoUrl: string | null; provider: string; emailVerified: boolean; emailVerificationToken: string | null }> = {}) {
51
- return {
52
- id: overrides.id ?? "user-1",
53
- email: overrides.email ?? "test@example.com",
54
- passwordHash: "passwordHash" in overrides ? overrides.passwordHash : "salt:hash",
55
- displayName: overrides.displayName ?? "Test User",
56
- photoUrl: overrides.photoUrl ?? null,
57
- emailVerified: overrides.emailVerified ?? false,
58
- emailVerificationToken: overrides.emailVerificationToken ?? null,
59
- emailVerificationSentAt: null,
60
- createdAt: new Date(),
61
- updatedAt: new Date()
62
- };
63
- }
64
-
65
- function mockRole(id: string, isAdmin = false) {
66
- return { id,
67
- name: id.charAt(0).toUpperCase() + id.slice(1),
68
- isAdmin,
69
- defaultPermissions: null,
70
- collectionPermissions: null };
71
- }
72
-
73
- let mockAuthRepo: jest.Mocked<AuthRepository>;
74
- let mockEmailService: { send: jest.Mock; isConfigured: jest.Mock };
75
-
76
- function createApp(opts: { allowRegistration?: boolean; withEmail?: boolean; defaultRole?: string; isBootstrapCompleted?: () => Promise<boolean> } = {}) {
77
- // Re-create mocked service instances each time
78
-
79
- // Wire constructor mocks to return our instances
80
-
81
- // Default returns for mocked services
82
-
83
- mockAuthRepo = {
84
- getUserByEmail: jest.fn().mockResolvedValue(null),
85
- getUserByIdentity: jest.fn().mockResolvedValue(null),
86
- linkUserIdentity: jest.fn().mockResolvedValue(undefined),
87
- getUserIdentities: jest.fn().mockResolvedValue([]),
88
- getUserById: jest.fn().mockResolvedValue(null),
89
- createUser: jest.fn().mockImplementation((data) =>
90
- Promise.resolve(mockUser({ email: data.email,
91
- displayName: data.displayName,
92
- passwordHash: data.passwordHash }))
93
- ),
94
- listUsers: jest.fn().mockResolvedValue([]),
95
- getUserRoles: jest.fn().mockResolvedValue([mockRole("editor")]),
96
- getUserRoleIds: jest.fn().mockResolvedValue(["editor"]),
97
- assignDefaultRole: jest.fn().mockResolvedValue(undefined),
98
- setUserRoles: jest.fn().mockResolvedValue(undefined),
99
- updateUser: jest.fn().mockImplementation((id, data) =>
100
- Promise.resolve(mockUser({ id,
101
- ...data }))
102
- ),
103
- deleteUser: jest.fn().mockResolvedValue(undefined),
104
- updatePassword: jest.fn().mockResolvedValue(undefined),
105
- setEmailVerified: jest.fn().mockResolvedValue(undefined),
106
- setVerificationToken: jest.fn().mockResolvedValue(undefined),
107
- getUserByVerificationToken: jest.fn().mockResolvedValue(null),
108
- getUserWithRoles: jest.fn().mockImplementation(async (userId) => {
109
- const user = mockUser({ id: userId });
110
- return { user,
111
- roles: [mockRole("editor")] };
112
- }),
113
- createRefreshToken: jest.fn().mockResolvedValue(undefined),
114
- findRefreshTokenByHash: jest.fn().mockResolvedValue(null),
115
- deleteRefreshToken: jest.fn().mockResolvedValue(undefined),
116
- deleteAllRefreshTokensForUser: jest.fn().mockResolvedValue(undefined),
117
- listRefreshTokensForUser: jest.fn().mockResolvedValue([]),
118
- deleteRefreshTokenById: jest.fn().mockResolvedValue(undefined),
119
- createPasswordResetToken: jest.fn().mockResolvedValue(undefined),
120
- findValidPasswordResetToken: jest.fn().mockResolvedValue(null),
121
- markPasswordResetTokenUsed: jest.fn().mockResolvedValue(undefined),
122
- deleteExpiredPasswordResetTokens: jest.fn().mockResolvedValue(undefined)
123
- } as unknown as jest.Mocked<AuthRepository>;
124
-
125
-
126
- // Password mocks
127
- (validatePasswordStrength as jest.Mock).mockReturnValue({ valid: true,
128
- errors: [] });
129
- (hashPassword as jest.Mock).mockResolvedValue("hashed-pw");
130
- (verifyPassword as jest.Mock).mockResolvedValue(true);
131
-
132
- // Email mock
133
- mockEmailService = { send: jest.fn().mockResolvedValue(undefined),
134
- isConfigured: jest.fn().mockReturnValue(opts.withEmail ?? false) };
135
-
136
- const config: AuthModuleConfig = {
137
- authRepo: mockAuthRepo,
138
- allowRegistration: opts.allowRegistration ?? true,
139
- defaultRole: opts.defaultRole,
140
- emailService: opts.withEmail ? mockEmailService as any : undefined,
141
- emailConfig: opts.withEmail ? { from: "test@test.com",
142
- appName: "TestApp",
143
- resetPasswordUrl: "https://app.test",
144
- verifyEmailUrl: "https://app.test" } : undefined,
145
- oauthProviders: opts.withEmail === false && opts.allowRegistration === false ? [] : [
146
- {
147
- id: "google",
148
- schema: z.object({ idToken: z.string().min(1) }),
149
- verify: async (payload: any) => {
150
- const idToken = payload.idToken;
151
- if (idToken === "bad-token") return null;
152
- if (idToken === "link-token") return { providerId: "g-456",
153
- email: "existing@test.com",
154
- displayName: "Existing",
155
- photoUrl: null,
156
- emailVerified: true };
157
- if (idToken === "returning-token") return { providerId: "g-789",
158
- email: "returning@test.com",
159
- displayName: "Updated Name",
160
- photoUrl: "https://new-photo.url",
161
- emailVerified: true };
162
- if (idToken === "valid-token") return { providerId: "g-123",
163
- email: "google@test.com",
164
- displayName: "Google User",
165
- photoUrl: "https://photo.url",
166
- emailVerified: true };
167
- return null;
168
- }
169
- }
170
- ]
171
- };
172
-
173
- if (opts.isBootstrapCompleted) {
174
- config.isBootstrapCompleted = opts.isBootstrapCompleted;
175
- }
176
-
177
-
178
- const app = new Hono<HonoEnv>();
179
- app.onError(errorHandler);
180
- app.route("/auth", createAuthRoutes(config));
181
- return app;
182
- }
183
-
184
- function json(body: Record<string, unknown>) {
185
- return {
186
- method: "POST" as const,
187
- headers: { "Content-Type": "application/json" },
188
- body: JSON.stringify(body)
189
- };
190
- }
191
-
192
- function authHeader(userId = "user-1", roles = ["editor"]) {
193
- return { Authorization: `Bearer ${generateAccessToken(userId, roles)}` };
194
- }
195
-
196
- // ═══════════════════════════════════════════════════════════════════════════
197
- // TESTS
198
- // ═══════════════════════════════════════════════════════════════════════════
199
-
200
- describe("Auth Routes (Integration)", () => {
201
- beforeAll(() => {
202
- configureJwt({ secret: TEST_SECRET,
203
- accessExpiresIn: "1h" });
204
- });
205
-
206
- beforeEach(() => {
207
- jest.clearAllMocks();
208
- });
209
-
210
- describe("Configuration Security", () => {
211
- it("throws an error when defaultRole is set to 'admin'", () => {
212
- expect(() => createApp({ defaultRole: "admin" })).toThrow(/CRITICAL SECURITY ERROR/);
213
- });
214
- });
215
-
216
- // ── Registration ────────────────────────────────────────────────────
217
- describe("POST /auth/register", () => {
218
- it("registers a new user and returns 201 with tokens", async () => {
219
- const app = createApp();
220
-
221
- const res = await app.request("/auth/register", json({ email: "new@test.com",
222
- password: "StrongPass1" }));
223
- expect(res.status).toBe(201);
224
- const body = await res.json() as any;
225
- expect(body.tokens.accessToken).toBeTruthy();
226
- expect(body.tokens.refreshToken).toBeTruthy();
227
- expect(body.user.email).toBe("new@test.com");
228
- });
229
-
230
- it("first user does NOT get admin role (must use bootstrap)", async () => {
231
- const app = createApp();
232
-
233
- await app.request("/auth/register", json({ email: "first@test.com",
234
- password: "StrongPass1" }));
235
- // No admin assignment — users must bootstrap via POST /admin/bootstrap
236
- expect(mockAuthRepo.assignDefaultRole).not.toHaveBeenCalled();
237
- });
238
-
239
- it("assigns configured default role to new users", async () => {
240
- const app = createApp({ defaultRole: "editor" });
241
-
242
- await app.request("/auth/register", json({ email: "second@test.com",
243
- password: "StrongPass1" }));
244
- expect(mockAuthRepo.assignDefaultRole).toHaveBeenCalledWith(expect.any(String), "editor");
245
- });
246
-
247
- it("does not assign role when defaultRole is not configured", async () => {
248
- const app = createApp();
249
-
250
- await app.request("/auth/register", json({ email: "third@test.com",
251
- password: "StrongPass1" }));
252
- expect(mockAuthRepo.assignDefaultRole).not.toHaveBeenCalled();
253
- });
254
-
255
- it("returns 409 when email already exists", async () => {
256
- const app = createApp();
257
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(mockUser());
258
-
259
- const res = await app.request("/auth/register", json({ email: "existing@test.com",
260
- password: "StrongPass1" }));
261
- expect(res.status).toBe(409);
262
- const body = await res.json() as any;
263
- expect(body.error.code).toBe("EMAIL_EXISTS");
264
- });
265
-
266
- it("returns 400 for weak password", async () => {
267
- const app = createApp();
268
- (validatePasswordStrength as jest.Mock).mockReturnValueOnce({ valid: false,
269
- errors: ["Too short"] });
270
-
271
- const res = await app.request("/auth/register", json({ email: "new@test.com",
272
- password: "weak" }));
273
- expect(res.status).toBe(400);
274
- const body = await res.json() as any;
275
- expect(body.error.code).toBe("WEAK_PASSWORD");
276
- });
277
-
278
- it("returns 400 for invalid email (Zod)", async () => {
279
- const app = createApp();
280
- const res = await app.request("/auth/register", json({ email: "not-an-email",
281
- password: "StrongPass1" }));
282
- expect(res.status).toBe(400);
283
- const body = await res.json() as any;
284
- expect(body.error.code).toBe("INVALID_INPUT");
285
- });
286
-
287
- it("returns 400 for missing password", async () => {
288
- const app = createApp();
289
- const res = await app.request("/auth/register", json({ email: "a@b.com" }));
290
- expect(res.status).toBe(400);
291
- });
292
-
293
- it("returns 403 when registration is disabled", async () => {
294
- const app = createApp({ allowRegistration: false });
295
-
296
- const res = await app.request("/auth/register", json({ email: "new@test.com",
297
- password: "StrongPass1" }));
298
- expect(res.status).toBe(403);
299
- const body = await res.json() as any;
300
- expect(body.error.code).toBe("REGISTRATION_DISABLED");
301
- });
302
-
303
- it("blocks registration even on empty database when allowRegistration=false", async () => {
304
- const app = createApp({ allowRegistration: false });
305
- // Even with no users, registration should be denied
306
- mockAuthRepo.listUsers.mockResolvedValueOnce([]);
307
-
308
- const res = await app.request("/auth/register", json({ email: "first@test.com",
309
- password: "StrongPass1" }));
310
- expect(res.status).toBe(403);
311
- const body = await res.json() as any;
312
- expect(body.error.code).toBe("REGISTRATION_DISABLED");
313
- });
314
-
315
- it("stores refresh token after registration", async () => {
316
- const app = createApp();
317
-
318
- await app.request("/auth/register", json({ email: "a@b.com",
319
- password: "StrongPass1" }));
320
- expect(mockAuthRepo.createRefreshToken).toHaveBeenCalledTimes(1);
321
- });
322
- });
323
-
324
- // ── Login ───────────────────────────────────────────────────────────
325
- describe("POST /auth/login", () => {
326
- it("returns tokens on successful login", async () => {
327
- const app = createApp();
328
- const user = mockUser({ passwordHash: "salt:hash" });
329
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(user);
330
-
331
- const res = await app.request("/auth/login", json({ email: "test@example.com",
332
- password: "ValidPass1" }));
333
- expect(res.status).toBe(200);
334
- const body = await res.json() as any;
335
- expect(body.tokens.accessToken).toBeTruthy();
336
- expect(body.user.uid).toBe("user-1");
337
- });
338
-
339
- it("returns 401 for non-existent email", async () => {
340
- const app = createApp();
341
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(null);
342
-
343
- const res = await app.request("/auth/login", json({ email: "nobody@test.com",
344
- password: "Any1" }));
345
- expect(res.status).toBe(401);
346
- const body = await res.json() as any;
347
- expect(body.error.code).toBe("INVALID_CREDENTIALS");
348
- });
349
-
350
- it("returns 401 for wrong password", async () => {
351
- const app = createApp();
352
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(mockUser());
353
- (verifyPassword as jest.Mock).mockResolvedValueOnce(false);
354
-
355
- const res = await app.request("/auth/login", json({ email: "test@example.com",
356
- password: "Wrong1" }));
357
- expect(res.status).toBe(401);
358
- });
359
-
360
- it("returns 401 for user without password hash (Google-only)", async () => {
361
- const app = createApp();
362
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(mockUser({ passwordHash: null }));
363
-
364
- const res = await app.request("/auth/login", json({ email: "google@test.com",
365
- password: "Any1" }));
366
- expect(res.status).toBe(401);
367
- });
368
-
369
- it("returns 400 for missing email field", async () => {
370
- const app = createApp();
371
- const res = await app.request("/auth/login", json({ password: "Any1" }));
372
- expect(res.status).toBe(400);
373
- });
374
-
375
- it("stores refresh token on login", async () => {
376
- const app = createApp();
377
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(mockUser());
378
-
379
- await app.request("/auth/login", json({ email: "test@example.com",
380
- password: "ValidPass1" }));
381
- expect(mockAuthRepo.createRefreshToken).toHaveBeenCalledTimes(1);
382
- });
383
-
384
- it("emits a structured security audit log on successful login", async () => {
385
- const app = createApp();
386
- const user = mockUser({ passwordHash: "salt:hash" });
387
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(user);
388
-
389
- await app.request("/auth/login", json({ email: "test@example.com", password: "ValidPass1" }));
390
-
391
- expect(logger.info).toHaveBeenCalledWith(
392
- expect.stringContaining("[Security Audit] Auth login success"),
393
- expect.objectContaining({
394
- userId: "user-1",
395
- email: "test@example.com",
396
- eventType: "auth.login.success"
397
- })
398
- );
399
- });
400
-
401
- it("emits a structured security audit log on failed login (wrong password)", async () => {
402
- const app = createApp();
403
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(mockUser());
404
- (verifyPassword as jest.Mock).mockResolvedValueOnce(false);
405
-
406
- await app.request("/auth/login", json({ email: "test@example.com", password: "WrongPassword" }));
407
-
408
- expect(logger.warn).toHaveBeenCalledWith(
409
- expect.stringContaining("[Security Audit] Auth login failure"),
410
- expect.objectContaining({
411
- email: "test@example.com",
412
- userId: "user-1",
413
- eventType: "auth.login.failure"
414
- })
415
- );
416
- });
417
- });
418
-
419
- // ── Google OAuth ────────────────────────────────────────────────────
420
- describe("POST /auth/google", () => {
421
- it("returns 404 when OAuth provider is not injected", async () => {
422
- const app = createApp({ allowRegistration: false,
423
- withEmail: false }); // Hack to pass empty list of providers
424
- const res = await app.request("/auth/google", json({ idToken: "google-token" }));
425
- expect(res.status).toBe(404);
426
- });
427
-
428
- it("returns 401 for invalid Google token", async () => {
429
- const app = createApp();
430
-
431
- const res = await app.request("/auth/google", json({ idToken: "bad-token" }));
432
- expect(res.status).toBe(401);
433
- const body = await res.json() as any;
434
- expect(body.error.code).toBe("INVALID_TOKEN");
435
- });
436
-
437
- it("creates a new user for new Google sign-in", async () => {
438
- const app = createApp();
439
- mockAuthRepo.getUserByIdentity.mockResolvedValueOnce(null);
440
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(null);
441
-
442
- const res = await app.request("/auth/google", json({ idToken: "valid-token" }));
443
- expect(res.status).toBe(200);
444
- expect(mockAuthRepo.createUser).toHaveBeenCalledWith(expect.objectContaining({
445
- email: "google@test.com"
446
- }));
447
- expect(mockAuthRepo.linkUserIdentity).toHaveBeenCalledWith(expect.any(String), "google", "g-123", expect.any(Object));
448
- // Verify no admin auto-assignment
449
- expect(mockAuthRepo.assignDefaultRole).not.toHaveBeenCalled();
450
- });
451
-
452
- it("links Google to existing account by email", async () => {
453
- const app = createApp();
454
- const existing = mockUser({ email: "existing@test.com" });
455
- mockAuthRepo.getUserByIdentity.mockResolvedValueOnce(null);
456
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(existing);
457
-
458
- const res = await app.request("/auth/google", json({ idToken: "link-token" }));
459
- expect(res.status).toBe(200);
460
- expect(mockAuthRepo.linkUserIdentity).toHaveBeenCalledWith(existing.id, "google", "g-456", expect.any(Object));
461
- });
462
-
463
- it("updates profile for returning Google user", async () => {
464
- const app = createApp();
465
- const existingUser = mockUser({ id: "g-user-1" });
466
- mockAuthRepo.getUserByIdentity.mockResolvedValueOnce(existingUser);
467
-
468
- const res = await app.request("/auth/google", json({ idToken: "returning-token" }));
469
- expect(res.status).toBe(200);
470
- expect(mockAuthRepo.updateUser).toHaveBeenCalledWith(existingUser.id, expect.objectContaining({
471
- displayName: "Updated Name",
472
- photoUrl: "https://new-photo.url"
473
- }));
474
- });
475
- });
476
-
477
- // ── Token Refresh ───────────────────────────────────────────────────
478
- describe("POST /auth/refresh", () => {
479
- it("returns new tokens on valid refresh", async () => {
480
- const app = createApp();
481
- mockAuthRepo.findRefreshTokenByHash.mockResolvedValueOnce({
482
- id: "rt-1",
483
- userId: "user-1",
484
- tokenHash: "old-hash",
485
- expiresAt: new Date(Date.now() + 86400000),
486
- createdAt: new Date(),
487
- userAgent: "",
488
- ipAddress: ""
489
- });
490
- mockAuthRepo.getUserRoles.mockResolvedValueOnce([mockRole("editor")]);
491
-
492
- const res = await app.request("/auth/refresh", json({ refreshToken: "valid-refresh-token" }));
493
- expect(res.status).toBe(200);
494
- const body = await res.json() as any;
495
- expect(body.tokens.accessToken).toBeTruthy();
496
- expect(body.tokens.refreshToken).toBeTruthy();
497
- });
498
-
499
- it("rotates refresh token — deletes old, creates new", async () => {
500
- const app = createApp();
501
- mockAuthRepo.findRefreshTokenByHash.mockResolvedValueOnce({
502
- id: "rt-1",
503
- userId: "user-1",
504
- tokenHash: "old-hash",
505
- expiresAt: new Date(Date.now() + 86400000),
506
- createdAt: new Date(),
507
- userAgent: "",
508
- ipAddress: ""
509
- });
510
-
511
- await app.request("/auth/refresh", json({ refreshToken: "the-token" }));
512
- // Old token deleted
513
- expect(mockAuthRepo.deleteRefreshToken).toHaveBeenCalledTimes(1);
514
- // New token stored
515
- expect(mockAuthRepo.createRefreshToken).toHaveBeenCalledTimes(1);
516
- });
517
-
518
- it("returns 401 for unknown refresh token", async () => {
519
- const app = createApp();
520
- mockAuthRepo.findRefreshTokenByHash.mockResolvedValueOnce(null);
521
-
522
- const res = await app.request("/auth/refresh", json({ refreshToken: "unknown" }));
523
- expect(res.status).toBe(401);
524
- const body = await res.json() as any;
525
- expect(body.error.code).toBe("INVALID_TOKEN");
526
- });
527
-
528
- it("returns 401 and deletes expired refresh token", async () => {
529
- const app = createApp();
530
- mockAuthRepo.findRefreshTokenByHash.mockResolvedValueOnce({
531
- id: "rt-1",
532
- userId: "user-1",
533
- tokenHash: "expired-hash",
534
- expiresAt: new Date(Date.now() - 1000), // expired
535
- createdAt: new Date(),
536
- userAgent: "",
537
- ipAddress: ""
538
- });
539
-
540
- const res = await app.request("/auth/refresh", json({ refreshToken: "expired-token" }));
541
- expect(res.status).toBe(401);
542
- const body = await res.json() as any;
543
- expect(body.error.code).toBe("TOKEN_EXPIRED");
544
- expect(mockAuthRepo.deleteRefreshToken).toHaveBeenCalled();
545
- });
546
-
547
- it("returns 400 for missing refreshToken field", async () => {
548
- const app = createApp();
549
- const res = await app.request("/auth/refresh", json({}));
550
- expect(res.status).toBe(400);
551
- });
552
- });
553
-
554
- // ── Logout ──────────────────────────────────────────────────────────
555
- describe("POST /auth/logout", () => {
556
- it("deletes refresh token on logout", async () => {
557
- const app = createApp();
558
- const res = await app.request("/auth/logout", json({ refreshToken: "rt-to-delete" }));
559
- expect(res.status).toBe(200);
560
- expect(mockAuthRepo.deleteRefreshToken).toHaveBeenCalledTimes(1);
561
- });
562
-
563
- it("returns 200 even without refresh token", async () => {
564
- const app = createApp();
565
- const res = await app.request("/auth/logout", json({}));
566
- expect(res.status).toBe(200);
567
- expect(mockAuthRepo.deleteRefreshToken).not.toHaveBeenCalled();
568
- });
569
- });
570
-
571
- // ── Forgot Password ─────────────────────────────────────────────────
572
- describe("POST /auth/forgot-password", () => {
573
- it("always returns success (timing-safe)", async () => {
574
- const app = createApp({ withEmail: true });
575
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(null); // user doesn't exist
576
-
577
- const res = await app.request("/auth/forgot-password", json({ email: "nobody@test.com" }));
578
- expect(res.status).toBe(200);
579
- const body = await res.json() as any;
580
- expect(body.success).toBe(true);
581
- });
582
-
583
- it("sends reset email when user exists", async () => {
584
- const app = createApp({ withEmail: true });
585
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(mockUser());
586
-
587
- await app.request("/auth/forgot-password", json({ email: "test@example.com" }));
588
- expect(mockAuthRepo.createPasswordResetToken).toHaveBeenCalledTimes(1);
589
- expect(mockEmailService.send).toHaveBeenCalledTimes(1);
590
- });
591
-
592
- it("does not send email when user does not exist", async () => {
593
- const app = createApp({ withEmail: true });
594
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(null);
595
-
596
- await app.request("/auth/forgot-password", json({ email: "nobody@test.com" }));
597
- expect(mockAuthRepo.createPasswordResetToken).not.toHaveBeenCalled();
598
- expect(mockEmailService.send).not.toHaveBeenCalled();
599
- });
600
-
601
- it("returns 503 when email service is not configured", async () => {
602
- const app = createApp({ withEmail: false });
603
- const res = await app.request("/auth/forgot-password", json({ email: "test@test.com" }));
604
- expect(res.status).toBe(503);
605
- const body = await res.json() as any;
606
- expect(body.error.code).toBe("EMAIL_NOT_CONFIGURED");
607
- });
608
- });
609
-
610
- // ── Reset Password ──────────────────────────────────────────────────
611
- describe("POST /auth/reset-password", () => {
612
- it("resets password with valid token", async () => {
613
- const app = createApp();
614
- mockAuthRepo.findValidPasswordResetToken.mockResolvedValueOnce({
615
- userId: "user-1",
616
- expiresAt: new Date(Date.now() + 3600000)
617
- });
618
-
619
- const res = await app.request("/auth/reset-password", json({ token: "valid-reset-token",
620
- password: "NewStrong1" }));
621
- expect(res.status).toBe(200);
622
- expect(mockAuthRepo.updatePassword).toHaveBeenCalledWith("user-1", "hashed-pw");
623
- expect(mockAuthRepo.markPasswordResetTokenUsed).toHaveBeenCalled();
624
- });
625
-
626
- it("invalidates all sessions after password reset", async () => {
627
- const app = createApp();
628
- mockAuthRepo.findValidPasswordResetToken.mockResolvedValueOnce({
629
- userId: "user-1",
630
- expiresAt: new Date(Date.now() + 3600000)
631
- });
632
-
633
- await app.request("/auth/reset-password", json({ token: "token",
634
- password: "NewStrong1" }));
635
- expect(mockAuthRepo.deleteAllRefreshTokensForUser).toHaveBeenCalledWith("user-1");
636
- });
637
-
638
- it("returns 400 for invalid/expired token", async () => {
639
- const app = createApp();
640
- mockAuthRepo.findValidPasswordResetToken.mockResolvedValueOnce(null);
641
-
642
- const res = await app.request("/auth/reset-password", json({ token: "expired",
643
- password: "NewStrong1" }));
644
- expect(res.status).toBe(400);
645
- const body = await res.json() as any;
646
- expect(body.error.code).toBe("INVALID_TOKEN");
647
- });
648
-
649
- it("returns 400 for weak new password", async () => {
650
- const app = createApp();
651
- (validatePasswordStrength as jest.Mock).mockReturnValueOnce({ valid: false,
652
- errors: ["Too weak"] });
653
-
654
- const res = await app.request("/auth/reset-password", json({ token: "token",
655
- password: "weak" }));
656
- expect(res.status).toBe(400);
657
- const body = await res.json() as any;
658
- expect(body.error.code).toBe("WEAK_PASSWORD");
659
- });
660
- });
661
-
662
- // ── Change Password ─────────────────────────────────────────────────
663
- describe("POST /auth/change-password", () => {
664
- it("changes password for authenticated user", async () => {
665
- const app = createApp();
666
- mockAuthRepo.getUserById.mockResolvedValue(mockUser());
667
-
668
- const res = await app.request("/auth/change-password", {
669
- ...json({ oldPassword: "OldPass1",
670
- newPassword: "NewPass1" }),
671
- headers: { ...json({}).headers,
672
- ...authHeader() }
673
- });
674
- expect(res.status).toBe(200);
675
- expect(mockAuthRepo.updatePassword).toHaveBeenCalled();
676
- });
677
-
678
- it("invalidates all sessions after password change", async () => {
679
- const app = createApp();
680
- mockAuthRepo.getUserById.mockResolvedValue(mockUser());
681
-
682
- await app.request("/auth/change-password", {
683
- ...json({ oldPassword: "Old1",
684
- newPassword: "New1Pass" }),
685
- headers: { ...json({}).headers,
686
- ...authHeader() }
687
- });
688
- expect(mockAuthRepo.deleteAllRefreshTokensForUser).toHaveBeenCalledWith("user-1");
689
- });
690
-
691
- it("returns 401 for wrong old password", async () => {
692
- const app = createApp();
693
- mockAuthRepo.getUserById.mockResolvedValue(mockUser());
694
- (verifyPassword as jest.Mock).mockResolvedValueOnce(false);
695
-
696
- const res = await app.request("/auth/change-password", {
697
- ...json({ oldPassword: "Wrong1",
698
- newPassword: "New1Pass" }),
699
- headers: { ...json({}).headers,
700
- ...authHeader() }
701
- });
702
- expect(res.status).toBe(401);
703
- });
704
-
705
- it("returns 400 for weak new password", async () => {
706
- const app = createApp();
707
- mockAuthRepo.getUserById.mockResolvedValue(mockUser());
708
- (validatePasswordStrength as jest.Mock).mockReturnValueOnce({ valid: false,
709
- errors: ["Too short"] });
710
-
711
- const res = await app.request("/auth/change-password", {
712
- ...json({ oldPassword: "Old1",
713
- newPassword: "x" }),
714
- headers: { ...json({}).headers,
715
- ...authHeader() }
716
- });
717
- expect(res.status).toBe(400);
718
- });
719
-
720
- it("returns 401 without auth", async () => {
721
- const app = createApp();
722
- const res = await app.request("/auth/change-password", json({ oldPassword: "Old1",
723
- newPassword: "New1Pass" }));
724
- expect(res.status).toBe(401);
725
- });
726
-
727
- it("returns 400 for user without password (Google-only account)", async () => {
728
- const app = createApp();
729
- mockAuthRepo.getUserById.mockResolvedValue(mockUser({ passwordHash: null }));
730
-
731
- const res = await app.request("/auth/change-password", {
732
- ...json({ oldPassword: "Old1",
733
- newPassword: "New1Pass" }),
734
- headers: { ...json({}).headers,
735
- ...authHeader() }
736
- });
737
- expect(res.status).toBe(400);
738
- const body = await res.json() as any;
739
- expect(body.error.code).toBe("INVALID_ACCOUNT");
740
- });
741
- });
742
-
743
- // ── Email Verification ──────────────────────────────────────────────
744
- describe("Email verification", () => {
745
- describe("POST /auth/send-verification", () => {
746
- it("sends verification email for authenticated user", async () => {
747
- const app = createApp({ withEmail: true });
748
- mockAuthRepo.getUserById.mockResolvedValueOnce(mockUser({ emailVerified: false }));
749
-
750
- const res = await app.request("/auth/send-verification", {
751
- method: "POST",
752
- headers: { ...authHeader() }
753
- });
754
- expect(res.status).toBe(200);
755
- expect(mockAuthRepo.setVerificationToken).toHaveBeenCalled();
756
- expect(mockEmailService.send).toHaveBeenCalled();
757
- });
758
-
759
- it("returns 400 when email is already verified", async () => {
760
- const app = createApp({ withEmail: true });
761
- mockAuthRepo.getUserById.mockResolvedValueOnce(mockUser({ emailVerified: true }));
762
-
763
- const res = await app.request("/auth/send-verification", {
764
- method: "POST",
765
- headers: { ...authHeader() }
766
- });
767
- expect(res.status).toBe(400);
768
- const body = await res.json() as any;
769
- expect(body.error.code).toBe("ALREADY_VERIFIED");
770
- });
771
-
772
- it("returns 401 without auth", async () => {
773
- const app = createApp({ withEmail: true });
774
- const res = await app.request("/auth/send-verification", { method: "POST" });
775
- expect(res.status).toBe(401);
776
- });
777
-
778
- it("returns 503 when email service is not configured", async () => {
779
- const app = createApp({ withEmail: false });
780
- const res = await app.request("/auth/send-verification", {
781
- method: "POST",
782
- headers: { ...authHeader() }
783
- });
784
- expect(res.status).toBe(503);
785
- });
786
- });
787
-
788
- describe("GET /auth/verify-email", () => {
789
- it("verifies email with valid token", async () => {
790
- const app = createApp();
791
- mockAuthRepo.getUserByVerificationToken.mockResolvedValueOnce(mockUser());
792
-
793
- const res = await app.request("/auth/verify-email?token=valid-token");
794
- expect(res.status).toBe(200);
795
- expect(mockAuthRepo.setEmailVerified).toHaveBeenCalledWith("user-1", true);
796
- });
797
-
798
- it("returns 400 for invalid verification token", async () => {
799
- const app = createApp();
800
- mockAuthRepo.getUserByVerificationToken.mockResolvedValueOnce(null);
801
-
802
- const res = await app.request("/auth/verify-email?token=bad-token");
803
- expect(res.status).toBe(400);
804
- const body = await res.json() as any;
805
- expect(body.error.code).toBe("INVALID_TOKEN");
806
- });
807
-
808
- it("returns 400 when token is missing", async () => {
809
- const app = createApp();
810
- const res = await app.request("/auth/verify-email");
811
- expect(res.status).toBe(400);
812
- });
813
- });
814
- });
815
-
816
- // ── User Profile ────────────────────────────────────────────────────
817
- describe("GET /auth/me", () => {
818
- it("returns authenticated user with roles", async () => {
819
- const app = createApp();
820
- const res = await app.request("/auth/me", {
821
- headers: { ...authHeader("user-1", ["admin"]) }
822
- });
823
- expect(res.status).toBe(200);
824
- const body = await res.json() as any;
825
- expect(body.user.uid).toBe("user-1");
826
- expect(body.user.roles).toBeDefined();
827
- });
828
-
829
- it("returns 401 without auth", async () => {
830
- const app = createApp();
831
- const res = await app.request("/auth/me");
832
- expect(res.status).toBe(401);
833
- });
834
-
835
- it("returns 404 when user is deleted", async () => {
836
- const app = createApp();
837
- mockAuthRepo.getUserWithRoles.mockResolvedValueOnce(null);
838
-
839
- const res = await app.request("/auth/me", {
840
- headers: { ...authHeader() }
841
- });
842
- expect(res.status).toBe(404);
843
- });
844
- });
845
-
846
- describe("PATCH /auth/me", () => {
847
- it("updates user profile", async () => {
848
- const app = createApp();
849
- mockAuthRepo.updateUser.mockResolvedValueOnce(mockUser({ displayName: "New Name" }));
850
-
851
- const res = await app.request("/auth/me", {
852
- method: "PATCH",
853
- headers: { "Content-Type": "application/json",
854
- ...authHeader() },
855
- body: JSON.stringify({ displayName: "New Name" })
856
- });
857
- expect(res.status).toBe(200);
858
- expect(mockAuthRepo.updateUser).toHaveBeenCalledWith("user-1", expect.objectContaining({
859
- displayName: "New Name"
860
- }));
861
- });
862
-
863
- it("returns 401 without auth", async () => {
864
- const app = createApp();
865
- const res = await app.request("/auth/me", {
866
- method: "PATCH",
867
- headers: { "Content-Type": "application/json" },
868
- body: JSON.stringify({ displayName: "Name" })
869
- });
870
- expect(res.status).toBe(401);
871
- });
872
- });
873
-
874
- // ── Sessions ────────────────────────────────────────────────────────
875
- describe("Session management", () => {
876
- it("GET /auth/sessions lists active sessions", async () => {
877
- const app = createApp();
878
- mockAuthRepo.listRefreshTokensForUser.mockResolvedValueOnce([
879
- { id: "s1",
880
- userId: "user-1",
881
- tokenHash: "h1",
882
- expiresAt: new Date(),
883
- createdAt: new Date(),
884
- userAgent: "Chrome",
885
- ipAddress: "1.2.3.4" }
886
- ]);
887
-
888
- const res = await app.request("/auth/sessions", { headers: { ...authHeader() } });
889
- expect(res.status).toBe(200);
890
- const body = await res.json() as any;
891
- expect(body.sessions).toHaveLength(1);
892
- expect(body.sessions[0].id).toBe("s1");
893
- });
894
-
895
- it("DELETE /auth/sessions revokes all sessions", async () => {
896
- const app = createApp();
897
- const res = await app.request("/auth/sessions", {
898
- method: "DELETE",
899
- headers: { ...authHeader() }
900
- });
901
- expect(res.status).toBe(200);
902
- expect(mockAuthRepo.deleteAllRefreshTokensForUser).toHaveBeenCalledWith("user-1");
903
- });
904
-
905
- it("DELETE /auth/sessions/:id revokes specific session", async () => {
906
- const app = createApp();
907
- const res = await app.request("/auth/sessions/s123", {
908
- method: "DELETE",
909
- headers: { ...authHeader() }
910
- });
911
- expect(res.status).toBe(200);
912
- expect(mockAuthRepo.deleteRefreshTokenById).toHaveBeenCalledWith("s123", "user-1");
913
- });
914
-
915
- it("sessions endpoints return 401 without auth", async () => {
916
- const app = createApp();
917
- const res1 = await app.request("/auth/sessions");
918
- expect(res1.status).toBe(401);
919
-
920
- const res2 = await app.request("/auth/sessions", { method: "DELETE" });
921
- expect(res2.status).toBe(401);
922
- });
923
- });
924
-
925
- // ── Auth Config ─────────────────────────────────────────────────────
926
- describe("GET /auth/config", () => {
927
- it("returns needsSetup=true when isBootstrapCompleted returns false", async () => {
928
- const app = createApp({ isBootstrapCompleted: async () => false });
929
-
930
- const res = await app.request("/auth/config");
931
- expect(res.status).toBe(200);
932
- const body = await res.json() as any;
933
- expect(body.needsSetup).toBe(true);
934
- expect(body.registrationEnabled).toBe(true); // always true when needsSetup
935
- });
936
-
937
- it("returns needsSetup=false when isBootstrapCompleted returns true", async () => {
938
- const app = createApp({ allowRegistration: false,
939
- isBootstrapCompleted: async () => true });
940
-
941
- const res = await app.request("/auth/config");
942
- expect(res.status).toBe(200);
943
- const body = await res.json() as any;
944
- expect(body.needsSetup).toBe(false);
945
- expect(body.registrationEnabled).toBe(false);
946
- });
947
-
948
- it("falls back to user-count check when no isBootstrapCompleted callback", async () => {
949
- const app = createApp();
950
- mockAuthRepo.listUsers.mockResolvedValueOnce([]);
951
-
952
- const res = await app.request("/auth/config");
953
- expect(res.status).toBe(200);
954
- const body = await res.json() as any;
955
- expect(body.needsSetup).toBe(true);
956
- expect(body.registrationEnabled).toBe(true);
957
- });
958
-
959
- it("returns correct flags when users exist and no callback", async () => {
960
- const app = createApp({ allowRegistration: false,
961
- withEmail: false });
962
- mockAuthRepo.listUsers.mockResolvedValueOnce([mockUser()]);
963
-
964
- const res = await app.request("/auth/config");
965
- expect(res.status).toBe(200);
966
- const body = await res.json() as any;
967
- expect(body.needsSetup).toBe(false);
968
- expect(body.registrationEnabled).toBe(false);
969
- expect(body.enabledProviders).toEqual([]);
970
- });
971
-
972
- it("reports Google enabled when configured", async () => {
973
- const app = createApp();
974
- mockAuthRepo.listUsers.mockResolvedValueOnce([mockUser()]);
975
-
976
- const res = await app.request("/auth/config");
977
- const body = await res.json() as any;
978
- expect(body.enabledProviders).toContain("google");
979
- });
980
- });
981
-
982
- // ═════════════════════════════════════════════════════════════════════
983
- // SECURITY REGRESSION TESTS — CVE: First-User Admin Privilege Escalation
984
- // These tests directly verify the exploit scenarios from the security audit.
985
- // ═════════════════════════════════════════════════════════════════════
986
-
987
- describe("Security: privilege escalation prevention", () => {
988
- it("CVE-FIX: registration NEVER assigns admin role, even for first user", async () => {
989
- const app = createApp({ allowRegistration: true });
990
- // Simulate first user (empty database before, one user after create)
991
- mockAuthRepo.listUsers.mockResolvedValueOnce([]);
992
-
993
- const res = await app.request("/auth/register", json({
994
- email: "hacker@evil.com",
995
- password: "HackRebase2026!",
996
- displayName: "Hacker"
997
- }));
998
-
999
- expect(res.status).toBe(201);
1000
- const body = await res.json() as any;
1001
-
1002
- // The critical assertion: admin must NOT be in the roles
1003
- expect(mockAuthRepo.assignDefaultRole).not.toHaveBeenCalledWith(
1004
- expect.any(String), "admin"
1005
- );
1006
- // Verify the user was created but NOT given admin
1007
- expect(mockAuthRepo.createUser).toHaveBeenCalledTimes(1);
1008
- });
1009
-
1010
- it("CVE-FIX: OAuth registration NEVER assigns admin role, even for first user", async () => {
1011
- const app = createApp({ allowRegistration: true });
1012
- mockAuthRepo.getUserByIdentity.mockResolvedValueOnce(null);
1013
- mockAuthRepo.getUserByEmail.mockResolvedValueOnce(null);
1014
-
1015
- const res = await app.request("/auth/google", json({ idToken: "valid-token" }));
1016
- expect(res.status).toBe(200);
1017
-
1018
- // The critical assertion: admin must NOT be assigned
1019
- expect(mockAuthRepo.assignDefaultRole).not.toHaveBeenCalledWith(
1020
- expect.any(String), "admin"
1021
- );
1022
- });
1023
-
1024
- it("CVE-FIX: empty database does NOT bypass allowRegistration=false", async () => {
1025
- const app = createApp({ allowRegistration: false });
1026
- // Even with zero users, the registration endpoint must reject
1027
- mockAuthRepo.listUsers.mockResolvedValueOnce([]);
1028
-
1029
- const res = await app.request("/auth/register", json({
1030
- email: "hacker@evil.com",
1031
- password: "HackRebase2026!",
1032
- displayName: "Hacker"
1033
- }));
1034
-
1035
- expect(res.status).toBe(403);
1036
- const body = await res.json() as any;
1037
- expect(body.error.code).toBe("REGISTRATION_DISABLED");
1038
- // createUser must NOT have been called
1039
- expect(mockAuthRepo.createUser).not.toHaveBeenCalled();
1040
- });
1041
-
1042
- it("CVE-FIX: registration is blocked when allowRegistration defaults to false", async () => {
1043
- const app = createApp({ allowRegistration: false });
1044
-
1045
- const res = await app.request("/auth/register", json({
1046
- email: "hacker@evil.com",
1047
- password: "HackRebase2026!",
1048
- displayName: "Hacker"
1049
- }));
1050
-
1051
- expect(res.status).toBe(403);
1052
- const body = await res.json() as any;
1053
- expect(body.error.code).toBe("REGISTRATION_DISABLED");
1054
- expect(mockAuthRepo.createUser).not.toHaveBeenCalled();
1055
- });
1056
-
1057
- it("CVE-FIX: concurrent registration attempts cannot produce multiple admins", async () => {
1058
- const app = createApp({ allowRegistration: true });
1059
-
1060
- // Simulate 5 concurrent registration requests
1061
- const requests = Array.from({ length: 5 }, (_, i) =>
1062
- app.request("/auth/register", json({
1063
- email: `concurrent-${i}@evil.com`,
1064
- password: "StrongPass1",
1065
- displayName: `Concurrent ${i}`
1066
- }))
1067
- );
1068
-
1069
- const responses = await Promise.all(requests);
1070
- const successfulRegistrations = responses.filter(r => r.status === 201);
1071
-
1072
- // Even if multiple registrations succeed, NONE should get admin
1073
- expect(mockAuthRepo.assignDefaultRole).not.toHaveBeenCalledWith(
1074
- expect.any(String), "admin"
1075
- );
1076
- });
1077
-
1078
- it("CVE-FIX: defaultRole cannot be set to 'admin' to grant admin via registration", async () => {
1079
- // Even if someone misconfigures defaultRole as 'admin',
1080
- // this test documents the current behavior — it would assign admin.
1081
- // The fix is in the config validation at startup (outside routes).
1082
- // Here we verify the defaultRole IS what's passed, and the auto-escalation is gone.
1083
- const app = createApp({ allowRegistration: true,
1084
- defaultRole: "viewer" });
1085
-
1086
- await app.request("/auth/register", json({
1087
- email: "new@test.com",
1088
- password: "StrongPass1"
1089
- }));
1090
-
1091
- // Only the configured default role is assigned, never auto-admin
1092
- expect(mockAuthRepo.assignDefaultRole).toHaveBeenCalledWith(
1093
- expect.any(String), "viewer"
1094
- );
1095
- expect(mockAuthRepo.assignDefaultRole).toHaveBeenCalledTimes(1);
1096
- });
1097
- });
1098
- });