@rebasepro/server-core 0.0.1-canary.09e5ec5

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/LICENSE +6 -0
  2. package/README.md +40 -0
  3. package/build-errors.txt +52 -0
  4. package/coverage/clover.xml +3739 -0
  5. package/coverage/coverage-final.json +31 -0
  6. package/coverage/lcov-report/base.css +224 -0
  7. package/coverage/lcov-report/block-navigation.js +87 -0
  8. package/coverage/lcov-report/favicon.png +0 -0
  9. package/coverage/lcov-report/index.html +266 -0
  10. package/coverage/lcov-report/prettify.css +1 -0
  11. package/coverage/lcov-report/prettify.js +2 -0
  12. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  13. package/coverage/lcov-report/sorter.js +210 -0
  14. package/coverage/lcov-report/src/api/ast-schema-editor.ts.html +952 -0
  15. package/coverage/lcov-report/src/api/errors.ts.html +472 -0
  16. package/coverage/lcov-report/src/api/graphql/graphql-schema-generator.ts.html +1069 -0
  17. package/coverage/lcov-report/src/api/graphql/index.html +116 -0
  18. package/coverage/lcov-report/src/api/index.html +176 -0
  19. package/coverage/lcov-report/src/api/openapi-generator.ts.html +565 -0
  20. package/coverage/lcov-report/src/api/rest/api-generator.ts.html +994 -0
  21. package/coverage/lcov-report/src/api/rest/index.html +131 -0
  22. package/coverage/lcov-report/src/api/rest/query-parser.ts.html +550 -0
  23. package/coverage/lcov-report/src/api/schema-editor-routes.ts.html +202 -0
  24. package/coverage/lcov-report/src/api/server.ts.html +823 -0
  25. package/coverage/lcov-report/src/auth/admin-routes.ts.html +973 -0
  26. package/coverage/lcov-report/src/auth/index.html +176 -0
  27. package/coverage/lcov-report/src/auth/jwt.ts.html +574 -0
  28. package/coverage/lcov-report/src/auth/middleware.ts.html +745 -0
  29. package/coverage/lcov-report/src/auth/password.ts.html +310 -0
  30. package/coverage/lcov-report/src/auth/services.ts.html +2074 -0
  31. package/coverage/lcov-report/src/collections/index.html +116 -0
  32. package/coverage/lcov-report/src/collections/loader.ts.html +232 -0
  33. package/coverage/lcov-report/src/db/auth-schema.ts.html +523 -0
  34. package/coverage/lcov-report/src/db/data-transformer.ts.html +1753 -0
  35. package/coverage/lcov-report/src/db/entityService.ts.html +700 -0
  36. package/coverage/lcov-report/src/db/index.html +146 -0
  37. package/coverage/lcov-report/src/db/services/EntityFetchService.ts.html +4048 -0
  38. package/coverage/lcov-report/src/db/services/EntityPersistService.ts.html +883 -0
  39. package/coverage/lcov-report/src/db/services/RelationService.ts.html +3121 -0
  40. package/coverage/lcov-report/src/db/services/entity-helpers.ts.html +442 -0
  41. package/coverage/lcov-report/src/db/services/index.html +176 -0
  42. package/coverage/lcov-report/src/db/services/index.ts.html +124 -0
  43. package/coverage/lcov-report/src/generate-drizzle-schema-logic.ts.html +1960 -0
  44. package/coverage/lcov-report/src/index.html +116 -0
  45. package/coverage/lcov-report/src/services/driver-registry.ts.html +631 -0
  46. package/coverage/lcov-report/src/services/index.html +131 -0
  47. package/coverage/lcov-report/src/services/postgresDataDriver.ts.html +3025 -0
  48. package/coverage/lcov-report/src/storage/LocalStorageController.ts.html +1189 -0
  49. package/coverage/lcov-report/src/storage/S3StorageController.ts.html +970 -0
  50. package/coverage/lcov-report/src/storage/index.html +161 -0
  51. package/coverage/lcov-report/src/storage/storage-registry.ts.html +646 -0
  52. package/coverage/lcov-report/src/storage/types.ts.html +451 -0
  53. package/coverage/lcov-report/src/utils/drizzle-conditions.ts.html +3082 -0
  54. package/coverage/lcov-report/src/utils/index.html +116 -0
  55. package/coverage/lcov.info +7179 -0
  56. package/dist/common/src/collections/CollectionRegistry.d.ts +56 -0
  57. package/dist/common/src/collections/index.d.ts +1 -0
  58. package/dist/common/src/data/buildRebaseData.d.ts +14 -0
  59. package/dist/common/src/index.d.ts +3 -0
  60. package/dist/common/src/util/builders.d.ts +57 -0
  61. package/dist/common/src/util/callbacks.d.ts +6 -0
  62. package/dist/common/src/util/collections.d.ts +11 -0
  63. package/dist/common/src/util/common.d.ts +2 -0
  64. package/dist/common/src/util/conditions.d.ts +26 -0
  65. package/dist/common/src/util/entities.d.ts +58 -0
  66. package/dist/common/src/util/enums.d.ts +3 -0
  67. package/dist/common/src/util/index.d.ts +16 -0
  68. package/dist/common/src/util/navigation_from_path.d.ts +34 -0
  69. package/dist/common/src/util/navigation_utils.d.ts +20 -0
  70. package/dist/common/src/util/parent_references_from_path.d.ts +6 -0
  71. package/dist/common/src/util/paths.d.ts +14 -0
  72. package/dist/common/src/util/permissions.d.ts +5 -0
  73. package/dist/common/src/util/references.d.ts +2 -0
  74. package/dist/common/src/util/relations.d.ts +22 -0
  75. package/dist/common/src/util/resolutions.d.ts +72 -0
  76. package/dist/common/src/util/storage.d.ts +24 -0
  77. package/dist/index-DXVBFp5V.js +37 -0
  78. package/dist/index-DXVBFp5V.js.map +1 -0
  79. package/dist/index.es.js +49934 -0
  80. package/dist/index.es.js.map +1 -0
  81. package/dist/index.umd.js +49968 -0
  82. package/dist/index.umd.js.map +1 -0
  83. package/dist/server-core/src/api/ast-schema-editor.d.ts +21 -0
  84. package/dist/server-core/src/api/collections_for_test/callbacks_test_collection.d.ts +2 -0
  85. package/dist/server-core/src/api/errors.d.ts +35 -0
  86. package/dist/server-core/src/api/graphql/graphql-schema-generator.d.ts +35 -0
  87. package/dist/server-core/src/api/graphql/index.d.ts +1 -0
  88. package/dist/server-core/src/api/index.d.ts +9 -0
  89. package/dist/server-core/src/api/openapi-generator.d.ts +16 -0
  90. package/dist/server-core/src/api/rest/api-generator.d.ts +64 -0
  91. package/dist/server-core/src/api/rest/index.d.ts +1 -0
  92. package/dist/server-core/src/api/rest/query-parser.d.ts +9 -0
  93. package/dist/server-core/src/api/schema-editor-routes.d.ts +3 -0
  94. package/dist/server-core/src/api/server.d.ts +40 -0
  95. package/dist/server-core/src/api/types.d.ts +90 -0
  96. package/dist/server-core/src/auth/admin-routes.d.ts +16 -0
  97. package/dist/server-core/src/auth/apple-oauth.d.ts +30 -0
  98. package/dist/server-core/src/auth/bitbucket-oauth.d.ts +11 -0
  99. package/dist/server-core/src/auth/discord-oauth.d.ts +14 -0
  100. package/dist/server-core/src/auth/facebook-oauth.d.ts +14 -0
  101. package/dist/server-core/src/auth/github-oauth.d.ts +15 -0
  102. package/dist/server-core/src/auth/gitlab-oauth.d.ts +13 -0
  103. package/dist/server-core/src/auth/google-oauth.d.ts +14 -0
  104. package/dist/server-core/src/auth/index.d.ts +23 -0
  105. package/dist/server-core/src/auth/interfaces.d.ts +309 -0
  106. package/dist/server-core/src/auth/jwt.d.ts +43 -0
  107. package/dist/server-core/src/auth/linkedin-oauth.d.ts +18 -0
  108. package/dist/server-core/src/auth/microsoft-oauth.d.ts +16 -0
  109. package/dist/server-core/src/auth/middleware.d.ts +81 -0
  110. package/dist/server-core/src/auth/password.d.ts +22 -0
  111. package/dist/server-core/src/auth/rate-limiter.d.ts +31 -0
  112. package/dist/server-core/src/auth/routes.d.ts +27 -0
  113. package/dist/server-core/src/auth/slack-oauth.d.ts +12 -0
  114. package/dist/server-core/src/auth/spotify-oauth.d.ts +12 -0
  115. package/dist/server-core/src/auth/twitter-oauth.d.ts +18 -0
  116. package/dist/server-core/src/bootstrappers/index.d.ts +0 -0
  117. package/dist/server-core/src/collections/BackendCollectionRegistry.d.ts +13 -0
  118. package/dist/server-core/src/collections/loader.d.ts +5 -0
  119. package/dist/server-core/src/cron/cron-loader.d.ts +17 -0
  120. package/dist/server-core/src/cron/cron-routes.d.ts +14 -0
  121. package/dist/server-core/src/cron/cron-scheduler.d.ts +61 -0
  122. package/dist/server-core/src/cron/cron-store.d.ts +32 -0
  123. package/dist/server-core/src/cron/index.d.ts +6 -0
  124. package/dist/server-core/src/db/interfaces.d.ts +18 -0
  125. package/dist/server-core/src/email/index.d.ts +6 -0
  126. package/dist/server-core/src/email/smtp-email-service.d.ts +25 -0
  127. package/dist/server-core/src/email/templates.d.ts +42 -0
  128. package/dist/server-core/src/email/types.d.ts +107 -0
  129. package/dist/server-core/src/functions/function-loader.d.ts +17 -0
  130. package/dist/server-core/src/functions/function-routes.d.ts +10 -0
  131. package/dist/server-core/src/functions/index.d.ts +3 -0
  132. package/dist/server-core/src/history/history-routes.d.ts +23 -0
  133. package/dist/server-core/src/history/index.d.ts +1 -0
  134. package/dist/server-core/src/index.d.ts +29 -0
  135. package/dist/server-core/src/init.d.ts +159 -0
  136. package/dist/server-core/src/serve-spa.d.ts +30 -0
  137. package/dist/server-core/src/services/driver-registry.d.ts +78 -0
  138. package/dist/server-core/src/singleton.d.ts +35 -0
  139. package/dist/server-core/src/storage/LocalStorageController.d.ts +46 -0
  140. package/dist/server-core/src/storage/S3StorageController.d.ts +36 -0
  141. package/dist/server-core/src/storage/index.d.ts +25 -0
  142. package/dist/server-core/src/storage/routes.d.ts +38 -0
  143. package/dist/server-core/src/storage/storage-registry.d.ts +78 -0
  144. package/dist/server-core/src/storage/types.d.ts +103 -0
  145. package/dist/server-core/src/types/index.d.ts +11 -0
  146. package/dist/server-core/src/utils/dev-port.d.ts +35 -0
  147. package/dist/server-core/src/utils/logger.d.ts +31 -0
  148. package/dist/server-core/src/utils/logging.d.ts +9 -0
  149. package/dist/server-core/src/utils/request-logger.d.ts +19 -0
  150. package/dist/server-core/src/utils/sql.d.ts +27 -0
  151. package/dist/types/src/controllers/analytics_controller.d.ts +7 -0
  152. package/dist/types/src/controllers/auth.d.ts +119 -0
  153. package/dist/types/src/controllers/client.d.ts +170 -0
  154. package/dist/types/src/controllers/collection_registry.d.ts +45 -0
  155. package/dist/types/src/controllers/customization_controller.d.ts +60 -0
  156. package/dist/types/src/controllers/data.d.ts +168 -0
  157. package/dist/types/src/controllers/data_driver.d.ts +160 -0
  158. package/dist/types/src/controllers/database_admin.d.ts +11 -0
  159. package/dist/types/src/controllers/dialogs_controller.d.ts +36 -0
  160. package/dist/types/src/controllers/effective_role.d.ts +4 -0
  161. package/dist/types/src/controllers/email.d.ts +34 -0
  162. package/dist/types/src/controllers/index.d.ts +18 -0
  163. package/dist/types/src/controllers/local_config_persistence.d.ts +20 -0
  164. package/dist/types/src/controllers/navigation.d.ts +213 -0
  165. package/dist/types/src/controllers/registry.d.ts +54 -0
  166. package/dist/types/src/controllers/side_dialogs_controller.d.ts +67 -0
  167. package/dist/types/src/controllers/side_entity_controller.d.ts +90 -0
  168. package/dist/types/src/controllers/snackbar.d.ts +24 -0
  169. package/dist/types/src/controllers/storage.d.ts +171 -0
  170. package/dist/types/src/index.d.ts +4 -0
  171. package/dist/types/src/rebase_context.d.ts +105 -0
  172. package/dist/types/src/types/backend.d.ts +536 -0
  173. package/dist/types/src/types/builders.d.ts +15 -0
  174. package/dist/types/src/types/chips.d.ts +5 -0
  175. package/dist/types/src/types/collections.d.ts +856 -0
  176. package/dist/types/src/types/cron.d.ts +102 -0
  177. package/dist/types/src/types/data_source.d.ts +64 -0
  178. package/dist/types/src/types/entities.d.ts +145 -0
  179. package/dist/types/src/types/entity_actions.d.ts +98 -0
  180. package/dist/types/src/types/entity_callbacks.d.ts +173 -0
  181. package/dist/types/src/types/entity_link_builder.d.ts +7 -0
  182. package/dist/types/src/types/entity_overrides.d.ts +10 -0
  183. package/dist/types/src/types/entity_views.d.ts +61 -0
  184. package/dist/types/src/types/export_import.d.ts +21 -0
  185. package/dist/types/src/types/index.d.ts +23 -0
  186. package/dist/types/src/types/locales.d.ts +4 -0
  187. package/dist/types/src/types/modify_collections.d.ts +5 -0
  188. package/dist/types/src/types/plugins.d.ts +279 -0
  189. package/dist/types/src/types/properties.d.ts +1176 -0
  190. package/dist/types/src/types/property_config.d.ts +70 -0
  191. package/dist/types/src/types/relations.d.ts +336 -0
  192. package/dist/types/src/types/slots.d.ts +252 -0
  193. package/dist/types/src/types/translations.d.ts +870 -0
  194. package/dist/types/src/types/user_management_delegate.d.ts +121 -0
  195. package/dist/types/src/types/websockets.d.ts +78 -0
  196. package/dist/types/src/users/index.d.ts +2 -0
  197. package/dist/types/src/users/roles.d.ts +22 -0
  198. package/dist/types/src/users/user.d.ts +46 -0
  199. package/history_diff.log +385 -0
  200. package/jest.config.cjs +16 -0
  201. package/package.json +86 -0
  202. package/scratch.ts +9 -0
  203. package/src/api/ast-schema-editor.ts +289 -0
  204. package/src/api/collections_for_test/callbacks_test_collection.ts +60 -0
  205. package/src/api/errors.ts +179 -0
  206. package/src/api/graphql/graphql-schema-generator.ts +336 -0
  207. package/src/api/graphql/index.ts +2 -0
  208. package/src/api/index.ts +11 -0
  209. package/src/api/openapi-generator.ts +715 -0
  210. package/src/api/rest/api-generator.ts +472 -0
  211. package/src/api/rest/index.ts +2 -0
  212. package/src/api/rest/query-parser.ts +155 -0
  213. package/src/api/schema-editor-routes.ts +41 -0
  214. package/src/api/server.ts +248 -0
  215. package/src/api/types.ts +90 -0
  216. package/src/auth/admin-routes.ts +529 -0
  217. package/src/auth/apple-oauth.ts +130 -0
  218. package/src/auth/bitbucket-oauth.ts +82 -0
  219. package/src/auth/discord-oauth.ts +83 -0
  220. package/src/auth/facebook-oauth.ts +72 -0
  221. package/src/auth/github-oauth.ts +110 -0
  222. package/src/auth/gitlab-oauth.ts +70 -0
  223. package/src/auth/google-oauth.ts +48 -0
  224. package/src/auth/index.ts +34 -0
  225. package/src/auth/interfaces.ts +363 -0
  226. package/src/auth/jwt.ts +181 -0
  227. package/src/auth/linkedin-oauth.ts +81 -0
  228. package/src/auth/microsoft-oauth.ts +88 -0
  229. package/src/auth/middleware.ts +384 -0
  230. package/src/auth/password.ts +77 -0
  231. package/src/auth/rate-limiter.ts +129 -0
  232. package/src/auth/routes.ts +788 -0
  233. package/src/auth/slack-oauth.ts +71 -0
  234. package/src/auth/spotify-oauth.ts +67 -0
  235. package/src/auth/twitter-oauth.ts +120 -0
  236. package/src/bootstrappers/index.ts +1 -0
  237. package/src/collections/BackendCollectionRegistry.ts +20 -0
  238. package/src/collections/loader.ts +49 -0
  239. package/src/cron/cron-loader.ts +89 -0
  240. package/src/cron/cron-routes.test.ts +265 -0
  241. package/src/cron/cron-routes.ts +85 -0
  242. package/src/cron/cron-scheduler.test.ts +421 -0
  243. package/src/cron/cron-scheduler.ts +413 -0
  244. package/src/cron/cron-store.ts +163 -0
  245. package/src/cron/index.ts +6 -0
  246. package/src/db/interfaces.ts +60 -0
  247. package/src/email/index.ts +18 -0
  248. package/src/email/smtp-email-service.ts +91 -0
  249. package/src/email/templates.ts +388 -0
  250. package/src/email/types.ts +105 -0
  251. package/src/functions/function-loader.ts +119 -0
  252. package/src/functions/function-routes.ts +31 -0
  253. package/src/functions/index.ts +3 -0
  254. package/src/history/history-routes.ts +129 -0
  255. package/src/history/index.ts +2 -0
  256. package/src/index.ts +66 -0
  257. package/src/init.ts +727 -0
  258. package/src/serve-spa.ts +81 -0
  259. package/src/services/driver-registry.ts +182 -0
  260. package/src/singleton.test.ts +28 -0
  261. package/src/singleton.ts +70 -0
  262. package/src/storage/LocalStorageController.ts +365 -0
  263. package/src/storage/S3StorageController.ts +298 -0
  264. package/src/storage/index.ts +43 -0
  265. package/src/storage/routes.ts +264 -0
  266. package/src/storage/storage-registry.ts +187 -0
  267. package/src/storage/types.ts +134 -0
  268. package/src/types/index.ts +27 -0
  269. package/src/utils/dev-port.ts +176 -0
  270. package/src/utils/logger.ts +143 -0
  271. package/src/utils/logging.ts +38 -0
  272. package/src/utils/request-logger.ts +66 -0
  273. package/src/utils/sql.ts +38 -0
  274. package/test/admin-routes.test.ts +640 -0
  275. package/test/api-generator.test.ts +501 -0
  276. package/test/ast-schema-editor.test.ts +63 -0
  277. package/test/auth-middleware-hono.test.ts +556 -0
  278. package/test/auth-routes.test.ts +1047 -0
  279. package/test/driver-registry.test.ts +282 -0
  280. package/test/error-propagation.test.ts +226 -0
  281. package/test/errors-hono.test.ts +133 -0
  282. package/test/errors.test.ts +155 -0
  283. package/test/jwt-security.test.ts +182 -0
  284. package/test/jwt.test.ts +324 -0
  285. package/test/middleware.test.ts +300 -0
  286. package/test/password.test.ts +165 -0
  287. package/test/query-parser.test.ts +263 -0
  288. package/test/rate-limiter.test.ts +102 -0
  289. package/test/safe-compare.test.ts +66 -0
  290. package/test/singleton.test.ts +59 -0
  291. package/test/storage-local.test.ts +271 -0
  292. package/test/storage-registry.test.ts +282 -0
  293. package/test/storage-routes.test.ts +222 -0
  294. package/test/storage-s3.test.ts +304 -0
  295. package/test-ast.ts +28 -0
  296. package/test.ts +6 -0
  297. package/test_output.txt +1133 -0
  298. package/tsconfig.json +49 -0
  299. package/tsconfig.prod.json +20 -0
  300. package/vite.config.ts +80 -0
@@ -0,0 +1,640 @@
1
+ /**
2
+ * Admin Routes — Integration Tests (Hono)
3
+ *
4
+ * Tests the full Hono request → admin route handler → JSON response cycle.
5
+ * Replaces the previous Express-based mock tests that only tested service calls.
6
+ */
7
+
8
+ import { Hono } from "hono";
9
+ import type { HonoEnv } from "../src/api/types";
10
+ import { errorHandler } from "../src/api/errors";
11
+ import { createAdminRoutes } from "../src/auth/admin-routes";
12
+ import { configureJwt, generateAccessToken } from "../src/auth/jwt";
13
+ import type { AuthModuleConfig } from "../src/auth/routes";
14
+
15
+ // ── Mocks ───────────────────────────────────────────────────────────────────
16
+
17
+ jest.mock("../src/auth/password");
18
+
19
+ import { UserService, RoleService } from "../src/auth/services";
20
+ import { hashPassword, validatePasswordStrength } from "../src/auth/password";
21
+
22
+ // ── Helpers ─────────────────────────────────────────────────────────────────
23
+
24
+ const TEST_SECRET = "admin-test-secret-key-that-is-definitely-32-chars-long!!!!!";
25
+
26
+ function mockUser(overrides: Partial<{ id: string; email: string; displayName: string | null; photoUrl: string | null; provider: string }> = {}) {
27
+ return {
28
+ id: overrides.id ?? "user-1",
29
+ email: overrides.email ?? "test@example.com",
30
+ passwordHash: "salt:hash",
31
+ displayName: overrides.displayName ?? "Test User",
32
+ photoUrl: overrides.photoUrl ?? null,
33
+ emailVerified: false,
34
+ emailVerificationToken: null,
35
+ emailVerificationSentAt: null,
36
+ createdAt: new Date("2024-01-01"),
37
+ updatedAt: new Date("2024-01-01")
38
+ };
39
+ }
40
+
41
+ function mockRole(id: string, isAdmin = false) {
42
+ return { id,
43
+ name: id.charAt(0).toUpperCase() + id.slice(1),
44
+ isAdmin,
45
+ defaultPermissions: null,
46
+ collectionPermissions: null,
47
+ config: null };
48
+ }
49
+
50
+
51
+ let mockAuthRepo: jest.Mocked<any>;
52
+
53
+ function createApp(opts: { defaultRole?: string } = {}) {
54
+ mockAuthRepo = {
55
+ getUserByEmail: jest.fn().mockResolvedValue(null),
56
+ getUserByIdentity: jest.fn().mockResolvedValue(null),
57
+ linkUserIdentity: jest.fn().mockResolvedValue(undefined),
58
+ getUserIdentities: jest.fn().mockResolvedValue([]),
59
+ getUserById: jest.fn().mockResolvedValue(null),
60
+ createUser: jest.fn().mockImplementation((data) =>
61
+ Promise.resolve(mockUser({ email: data.email,
62
+ displayName: data.displayName,
63
+ passwordHash: data.passwordHash }))
64
+ ),
65
+ listUsers: jest.fn().mockResolvedValue([]),
66
+ getUserRoles: jest.fn().mockResolvedValue([mockRole("editor")]),
67
+ getUserRoleIds: jest.fn().mockResolvedValue(["editor"]),
68
+ assignDefaultRole: jest.fn().mockResolvedValue(undefined),
69
+ setUserRoles: jest.fn().mockResolvedValue(undefined),
70
+ updateUser: jest.fn().mockImplementation((id, data) =>
71
+ Promise.resolve(mockUser({ id,
72
+ ...data }))
73
+ ),
74
+ deleteUser: jest.fn().mockResolvedValue(undefined),
75
+ updatePassword: jest.fn().mockResolvedValue(undefined),
76
+ setEmailVerified: jest.fn().mockResolvedValue(undefined),
77
+ setVerificationToken: jest.fn().mockResolvedValue(undefined),
78
+ getUserByVerificationToken: jest.fn().mockResolvedValue(null),
79
+ getUserWithRoles: jest.fn().mockImplementation(async (userId) => {
80
+ const user = mockUser({ id: userId });
81
+ return { user,
82
+ roles: [mockRole("editor")] };
83
+ }),
84
+ createRefreshToken: jest.fn().mockResolvedValue(undefined),
85
+ findRefreshTokenByHash: jest.fn().mockResolvedValue(null),
86
+ deleteRefreshToken: jest.fn().mockResolvedValue(undefined),
87
+ deleteAllRefreshTokensForUser: jest.fn().mockResolvedValue(undefined),
88
+ listRefreshTokensForUser: jest.fn().mockResolvedValue([]),
89
+ deleteRefreshTokenById: jest.fn().mockResolvedValue(undefined),
90
+ createPasswordResetToken: jest.fn().mockResolvedValue(undefined),
91
+ findValidPasswordResetToken: jest.fn().mockResolvedValue(null),
92
+ markPasswordResetTokenUsed: jest.fn().mockResolvedValue(undefined),
93
+ deleteExpiredPasswordResetTokens: jest.fn().mockResolvedValue(undefined),
94
+ listRoles: jest.fn().mockResolvedValue([]),
95
+ getRoleById: jest.fn().mockResolvedValue(null),
96
+ createRole: jest.fn().mockImplementation(r => Promise.resolve({ id: r.id,
97
+ name: r.name,
98
+ isAdmin: r.isAdmin || false,
99
+ defaultPermissions: null,
100
+ collectionPermissions: null,
101
+ config: null })),
102
+ updateRole: jest.fn().mockImplementation((id, r) => Promise.resolve({ id,
103
+ name: r.name,
104
+ isAdmin: r.isAdmin || false,
105
+ defaultPermissions: null,
106
+ collectionPermissions: null,
107
+ config: null })),
108
+ deleteRole: jest.fn().mockResolvedValue(undefined)
109
+ } as unknown as jest.Mocked<AuthRepository>;
110
+
111
+
112
+ // Password mocks
113
+ (validatePasswordStrength as jest.Mock).mockReturnValue({ valid: true,
114
+ errors: [] });
115
+ (hashPassword as jest.Mock).mockResolvedValue("hashed-pw");
116
+
117
+ const config: AuthModuleConfig = {
118
+ authRepo: mockAuthRepo,
119
+ defaultRole: opts.defaultRole
120
+ };
121
+
122
+ const app = new Hono<HonoEnv>();
123
+ app.onError(errorHandler);
124
+ app.route("/admin", createAdminRoutes(config));
125
+ return app;
126
+ }
127
+
128
+ function adminAuth(userId = "admin-1") {
129
+ return { Authorization: `Bearer ${generateAccessToken(userId, ["admin"])}` };
130
+ }
131
+
132
+ function editorAuth(userId = "editor-1") {
133
+ return { Authorization: `Bearer ${generateAccessToken(userId, ["editor"])}` };
134
+ }
135
+
136
+ function json(body: Record<string, unknown>) {
137
+ return {
138
+ method: "POST" as const,
139
+ headers: { "Content-Type": "application/json" },
140
+ body: JSON.stringify(body)
141
+ };
142
+ }
143
+
144
+ // ═══════════════════════════════════════════════════════════════════════════
145
+ // TESTS
146
+ // ═══════════════════════════════════════════════════════════════════════════
147
+
148
+ describe("Admin Routes (Integration)", () => {
149
+ beforeAll(() => {
150
+ configureJwt({ secret: TEST_SECRET,
151
+ accessExpiresIn: "1h" });
152
+ });
153
+
154
+ beforeEach(() => {
155
+ jest.clearAllMocks();
156
+ });
157
+
158
+ // ── Auth barriers ───────────────────────────────────────────────────
159
+ describe("Authorization", () => {
160
+ it("returns 401 for unauthenticated requests", async () => {
161
+ const app = createApp();
162
+ const res = await app.request("/admin/users");
163
+ expect(res.status).toBe(401);
164
+ });
165
+
166
+ it("returns 403 for non-admin users on admin-only endpoints", async () => {
167
+ const app = createApp();
168
+ const res = await app.request("/admin/users", {
169
+ headers: { ...editorAuth() }
170
+ });
171
+ expect(res.status).toBe(403);
172
+ });
173
+
174
+ it("allows admin users through", async () => {
175
+ const app = createApp();
176
+ const res = await app.request("/admin/users", {
177
+ headers: { ...adminAuth() }
178
+ });
179
+ expect(res.status).toBe(200);
180
+ });
181
+
182
+ it("allows schema-admin users through", async () => {
183
+ const app = createApp();
184
+ const res = await app.request("/admin/users", {
185
+ headers: { Authorization: `Bearer ${generateAccessToken("sa-1", ["schema-admin"])}` }
186
+ });
187
+ expect(res.status).toBe(200);
188
+ });
189
+ });
190
+
191
+ // ── Bootstrap ───────────────────────────────────────────────────────
192
+ describe("POST /admin/bootstrap", () => {
193
+ it("promotes current user to admin when no admins exist", async () => {
194
+ const app = createApp();
195
+ mockAuthRepo.listUsers.mockResolvedValueOnce([mockUser({ id: "user-1" })]);
196
+ mockAuthRepo.getUserRoleIds.mockResolvedValueOnce(["editor"]); // no admin
197
+
198
+ const res = await app.request("/admin/bootstrap", {
199
+ method: "POST",
200
+ headers: { ...adminAuth("user-1") }
201
+ });
202
+ expect(res.status).toBe(200);
203
+ const body = await res.json() as any;
204
+ expect(body.user.roles).toContain("admin");
205
+ expect(mockAuthRepo.setUserRoles).toHaveBeenCalledWith("user-1", ["admin"]);
206
+ });
207
+
208
+ it("returns 403 when admin already exists", async () => {
209
+ const app = createApp();
210
+ const adminUser = mockUser({ id: "existing-admin" });
211
+ mockAuthRepo.listUsers.mockResolvedValueOnce([adminUser]);
212
+ mockAuthRepo.getUserRoleIds.mockResolvedValueOnce(["admin"]); // admin exists
213
+
214
+ const res = await app.request("/admin/bootstrap", {
215
+ method: "POST",
216
+ headers: { ...adminAuth("user-1") }
217
+ });
218
+ expect(res.status).toBe(403);
219
+ const body = await res.json() as any;
220
+ expect(body.error.message).toContain("Admin users already exist");
221
+ });
222
+ });
223
+
224
+ // ── User CRUD ───────────────────────────────────────────────────────
225
+ describe("User Management", () => {
226
+ describe("GET /admin/users", () => {
227
+ it("returns list of users with roles", async () => {
228
+ const app = createApp();
229
+ mockAuthRepo.listUsers.mockResolvedValueOnce([
230
+ mockUser({ id: "u1",
231
+ email: "a@test.com" }),
232
+ mockUser({ id: "u2",
233
+ email: "b@test.com" })
234
+ ]);
235
+ mockAuthRepo.getUserRoleIds
236
+ .mockResolvedValueOnce(["admin"])
237
+ .mockResolvedValueOnce(["editor"]);
238
+
239
+ const res = await app.request("/admin/users", { headers: { ...adminAuth() } });
240
+ expect(res.status).toBe(200);
241
+ const body = await res.json() as any;
242
+ expect(body.users).toHaveLength(2);
243
+ expect(body.users[0].roles).toContain("admin");
244
+ expect(body.users[1].roles).toContain("editor");
245
+ });
246
+ });
247
+
248
+ describe("GET /admin/users/:userId", () => {
249
+ it("returns user with roles", async () => {
250
+ const app = createApp();
251
+ mockAuthRepo.getUserWithRoles.mockResolvedValueOnce({
252
+ user: mockUser({ id: "u1" }),
253
+ roles: [mockRole("editor"), mockRole("viewer")]
254
+ });
255
+
256
+ const res = await app.request("/admin/users/u1", { headers: { ...adminAuth() } });
257
+ expect(res.status).toBe(200);
258
+ const body = await res.json() as any;
259
+ expect(body.user.uid).toBe("u1");
260
+ expect(body.user.roles).toEqual(["editor", "viewer"]);
261
+ });
262
+
263
+ it("returns 404 for non-existent user", async () => {
264
+ const app = createApp();
265
+ mockAuthRepo.getUserWithRoles.mockResolvedValueOnce(null);
266
+
267
+ const res = await app.request("/admin/users/missing", { headers: { ...adminAuth() } });
268
+ expect(res.status).toBe(404);
269
+ });
270
+ });
271
+
272
+ describe("POST /admin/users", () => {
273
+ it("creates a new user", async () => {
274
+ const app = createApp();
275
+
276
+ const res = await app.request("/admin/users", {
277
+ ...json({ email: "new@test.com",
278
+ displayName: "New",
279
+ password: "StrongPass1",
280
+ roles: ["editor"] }),
281
+ headers: { ...json({}).headers,
282
+ ...adminAuth() }
283
+ });
284
+ expect(res.status).toBe(201);
285
+ const body = await res.json() as any;
286
+ expect(body.user.email).toBe("new@test.com");
287
+ expect(mockAuthRepo.createUser).toHaveBeenCalledWith(expect.objectContaining({
288
+ email: "new@test.com"
289
+ }));
290
+ });
291
+
292
+ it("hashes password when provided", async () => {
293
+ const app = createApp();
294
+
295
+ await app.request("/admin/users", {
296
+ ...json({ email: "pw@test.com",
297
+ password: "StrongPass1" }),
298
+ headers: { ...json({}).headers,
299
+ ...adminAuth() }
300
+ });
301
+ expect(hashPassword).toHaveBeenCalledWith("StrongPass1");
302
+ });
303
+
304
+ it("returns 400 for missing email", async () => {
305
+ const app = createApp();
306
+
307
+ const res = await app.request("/admin/users", {
308
+ ...json({ displayName: "No Email" }),
309
+ headers: { ...json({}).headers,
310
+ ...adminAuth() }
311
+ });
312
+ expect(res.status).toBe(400);
313
+ });
314
+
315
+ it("returns 409 when email already exists", async () => {
316
+ const app = createApp();
317
+ mockAuthRepo.getUserByEmail.mockResolvedValueOnce(mockUser());
318
+
319
+ const res = await app.request("/admin/users", {
320
+ ...json({ email: "existing@test.com" }),
321
+ headers: { ...json({}).headers,
322
+ ...adminAuth() }
323
+ });
324
+ expect(res.status).toBe(409);
325
+ const body = await res.json() as any;
326
+ expect(body.error.code).toBe("EMAIL_EXISTS");
327
+ });
328
+
329
+ it("returns 400 for weak password", async () => {
330
+ const app = createApp();
331
+ (validatePasswordStrength as jest.Mock).mockReturnValueOnce({ valid: false,
332
+ errors: ["Too short"] });
333
+
334
+ const res = await app.request("/admin/users", {
335
+ ...json({ email: "weak@test.com",
336
+ password: "weak" }),
337
+ headers: { ...json({}).headers,
338
+ ...adminAuth() }
339
+ });
340
+ expect(res.status).toBe(400);
341
+ const body = await res.json() as any;
342
+ expect(body.error.code).toBe("WEAK_PASSWORD");
343
+ });
344
+
345
+ it("assigns configured default role when no roles specified", async () => {
346
+ const app = createApp({ defaultRole: "editor" });
347
+
348
+ await app.request("/admin/users", {
349
+ ...json({ email: "norole@test.com" }),
350
+ headers: { ...json({}).headers,
351
+ ...adminAuth() }
352
+ });
353
+ expect(mockAuthRepo.assignDefaultRole).toHaveBeenCalledWith(expect.any(String), "editor");
354
+ });
355
+
356
+ it("does not assign a default role when not configured", async () => {
357
+ const app = createApp();
358
+
359
+ await app.request("/admin/users", {
360
+ ...json({ email: "nodefault@test.com" }),
361
+ headers: { ...json({}).headers,
362
+ ...adminAuth() }
363
+ });
364
+ expect(mockAuthRepo.assignDefaultRole).not.toHaveBeenCalled();
365
+ });
366
+
367
+ it("assigns specified roles", async () => {
368
+ const app = createApp();
369
+
370
+ await app.request("/admin/users", {
371
+ ...json({ email: "withroles@test.com",
372
+ roles: ["admin", "editor"] }),
373
+ headers: { ...json({}).headers,
374
+ ...adminAuth() }
375
+ });
376
+ expect(mockAuthRepo.setUserRoles).toHaveBeenCalledWith(expect.any(String), ["admin", "editor"]);
377
+ });
378
+ });
379
+
380
+ describe("PUT /admin/users/:userId", () => {
381
+ it("updates user profile", async () => {
382
+ const app = createApp();
383
+ mockAuthRepo.getUserById.mockResolvedValueOnce(mockUser({ id: "u1" }));
384
+ mockAuthRepo.getUserWithRoles.mockResolvedValueOnce({
385
+ user: mockUser({ id: "u1",
386
+ displayName: "Updated" }),
387
+ roles: [mockRole("editor")]
388
+ });
389
+
390
+ const res = await app.request("/admin/users/u1", {
391
+ method: "PUT",
392
+ headers: { "Content-Type": "application/json",
393
+ ...adminAuth() },
394
+ body: JSON.stringify({ displayName: "Updated" })
395
+ });
396
+ expect(res.status).toBe(200);
397
+ const body = await res.json() as any;
398
+ expect(body.user.displayName).toBe("Updated");
399
+ });
400
+
401
+ it("updates roles when specified", async () => {
402
+ const app = createApp();
403
+ mockAuthRepo.getUserById.mockResolvedValueOnce(mockUser({ id: "u1" }));
404
+ mockAuthRepo.getUserWithRoles.mockResolvedValueOnce({
405
+ user: mockUser({ id: "u1" }),
406
+ roles: [mockRole("admin")]
407
+ });
408
+
409
+ await app.request("/admin/users/u1", {
410
+ method: "PUT",
411
+ headers: { "Content-Type": "application/json",
412
+ ...adminAuth() },
413
+ body: JSON.stringify({ roles: ["admin"] })
414
+ });
415
+ expect(mockAuthRepo.setUserRoles).toHaveBeenCalledWith("u1", ["admin"]);
416
+ });
417
+
418
+ it("returns 404 for non-existent user", async () => {
419
+ const app = createApp();
420
+ mockAuthRepo.getUserById.mockResolvedValueOnce(null);
421
+
422
+ const res = await app.request("/admin/users/missing", {
423
+ method: "PUT",
424
+ headers: { "Content-Type": "application/json",
425
+ ...adminAuth() },
426
+ body: JSON.stringify({ displayName: "Updated" })
427
+ });
428
+ expect(res.status).toBe(404);
429
+ });
430
+ });
431
+
432
+ describe("DELETE /admin/users/:userId", () => {
433
+ it("deletes a user", async () => {
434
+ const app = createApp();
435
+ mockAuthRepo.getUserById.mockResolvedValueOnce(mockUser({ id: "u1" }));
436
+
437
+ const res = await app.request("/admin/users/u1", {
438
+ method: "DELETE",
439
+ headers: { ...adminAuth("admin-1") }
440
+ });
441
+ expect(res.status).toBe(200);
442
+ expect(mockAuthRepo.deleteUser).toHaveBeenCalledWith("u1");
443
+ });
444
+
445
+ it("prevents self-deletion", async () => {
446
+ const app = createApp();
447
+
448
+ const res = await app.request("/admin/users/admin-1", {
449
+ method: "DELETE",
450
+ headers: { ...adminAuth("admin-1") }
451
+ });
452
+ expect(res.status).toBe(400);
453
+ const body = await res.json() as any;
454
+ expect(body.error.code).toBe("SELF_DELETE");
455
+ });
456
+
457
+ it("returns 404 for non-existent user", async () => {
458
+ const app = createApp();
459
+ mockAuthRepo.getUserById.mockResolvedValueOnce(null);
460
+
461
+ const res = await app.request("/admin/users/missing", {
462
+ method: "DELETE",
463
+ headers: { ...adminAuth() }
464
+ });
465
+ expect(res.status).toBe(404);
466
+ });
467
+ });
468
+ });
469
+
470
+ // ── Role CRUD ───────────────────────────────────────────────────────
471
+ describe("Role Management", () => {
472
+ describe("GET /admin/roles", () => {
473
+ it("returns list of roles", async () => {
474
+ const app = createApp();
475
+ mockAuthRepo.listRoles.mockResolvedValueOnce([
476
+ mockRole("admin", true),
477
+ mockRole("editor"),
478
+ mockRole("viewer")
479
+ ]);
480
+
481
+ const res = await app.request("/admin/roles", { headers: { ...adminAuth() } });
482
+ expect(res.status).toBe(200);
483
+ const body = await res.json() as any;
484
+ expect(body.roles).toHaveLength(3);
485
+ expect(body.roles[0].isAdmin).toBe(true);
486
+ });
487
+ });
488
+
489
+ describe("GET /admin/roles/:roleId", () => {
490
+ it("returns role by ID", async () => {
491
+ const app = createApp();
492
+ mockAuthRepo.getRoleById.mockResolvedValueOnce(mockRole("admin", true));
493
+
494
+ const res = await app.request("/admin/roles/admin", { headers: { ...adminAuth() } });
495
+ expect(res.status).toBe(200);
496
+ const body = await res.json() as any;
497
+ expect(body.role.id).toBe("admin");
498
+ expect(body.role.isAdmin).toBe(true);
499
+ });
500
+
501
+ it("returns 404 for non-existent role", async () => {
502
+ const app = createApp();
503
+ mockAuthRepo.getRoleById.mockResolvedValueOnce(null);
504
+
505
+ const res = await app.request("/admin/roles/missing", { headers: { ...adminAuth() } });
506
+ expect(res.status).toBe(404);
507
+ });
508
+ });
509
+
510
+ describe("POST /admin/roles", () => {
511
+ it("creates a new role", async () => {
512
+ const app = createApp();
513
+
514
+ const res = await app.request("/admin/roles", {
515
+ ...json({ id: "custom",
516
+ name: "Custom Role" }),
517
+ headers: { ...json({}).headers,
518
+ ...adminAuth() }
519
+ });
520
+ expect(res.status).toBe(201);
521
+ const body = await res.json() as any;
522
+ expect(body.role.id).toBe("custom");
523
+ });
524
+
525
+ it("returns 400 for missing id or name", async () => {
526
+ const app = createApp();
527
+
528
+ const res = await app.request("/admin/roles", {
529
+ ...json({ id: "nope" }),
530
+ headers: { ...json({}).headers,
531
+ ...adminAuth() }
532
+ });
533
+ expect(res.status).toBe(400);
534
+ });
535
+
536
+ it("returns 409 when role already exists", async () => {
537
+ const app = createApp();
538
+ mockAuthRepo.getRoleById.mockResolvedValueOnce(mockRole("custom"));
539
+
540
+ const res = await app.request("/admin/roles", {
541
+ ...json({ id: "custom",
542
+ name: "Dup" }),
543
+ headers: { ...json({}).headers,
544
+ ...adminAuth() }
545
+ });
546
+ expect(res.status).toBe(409);
547
+ const body = await res.json() as any;
548
+ expect(body.error.code).toBe("ROLE_EXISTS");
549
+ });
550
+ });
551
+
552
+ describe("PUT /admin/roles/:roleId", () => {
553
+ it("updates an existing role", async () => {
554
+ const app = createApp();
555
+ mockAuthRepo.getRoleById.mockResolvedValueOnce(mockRole("editor"));
556
+
557
+ const res = await app.request("/admin/roles/editor", {
558
+ method: "PUT",
559
+ headers: { "Content-Type": "application/json",
560
+ ...adminAuth() },
561
+ body: JSON.stringify({ name: "Super Editor" })
562
+ });
563
+ expect(res.status).toBe(200);
564
+ expect(mockAuthRepo.updateRole).toHaveBeenCalledWith("editor", expect.objectContaining({
565
+ name: "Super Editor"
566
+ }));
567
+ });
568
+
569
+ it("returns 404 for non-existent role", async () => {
570
+ const app = createApp();
571
+ mockAuthRepo.getRoleById.mockResolvedValueOnce(null);
572
+
573
+ const res = await app.request("/admin/roles/missing", {
574
+ method: "PUT",
575
+ headers: { "Content-Type": "application/json",
576
+ ...adminAuth() },
577
+ body: JSON.stringify({ name: "Nope" })
578
+ });
579
+ expect(res.status).toBe(404);
580
+ });
581
+ });
582
+
583
+ describe("DELETE /admin/roles/:roleId", () => {
584
+ it("deletes a custom role", async () => {
585
+ const app = createApp();
586
+ mockAuthRepo.getRoleById.mockResolvedValueOnce(mockRole("custom"));
587
+
588
+ const res = await app.request("/admin/roles/custom", {
589
+ method: "DELETE",
590
+ headers: { ...adminAuth() }
591
+ });
592
+ expect(res.status).toBe(200);
593
+ expect(mockAuthRepo.deleteRole).toHaveBeenCalledWith("custom");
594
+ });
595
+
596
+ it("prevents deletion of built-in admin role", async () => {
597
+ const app = createApp();
598
+
599
+ const res = await app.request("/admin/roles/admin", {
600
+ method: "DELETE",
601
+ headers: { ...adminAuth() }
602
+ });
603
+ expect(res.status).toBe(400);
604
+ const body = await res.json() as any;
605
+ expect(body.error.code).toBe("BUILTIN_ROLE");
606
+ });
607
+
608
+ it("prevents deletion of built-in editor role", async () => {
609
+ const app = createApp();
610
+
611
+ const res = await app.request("/admin/roles/editor", {
612
+ method: "DELETE",
613
+ headers: { ...adminAuth() }
614
+ });
615
+ expect(res.status).toBe(400);
616
+ });
617
+
618
+ it("prevents deletion of built-in viewer role", async () => {
619
+ const app = createApp();
620
+
621
+ const res = await app.request("/admin/roles/viewer", {
622
+ method: "DELETE",
623
+ headers: { ...adminAuth() }
624
+ });
625
+ expect(res.status).toBe(400);
626
+ });
627
+
628
+ it("returns 404 for non-existent role", async () => {
629
+ const app = createApp();
630
+ mockAuthRepo.getRoleById.mockResolvedValueOnce(null);
631
+
632
+ const res = await app.request("/admin/roles/ghost", {
633
+ method: "DELETE",
634
+ headers: { ...adminAuth() }
635
+ });
636
+ expect(res.status).toBe(404);
637
+ });
638
+ });
639
+ });
640
+ });