@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,302 +0,0 @@
1
- /**
2
- * Standalone admin endpoint for user management.
3
- *
4
- * Mounts:
5
- * GET /users
6
- * GET /users/:userId
7
- * POST /users
8
- * PUT /users/:userId
9
- * DELETE /users/:userId
10
- * POST /bootstrap
11
- */
12
-
13
- import { Hono } from "hono";
14
- import { ApiError, errorHandler } from "../api/errors";
15
- import type { AuthRepository } from "./interfaces";
16
- import { createRequireAuth, requireAdmin } from "./middleware";
17
- import type { AuthHooks } from "./auth-hooks";
18
- import { resolveAuthHooks } from "./auth-hooks";
19
- import { prepareAdminUserValues, finalizeAdminUserCreation } from "./admin-user-ops";
20
- import type { EmailService, EmailConfig } from "../email";
21
- import type { HonoEnv } from "../api/types";
22
- import type { AdminUser, AuthCollectionConfig } from "@rebasepro/types";
23
- import { logger } from "../utils/logger";
24
-
25
- export interface AdminUsersRouteConfig {
26
- authRepo: AuthRepository;
27
- emailService?: EmailService;
28
- emailConfig?: EmailConfig;
29
- serviceKey?: string;
30
- authHooks?: AuthHooks;
31
- collectionAuthConfig?: AuthCollectionConfig;
32
- isBootstrapCompleted?: () => Promise<boolean>;
33
- setBootstrapCompleted?: () => Promise<void>;
34
- }
35
-
36
- export function createAdminUsersRoute(config: AdminUsersRouteConfig): Hono<HonoEnv> {
37
- const router = new Hono<HonoEnv>();
38
- const authRepo = config.authRepo;
39
- const { emailService, emailConfig, collectionAuthConfig } = config;
40
- const ops = resolveAuthHooks(config.authHooks);
41
-
42
- function toAdminUser(
43
- u: {
44
- id: string;
45
- email: string;
46
- displayName?: string | null;
47
- photoUrl?: string | null;
48
- createdAt?: Date | string;
49
- updatedAt?: Date | string;
50
- },
51
- roles: string[]
52
- ): AdminUser {
53
- return {
54
- uid: u.id,
55
- email: u.email,
56
- displayName: u.displayName ?? null,
57
- photoURL: u.photoUrl ?? null,
58
- provider: "custom",
59
- roles,
60
- createdAt: u.createdAt instanceof Date ? u.createdAt.toISOString() : (u.createdAt ?? new Date().toISOString()),
61
- updatedAt: u.updatedAt instanceof Date ? u.updatedAt.toISOString() : (u.updatedAt ?? new Date().toISOString())
62
- };
63
- }
64
-
65
- router.onError(errorHandler);
66
- router.use("/*", createRequireAuth({ serviceKey: config.serviceKey }));
67
-
68
- router.post("/bootstrap", async (c) => {
69
- const user = c.get("user");
70
- if (!user || typeof user !== "object") {
71
- throw ApiError.unauthorized("Not authenticated");
72
- }
73
-
74
- if (config.isBootstrapCompleted) {
75
- const alreadyDone = await config.isBootstrapCompleted();
76
- if (alreadyDone) {
77
- throw ApiError.forbidden("Bootstrap has already been completed.", "BOOTSTRAP_COMPLETED");
78
- }
79
- }
80
-
81
- const users = await authRepo.listUsers();
82
- let hasAdmin = false;
83
-
84
- for (const u of users) {
85
- const roles = await authRepo.getUserRoleIds(u.id);
86
- if (roles.includes("admin")) {
87
- hasAdmin = true;
88
- break;
89
- }
90
- }
91
-
92
- if (hasAdmin) {
93
- throw ApiError.forbidden("Admin users already exist. Bootstrap not allowed.", "BOOTSTRAP_COMPLETED");
94
- }
95
-
96
- const userId = "userId" in user ? (user as { userId: string }).userId : ("uid" in user ? (user as { uid: string }).uid : undefined);
97
- if (!userId) {
98
- throw ApiError.unauthorized("User ID not found in auth context");
99
- }
100
- const caller = await authRepo.getUserById(userId);
101
- if (!caller) {
102
- throw ApiError.notFound("Authenticated user does not exist in the database.", "USER_NOT_FOUND");
103
- }
104
- await authRepo.setUserRoles(userId, ["admin"]);
105
-
106
- if (config.setBootstrapCompleted) {
107
- await config.setBootstrapCompleted();
108
- }
109
-
110
- return c.json({
111
- success: true,
112
- message: "You are now an admin",
113
- user: {
114
- uid: userId,
115
- roles: ["admin"]
116
- }
117
- });
118
- });
119
-
120
- router.get("/users", requireAdmin, async (c) => {
121
- const limitParam = c.req.query("limit");
122
- const offsetParam = c.req.query("offset");
123
- const search = c.req.query("search");
124
- const orderBy = c.req.query("orderBy");
125
- const orderDir = c.req.query("orderDir") as "asc" | "desc" | undefined;
126
-
127
- const limit = limitParam ? parseInt(limitParam, 10) : 25;
128
- const offset = offsetParam ? parseInt(offsetParam, 10) : 0;
129
-
130
- const result = await authRepo.listUsersPaginated({
131
- limit,
132
- offset,
133
- search: search || undefined,
134
- orderBy: orderBy || undefined,
135
- orderDir: orderDir || undefined,
136
- roleId: c.req.query("role") || undefined
137
- });
138
-
139
- const usersWithRoles = await Promise.all(
140
- result.users.map(async (u) => {
141
- const roles = await authRepo.getUserRoleIds(u.id);
142
- return toAdminUser(u, roles);
143
- })
144
- );
145
-
146
- return c.json({
147
- users: usersWithRoles,
148
- total: result.total,
149
- limit: result.limit,
150
- offset: result.offset
151
- });
152
- });
153
-
154
- router.get("/users/:userId", requireAdmin, async (c) => {
155
- const userId = c.req.param("userId");
156
- const result = await authRepo.getUserWithRoles(userId);
157
-
158
- if (!result) {
159
- throw ApiError.notFound("User not found");
160
- }
161
-
162
- const adminUser = toAdminUser(result.user, result.roles.map((r) => r.id));
163
- return c.json({ user: adminUser });
164
- });
165
-
166
- router.post("/users", requireAdmin, async (c) => {
167
- const body = await c.req.json();
168
- const { email, roles } = body;
169
- if (!email) {
170
- throw ApiError.badRequest("Email is required");
171
- }
172
-
173
- const existing = await authRepo.getUserByEmail(email.toLowerCase());
174
- if (existing) {
175
- throw ApiError.conflict("A user with this email already exists");
176
- }
177
-
178
- const prepResult = await prepareAdminUserValues(body, {
179
- authRepo,
180
- emailService,
181
- emailConfig,
182
- resolvedHooks: ops,
183
- collectionAuthConfig
184
- });
185
-
186
- const user = await authRepo.createUser({
187
- email: prepResult.values.email as string,
188
- passwordHash: prepResult.values.passwordHash as string | undefined,
189
- displayName: prepResult.values.displayName as string | undefined,
190
- photoUrl: prepResult.values.photoUrl as string | undefined,
191
- metadata: prepResult.values.metadata as Record<string, unknown> | undefined
192
- });
193
-
194
- if (roles && Array.isArray(roles)) {
195
- await authRepo.setUserRoles(user.id, roles);
196
- }
197
-
198
- const finalizeResult = await finalizeAdminUserCreation(
199
- { id: user.id, values: prepResult.values },
200
- prepResult.clearPassword,
201
- {
202
- authRepo,
203
- emailService,
204
- emailConfig,
205
- resolvedHooks: ops,
206
- collectionAuthConfig
207
- }
208
- );
209
-
210
- const userRoles = await authRepo.getUserRoleIds(user.id);
211
- const adminUser = toAdminUser(user, userRoles);
212
-
213
- return c.json(
214
- {
215
- user: adminUser,
216
- invitationSent: finalizeResult.invitationSent,
217
- ...(finalizeResult.temporaryPassword ? { temporaryPassword: finalizeResult.temporaryPassword } : {})
218
- },
219
- 201
220
- );
221
- });
222
-
223
- router.put("/users/:userId", requireAdmin, async (c) => {
224
- const userId = c.req.param("userId");
225
- const body = await c.req.json();
226
- const { password, email, displayName, roles } = body;
227
-
228
- const existing = await authRepo.getUserById(userId);
229
- if (!existing) {
230
- throw ApiError.notFound("User not found");
231
- }
232
-
233
- const updates: Record<string, unknown> = {};
234
- if (email !== undefined) updates.email = email.toLowerCase();
235
- if (displayName !== undefined) updates.displayName = displayName;
236
-
237
- if (password) {
238
- const validation = ops.validatePasswordStrength(password);
239
- if (!validation.valid) {
240
- throw ApiError.badRequest(`Password too weak: ${validation.errors.join(". ")}`);
241
- }
242
- updates.passwordHash = await ops.hashPassword(password);
243
- }
244
-
245
- if (Object.keys(updates).length > 0) {
246
- await authRepo.updateUser(userId, updates);
247
- }
248
-
249
- if (roles !== undefined && Array.isArray(roles)) {
250
- const currentRoles = await authRepo.getUserRoleIds(userId);
251
- const wasAdmin = currentRoles.includes("admin");
252
- const willBeAdmin = roles.includes("admin");
253
-
254
- if (wasAdmin && !willBeAdmin) {
255
- const adminUsers = await authRepo.listUsersPaginated({
256
- roleId: "admin",
257
- limit: 1
258
- });
259
- if (adminUsers.total <= 1) {
260
- throw ApiError.forbidden("Cannot demote the last administrator", "LAST_ADMIN");
261
- }
262
- }
263
- await authRepo.setUserRoles(userId, roles);
264
- }
265
-
266
- const result = await authRepo.getUserWithRoles(userId);
267
- const adminUser = toAdminUser(result!.user, result!.roles.map((r) => r.id));
268
-
269
- return c.json({ user: adminUser });
270
- });
271
-
272
- router.delete("/users/:userId", requireAdmin, async (c) => {
273
- const userId = c.req.param("userId");
274
- const authUser = c.get("user") as { uid?: string; userId?: string } | undefined;
275
- const currentUserId = authUser?.uid || authUser?.userId;
276
-
277
- if (currentUserId === userId) {
278
- throw ApiError.badRequest("Cannot delete your own account", "SELF_DELETE");
279
- }
280
-
281
- const existing = await authRepo.getUserById(userId);
282
- if (!existing) {
283
- throw ApiError.notFound("User not found");
284
- }
285
-
286
- const roles = await authRepo.getUserRoleIds(userId);
287
- if (roles.includes("admin")) {
288
- const adminUsers = await authRepo.listUsersPaginated({
289
- roleId: "admin",
290
- limit: 1
291
- });
292
- if (adminUsers.total <= 1) {
293
- throw ApiError.forbidden("Cannot delete the last administrator", "LAST_ADMIN");
294
- }
295
- }
296
-
297
- await authRepo.deleteUser(userId);
298
- return c.json({ success: true });
299
- });
300
-
301
- return router;
302
- }
@@ -1,133 +0,0 @@
1
- /**
2
- * Hono middleware for authenticating requests via Service API Keys.
3
- *
4
- * This middleware is integrated into `createAuthMiddleware()` and
5
- * activates only when the bearer token starts with `rk_`. It:
6
- *
7
- * 1. Hashes the token with SHA-256
8
- * 2. Looks up the hash in the `rebase.api_keys` table
9
- * 3. Validates the key is not revoked and not expired
10
- * 4. Sets `c.set("user", ...)` and `c.set("apiKey", ...)` for downstream use
11
- * 5. Scopes the DataDriver via `withAuth()` using the API key's service identity
12
- *
13
- * @module
14
- */
15
-
16
- import { createHash } from "crypto";
17
- import type { Context } from "hono";
18
- import type { DataDriver } from "@rebasepro/types";
19
- import type { HonoEnv } from "../../api/types";
20
- import type { ApiKeyStore } from "./api-key-store";
21
- import type { ApiKeyMasked } from "./api-key-types";
22
- import { scopeDataDriver } from "../rls-scope";
23
- import { logger } from "../../utils/logger";
24
-
25
- /**
26
- * Check whether a token looks like a Rebase API key.
27
- */
28
- export function isApiKeyToken(token: string): boolean {
29
- return token.startsWith("rk_");
30
- }
31
-
32
- /**
33
- * Hash a plaintext API key token for database lookup.
34
- */
35
- function hashToken(token: string): string {
36
- return createHash("sha256").update(token).digest("hex");
37
- }
38
-
39
- /**
40
- * Options for the API key authentication handler.
41
- */
42
- export interface ApiKeyAuthOptions {
43
- store: ApiKeyStore;
44
- driver: DataDriver;
45
- }
46
-
47
- /**
48
- * Validate an API key token and populate the Hono context.
49
- *
50
- * Returns `true` if the key is valid and context has been populated,
51
- * or returns an error Response if the key is invalid.
52
- *
53
- * This is NOT a standalone middleware — it's called from within
54
- * `createAuthMiddleware()` when a `rk_` prefixed token is detected.
55
- */
56
- export async function validateApiKey(
57
- c: Context<HonoEnv>,
58
- token: string,
59
- options: ApiKeyAuthOptions
60
- ): Promise<Response | true> {
61
- const { store, driver } = options;
62
-
63
- const hash = hashToken(token);
64
- const apiKey = await store.findByKeyHash(hash);
65
-
66
- if (!apiKey) {
67
- return c.json({
68
- error: { message: "Invalid API key",
69
- code: "UNAUTHORIZED" }
70
- }, 401);
71
- }
72
-
73
- // Check revocation
74
- if (apiKey.revoked_at) {
75
- return c.json({
76
- error: { message: "API key has been revoked",
77
- code: "UNAUTHORIZED" }
78
- }, 401);
79
- }
80
-
81
- // Check expiration
82
- if (apiKey.expires_at && new Date(apiKey.expires_at) < new Date()) {
83
- return c.json({
84
- error: { message: "API key has expired",
85
- code: "UNAUTHORIZED" }
86
- }, 401);
87
- }
88
-
89
- // Set user identity — API keys represent service accounts
90
- const userId = `api-key:${apiKey.id}`;
91
- const roles: string[] = apiKey.admin ? ["admin", "service"] : ["service"];
92
- c.set("user", { userId, roles });
93
-
94
- // Expose masked key metadata for downstream permission checks
95
- const masked: ApiKeyMasked = {
96
- id: apiKey.id,
97
- name: apiKey.name,
98
- key_prefix: apiKey.key_prefix,
99
- permissions: apiKey.permissions,
100
- admin: apiKey.admin,
101
- rate_limit: apiKey.rate_limit,
102
- created_by: apiKey.created_by,
103
- created_at: apiKey.created_at,
104
- updated_at: apiKey.updated_at,
105
- last_used_at: apiKey.last_used_at,
106
- expires_at: apiKey.expires_at,
107
- revoked_at: apiKey.revoked_at
108
- };
109
- // Store apiKey in the context for permission checking in api-generator
110
- c.set("apiKey", masked);
111
-
112
- // Scope the DataDriver — API keys bypass RLS (service identity)
113
- try {
114
- const scopedDriver = await scopeDataDriver(driver, {
115
- uid: userId,
116
- roles
117
- });
118
- c.set("driver", scopedDriver);
119
- } catch (error) {
120
- logger.error("[AUTH] RLS scoping failed for API key", { error: error });
121
- return c.json({
122
- error: { message: "Internal authentication error",
123
- code: "INTERNAL_ERROR" }
124
- }, 500);
125
- }
126
-
127
- // Touch last_used_at in the background (non-blocking)
128
- store.updateLastUsed(apiKey.id).catch(() => {
129
- // Swallowed intentionally — logged inside the store
130
- });
131
-
132
- return true;
133
- }
@@ -1,193 +0,0 @@
1
- /**
2
- * Admin routes for managing Service API Keys.
3
- *
4
- * Mounted under `/api/admin/api-keys` with `requireAuth` + `requireAdmin`.
5
- * All routes return masked keys (never the hash). The full plaintext key
6
- * is returned exactly once in the POST response.
7
- *
8
- * @module
9
- */
10
-
11
- import { Hono } from "hono";
12
- import { ApiError, errorHandler } from "../../api/errors";
13
- import { createRequireAuth, requireAdmin } from "../middleware";
14
- import type { HonoEnv } from "../../api/types";
15
- import type { ApiKeyStore } from "./api-key-store";
16
- import type { CreateApiKeyRequest, UpdateApiKeyRequest, ApiKeyPermission } from "./api-key-types";
17
-
18
- export interface ApiKeyRouteOptions {
19
- store: ApiKeyStore;
20
- serviceKey?: string;
21
- }
22
-
23
- /**
24
- * Validate that a permissions array is well-formed.
25
- */
26
- function validatePermissions(permissions: unknown): permissions is ApiKeyPermission[] {
27
- if (!Array.isArray(permissions)) return false;
28
- for (const perm of permissions) {
29
- if (typeof perm !== "object" || perm === null) return false;
30
- if (typeof perm.collection !== "string" || perm.collection.length === 0) return false;
31
- if (!Array.isArray(perm.operations) || perm.operations.length === 0) return false;
32
- const validOps = new Set(["read", "write", "delete"]);
33
- for (const op of perm.operations) {
34
- if (!validOps.has(op)) return false;
35
- }
36
- }
37
- return true;
38
- }
39
-
40
- /**
41
- * Create admin routes for API key management.
42
- */
43
- export function createApiKeyRoutes(options: ApiKeyRouteOptions): Hono<HonoEnv> {
44
- const { store, serviceKey } = options;
45
- const router = new Hono<HonoEnv>();
46
-
47
- router.onError(errorHandler);
48
-
49
- // Apply auth middleware (service-key-aware)
50
- router.use("/*", createRequireAuth({ serviceKey }));
51
- router.use("/*", requireAdmin);
52
-
53
- // GET / — List all API keys (masked)
54
- router.get("/", async (c) => {
55
- const keys = await store.listApiKeys();
56
- return c.json({ keys });
57
- });
58
-
59
- // POST / — Create a new API key
60
- router.post("/", async (c) => {
61
- const body = await c.req.json() as Record<string, unknown>;
62
- const { name, permissions, admin, rate_limit, expires_at } = body;
63
-
64
- if (!name || typeof name !== "string" || name.trim().length === 0) {
65
- throw ApiError.badRequest("Name is required", "INVALID_INPUT");
66
- }
67
-
68
- if (!validatePermissions(permissions)) {
69
- throw ApiError.badRequest(
70
- "Permissions must be an array of { collection: string, operations: ('read' | 'write' | 'delete')[] }",
71
- "INVALID_INPUT"
72
- );
73
- }
74
-
75
- if (admin !== undefined && typeof admin !== "boolean") {
76
- throw ApiError.badRequest("admin must be a boolean", "INVALID_INPUT");
77
- }
78
-
79
- if (rate_limit !== undefined && rate_limit !== null) {
80
- if (typeof rate_limit !== "number" || rate_limit < 1 || !Number.isInteger(rate_limit)) {
81
- throw ApiError.badRequest("rate_limit must be a positive integer or null", "INVALID_INPUT");
82
- }
83
- }
84
-
85
- if (expires_at !== undefined && expires_at !== null) {
86
- const parsed = new Date(expires_at as string);
87
- if (isNaN(parsed.getTime())) {
88
- throw ApiError.badRequest("expires_at must be a valid ISO-8601 date", "INVALID_INPUT");
89
- }
90
- if (parsed <= new Date()) {
91
- throw ApiError.badRequest("expires_at must be in the future", "INVALID_INPUT");
92
- }
93
- }
94
-
95
- const user = c.get("user");
96
- const createdBy = (user && typeof user === "object" && "userId" in user)
97
- ? (user.userId as string)
98
- : "unknown";
99
-
100
- const request: CreateApiKeyRequest = {
101
- name: name.trim(),
102
- permissions: permissions as ApiKeyPermission[],
103
- admin: (admin as boolean) ?? false,
104
- rate_limit: (rate_limit as number | null) ?? null,
105
- expires_at: (expires_at as string | null) ?? null
106
- };
107
-
108
- const keyWithSecret = await store.createApiKey(request, createdBy);
109
-
110
- return c.json({ key: keyWithSecret }, 201);
111
- });
112
-
113
- // GET /:id — Get API key details (masked)
114
- router.get("/:id", async (c) => {
115
- const id = c.req.param("id");
116
- const key = await store.getApiKeyById(id);
117
-
118
- if (!key) {
119
- throw ApiError.notFound("API key not found");
120
- }
121
-
122
- return c.json({ key });
123
- });
124
-
125
- // PUT /:id — Update API key
126
- router.put("/:id", async (c) => {
127
- const id = c.req.param("id");
128
- const body = await c.req.json() as Record<string, unknown>;
129
- const { name, permissions, admin, rate_limit, expires_at } = body;
130
-
131
- // Validate fields if provided
132
- if (name !== undefined) {
133
- if (typeof name !== "string" || name.trim().length === 0) {
134
- throw ApiError.badRequest("Name must be a non-empty string", "INVALID_INPUT");
135
- }
136
- }
137
-
138
- if (permissions !== undefined) {
139
- if (!validatePermissions(permissions)) {
140
- throw ApiError.badRequest(
141
- "Permissions must be an array of { collection: string, operations: ('read' | 'write' | 'delete')[] }",
142
- "INVALID_INPUT"
143
- );
144
- }
145
- }
146
-
147
- if (admin !== undefined && typeof admin !== "boolean") {
148
- throw ApiError.badRequest("admin must be a boolean", "INVALID_INPUT");
149
- }
150
-
151
- if (rate_limit !== undefined && rate_limit !== null) {
152
- if (typeof rate_limit !== "number" || rate_limit < 1 || !Number.isInteger(rate_limit)) {
153
- throw ApiError.badRequest("rate_limit must be a positive integer or null", "INVALID_INPUT");
154
- }
155
- }
156
-
157
- if (expires_at !== undefined && expires_at !== null) {
158
- const parsed = new Date(expires_at as string);
159
- if (isNaN(parsed.getTime())) {
160
- throw ApiError.badRequest("expires_at must be a valid ISO-8601 date", "INVALID_INPUT");
161
- }
162
- }
163
-
164
- const updates: UpdateApiKeyRequest = {};
165
- if (name !== undefined) updates.name = (name as string).trim();
166
- if (permissions !== undefined) updates.permissions = permissions as ApiKeyPermission[];
167
- if (admin !== undefined) updates.admin = admin as boolean;
168
- if (rate_limit !== undefined) updates.rate_limit = rate_limit as number | null;
169
- if (expires_at !== undefined) updates.expires_at = expires_at as string | null;
170
-
171
- const key = await store.updateApiKey(id, updates);
172
-
173
- if (!key) {
174
- throw ApiError.notFound("API key not found");
175
- }
176
-
177
- return c.json({ key });
178
- });
179
-
180
- // DELETE /:id — Revoke (soft-delete)
181
- router.delete("/:id", async (c) => {
182
- const id = c.req.param("id");
183
- const revoked = await store.revokeApiKey(id);
184
-
185
- if (!revoked) {
186
- throw ApiError.notFound("API key not found or already revoked");
187
- }
188
-
189
- return c.json({ success: true });
190
- });
191
-
192
- return router;
193
- }