@rebasepro/server-core 0.2.3 → 0.3.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 (109) hide show
  1. package/dist/common/src/collections/default-collections.d.ts +12 -0
  2. package/dist/common/src/collections/index.d.ts +1 -0
  3. package/dist/common/src/util/permissions.d.ts +1 -0
  4. package/dist/{index-BZoAtuqi.js → index-Cr1D21av.js} +11 -3
  5. package/dist/index-Cr1D21av.js.map +1 -0
  6. package/dist/index.es.js +2166 -208
  7. package/dist/index.es.js.map +1 -1
  8. package/dist/index.umd.js +2155 -193
  9. package/dist/index.umd.js.map +1 -1
  10. package/dist/server-core/src/api/logs-routes.d.ts +37 -0
  11. package/dist/server-core/src/api/rest/api-generator.d.ts +6 -0
  12. package/dist/server-core/src/api/types.d.ts +6 -1
  13. package/dist/server-core/src/auth/adapter-middleware.d.ts +7 -3
  14. package/dist/server-core/src/auth/admin-routes.d.ts +3 -3
  15. package/dist/server-core/src/auth/api-keys/api-key-middleware.d.ts +39 -0
  16. package/dist/server-core/src/auth/api-keys/api-key-permission-guard.d.ts +32 -0
  17. package/dist/server-core/src/auth/api-keys/api-key-routes.d.ts +20 -0
  18. package/dist/server-core/src/auth/api-keys/api-key-store.d.ts +35 -0
  19. package/dist/server-core/src/auth/api-keys/api-key-types.d.ts +88 -0
  20. package/dist/server-core/src/auth/api-keys/index.d.ts +17 -0
  21. package/dist/server-core/src/auth/{auth-overrides.d.ts → auth-hooks.d.ts} +69 -11
  22. package/dist/server-core/src/auth/builtin-auth-adapter.d.ts +3 -3
  23. package/dist/server-core/src/auth/index.d.ts +5 -3
  24. package/dist/server-core/src/auth/interfaces.d.ts +93 -3
  25. package/dist/server-core/src/auth/jwt.d.ts +3 -1
  26. package/dist/server-core/src/auth/mfa.d.ts +49 -0
  27. package/dist/server-core/src/auth/middleware.d.ts +7 -0
  28. package/dist/server-core/src/auth/rate-limiter.d.ts +19 -0
  29. package/dist/server-core/src/auth/routes.d.ts +3 -3
  30. package/dist/server-core/src/env.d.ts +6 -0
  31. package/dist/server-core/src/index.d.ts +1 -0
  32. package/dist/server-core/src/init.d.ts +3 -3
  33. package/dist/server-core/src/services/webhook-service.d.ts +29 -0
  34. package/dist/server-core/src/storage/image-transform.d.ts +48 -0
  35. package/dist/server-core/src/storage/index.d.ts +3 -0
  36. package/dist/server-core/src/storage/tus-handler.d.ts +51 -0
  37. package/dist/types/src/controllers/auth.d.ts +2 -24
  38. package/dist/types/src/controllers/client.d.ts +0 -3
  39. package/dist/types/src/controllers/collection_registry.d.ts +1 -1
  40. package/dist/types/src/controllers/data_driver.d.ts +18 -0
  41. package/dist/types/src/controllers/registry.d.ts +5 -4
  42. package/dist/types/src/rebase_context.d.ts +1 -1
  43. package/dist/types/src/types/auth_adapter.d.ts +2 -4
  44. package/dist/types/src/types/collections.d.ts +0 -4
  45. package/dist/types/src/types/component_ref.d.ts +1 -1
  46. package/dist/types/src/types/cron.d.ts +1 -1
  47. package/dist/types/src/types/entity_views.d.ts +1 -0
  48. package/dist/types/src/types/export_import.d.ts +1 -1
  49. package/dist/types/src/types/formex.d.ts +2 -2
  50. package/dist/types/src/types/properties.d.ts +2 -2
  51. package/dist/types/src/types/translations.d.ts +28 -12
  52. package/dist/types/src/types/user_management_delegate.d.ts +6 -4
  53. package/dist/types/src/users/roles.d.ts +0 -8
  54. package/package.json +8 -6
  55. package/src/api/ast-schema-editor.ts +4 -4
  56. package/src/api/errors.ts +16 -7
  57. package/src/api/logs-routes.ts +129 -0
  58. package/src/api/rest/api-generator.ts +42 -2
  59. package/src/api/rest/query-parser.ts +37 -1
  60. package/src/api/types.ts +6 -1
  61. package/src/auth/adapter-middleware.ts +20 -4
  62. package/src/auth/admin-routes.ts +39 -14
  63. package/src/auth/api-keys/api-key-middleware.ts +126 -0
  64. package/src/auth/api-keys/api-key-permission-guard.ts +64 -0
  65. package/src/auth/api-keys/api-key-routes.ts +183 -0
  66. package/src/auth/api-keys/api-key-store.ts +317 -0
  67. package/src/auth/api-keys/api-key-types.ts +94 -0
  68. package/src/auth/api-keys/index.ts +37 -0
  69. package/src/auth/{auth-overrides.ts → auth-hooks.ts} +81 -14
  70. package/src/auth/builtin-auth-adapter.ts +31 -19
  71. package/src/auth/index.ts +7 -3
  72. package/src/auth/interfaces.ts +111 -3
  73. package/src/auth/jwt.ts +19 -5
  74. package/src/auth/mfa.ts +160 -0
  75. package/src/auth/middleware.ts +20 -1
  76. package/src/auth/rate-limiter.ts +92 -0
  77. package/src/auth/routes.ts +455 -24
  78. package/src/cron/cron-loader.ts +5 -10
  79. package/src/cron/cron-scheduler.ts +11 -12
  80. package/src/cron/cron-store.ts +8 -7
  81. package/src/env.ts +2 -0
  82. package/src/functions/function-loader.ts +6 -9
  83. package/src/index.ts +1 -2
  84. package/src/init.ts +37 -7
  85. package/src/serve-spa.ts +5 -4
  86. package/src/services/webhook-service.ts +155 -0
  87. package/src/storage/image-transform.ts +202 -0
  88. package/src/storage/index.ts +3 -0
  89. package/src/storage/routes.ts +56 -3
  90. package/src/storage/tus-handler.ts +315 -0
  91. package/src/utils/dev-port.ts +14 -0
  92. package/src/utils/logging.ts +9 -7
  93. package/test/admin-routes.test.ts +74 -7
  94. package/test/api-generator.test.ts +0 -1
  95. package/test/api-key-permission-guard.test.ts +132 -0
  96. package/test/ast-schema-editor.test.ts +26 -0
  97. package/test/auth-routes.test.ts +1 -2
  98. package/test/backend-hooks-admin.test.ts +3 -4
  99. package/test/email-templates.test.ts +169 -0
  100. package/test/function-loader.test.ts +124 -0
  101. package/test/jwt.test.ts +4 -2
  102. package/test/mfa.test.ts +197 -0
  103. package/test/middleware.test.ts +10 -5
  104. package/test/webhook-service.test.ts +249 -0
  105. package/vite.config.ts +3 -2
  106. package/dist/index-BZoAtuqi.js.map +0 -1
  107. package/dist/server-core/src/bootstrappers/index.d.ts +0 -0
  108. package/src/bootstrappers/index.ts +0 -1
  109. package/src/singleton.test.ts +0 -28
@@ -2,8 +2,8 @@ import { Hono } from "hono";
2
2
  import { ApiError, errorHandler } from "../api/errors";
3
3
  import type { AuthRepository } from "./interfaces";
4
4
  import { requireAuth, requireAdmin, createRequireAuth } from "./middleware";
5
- import type { AuthOverrides } from "./auth-overrides";
6
- import { resolveAuthOverrides } from "./auth-overrides";
5
+ import type { AuthHooks } from "./auth-hooks";
6
+ import { resolveAuthHooks } from "./auth-hooks";
7
7
  import { AuthModuleConfig } from "./routes";
8
8
  import type { BackendHooks, AdminUser, AdminRole, BackendHookContext } from "@rebasepro/types";
9
9
 
@@ -19,10 +19,10 @@ interface AdminRouteOptions extends AuthModuleConfig {
19
19
  */
20
20
  hooks?: BackendHooks;
21
21
  /**
22
- * Auth overrides for customizing password hashing, credential
22
+ * Auth hooks for customizing password hashing, credential
23
23
  * verification, lifecycle hooks, etc.
24
24
  */
25
- overrides?: AuthOverrides;
25
+ authHooks?: AuthHooks;
26
26
  }
27
27
  import { HonoEnv } from "../api/types";
28
28
  import { randomBytes, createHash } from "crypto";
@@ -74,8 +74,8 @@ function hashToken(token: string): string {
74
74
  export function createAdminRoutes(config: AdminRouteOptions): Hono<HonoEnv> {
75
75
  const router = new Hono<HonoEnv>();
76
76
  const authRepo = config.authRepo;
77
- const { emailService, emailConfig, hooks, overrides } = config;
78
- const ops = resolveAuthOverrides(overrides);
77
+ const { emailService, emailConfig, hooks, authHooks } = config;
78
+ const ops = resolveAuthHooks(authHooks);
79
79
 
80
80
  /** Build a BackendHookContext from Hono's context object */
81
81
  function buildHookContext(c: { get: (key: string) => unknown }, method: BackendHookContext["method"]): BackendHookContext {
@@ -174,6 +174,10 @@ export function createAdminRoutes(config: AdminRouteOptions): Hono<HonoEnv> {
174
174
  if (!userId) {
175
175
  throw ApiError.unauthorized("User ID not found in auth context");
176
176
  }
177
+ const caller = await authRepo.getUserById(userId);
178
+ if (!caller) {
179
+ throw ApiError.notFound("Authenticated user does not exist in the database. Please sign out and sign in/register again.", "USER_NOT_FOUND");
180
+ }
177
181
  await authRepo.setUserRoles(userId, ["admin"]);
178
182
 
179
183
  // ── Set persistent flag ──────────────────────────────────────
@@ -456,6 +460,19 @@ displayName: existing.displayName }, appName);
456
460
  }
457
461
 
458
462
  if (roles !== undefined && Array.isArray(roles)) {
463
+ const currentRoles = await authRepo.getUserRoleIds(userId);
464
+ const wasAdmin = currentRoles.includes("admin");
465
+ const willBeAdmin = roles.includes("admin");
466
+
467
+ if (wasAdmin && !willBeAdmin) {
468
+ const adminUsers = await authRepo.listUsersPaginated({
469
+ roleId: "admin",
470
+ limit: 1
471
+ });
472
+ if (adminUsers.total <= 1) {
473
+ throw ApiError.forbidden("Cannot demote the last administrator", "LAST_ADMIN");
474
+ }
475
+ }
459
476
  await authRepo.setUserRoles(userId, roles);
460
477
  }
461
478
 
@@ -487,6 +504,17 @@ displayName: existing.displayName }, appName);
487
504
  throw ApiError.notFound("User not found");
488
505
  }
489
506
 
507
+ const roles = await authRepo.getUserRoleIds(userId);
508
+ if (roles.includes("admin")) {
509
+ const adminUsers = await authRepo.listUsersPaginated({
510
+ roleId: "admin",
511
+ limit: 1
512
+ });
513
+ if (adminUsers.total <= 1) {
514
+ throw ApiError.forbidden("Cannot delete the last administrator", "LAST_ADMIN");
515
+ }
516
+ }
517
+
490
518
  // Apply beforeDelete hook (throw to abort)
491
519
  const hookCtx = buildHookContext(c, "DELETE");
492
520
  if (hooks?.users?.beforeDelete) {
@@ -513,8 +541,7 @@ displayName: existing.displayName }, appName);
513
541
  id: r.id,
514
542
  name: r.name,
515
543
  isAdmin: r.isAdmin,
516
- defaultPermissions: r.defaultPermissions,
517
- config: r.config
544
+ defaultPermissions: r.defaultPermissions
518
545
  }));
519
546
 
520
547
  adminRoles = await applyRoleAfterReadBatch(adminRoles, hookCtx);
@@ -535,7 +562,7 @@ displayName: existing.displayName }, appName);
535
562
 
536
563
  router.post("/roles", requireAdmin, async (c) => {
537
564
  const body = await c.req.json();
538
- const { id, name, isAdmin, defaultPermissions, config } = body;
565
+ const { id, name, isAdmin, defaultPermissions } = body;
539
566
 
540
567
  if (!id || !name) {
541
568
  throw ApiError.badRequest("Role ID and name are required", "INVALID_INPUT");
@@ -550,8 +577,7 @@ displayName: existing.displayName }, appName);
550
577
  id,
551
578
  name,
552
579
  isAdmin: isAdmin ?? false,
553
- defaultPermissions: defaultPermissions ?? null,
554
- config: config ?? null
580
+ defaultPermissions: defaultPermissions ?? null
555
581
  });
556
582
 
557
583
  return c.json({ role }, 201);
@@ -560,7 +586,7 @@ displayName: existing.displayName }, appName);
560
586
  router.put("/roles/:roleId", requireAdmin, async (c) => {
561
587
  const roleId = c.req.param("roleId");
562
588
  const body = await c.req.json();
563
- const { name, isAdmin, defaultPermissions, config } = body;
589
+ const { name, isAdmin, defaultPermissions } = body;
564
590
 
565
591
  const existing = await authRepo.getRoleById(roleId);
566
592
  if (!existing) {
@@ -570,8 +596,7 @@ displayName: existing.displayName }, appName);
570
596
  const role = await authRepo.updateRole(roleId, {
571
597
  name,
572
598
  isAdmin,
573
- defaultPermissions,
574
- config
599
+ defaultPermissions
575
600
  });
576
601
 
577
602
  return c.json({ role });
@@ -0,0 +1,126 @@
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
+
24
+ /**
25
+ * Check whether a token looks like a Rebase API key.
26
+ */
27
+ export function isApiKeyToken(token: string): boolean {
28
+ return token.startsWith("rk_");
29
+ }
30
+
31
+ /**
32
+ * Hash a plaintext API key token for database lookup.
33
+ */
34
+ function hashToken(token: string): string {
35
+ return createHash("sha256").update(token).digest("hex");
36
+ }
37
+
38
+ /**
39
+ * Options for the API key authentication handler.
40
+ */
41
+ export interface ApiKeyAuthOptions {
42
+ store: ApiKeyStore;
43
+ driver: DataDriver;
44
+ }
45
+
46
+ /**
47
+ * Validate an API key token and populate the Hono context.
48
+ *
49
+ * Returns `true` if the key is valid and context has been populated,
50
+ * or returns an error Response if the key is invalid.
51
+ *
52
+ * This is NOT a standalone middleware — it's called from within
53
+ * `createAuthMiddleware()` when a `rk_` prefixed token is detected.
54
+ */
55
+ export async function validateApiKey(
56
+ c: Context<HonoEnv>,
57
+ token: string,
58
+ options: ApiKeyAuthOptions,
59
+ ): Promise<Response | true> {
60
+ const { store, driver } = options;
61
+
62
+ const hash = hashToken(token);
63
+ const apiKey = await store.findByKeyHash(hash);
64
+
65
+ if (!apiKey) {
66
+ return c.json({
67
+ error: { message: "Invalid API key", code: "UNAUTHORIZED" },
68
+ }, 401);
69
+ }
70
+
71
+ // Check revocation
72
+ if (apiKey.revoked_at) {
73
+ return c.json({
74
+ error: { message: "API key has been revoked", code: "UNAUTHORIZED" },
75
+ }, 401);
76
+ }
77
+
78
+ // Check expiration
79
+ if (apiKey.expires_at && new Date(apiKey.expires_at) < new Date()) {
80
+ return c.json({
81
+ error: { message: "API key has expired", code: "UNAUTHORIZED" },
82
+ }, 401);
83
+ }
84
+
85
+ // Set user identity — API keys represent service accounts
86
+ const userId = `api-key:${apiKey.id}`;
87
+ c.set("user", { userId, roles: [] });
88
+
89
+ // Expose masked key metadata for downstream permission checks
90
+ const masked: ApiKeyMasked = {
91
+ id: apiKey.id,
92
+ name: apiKey.name,
93
+ key_prefix: apiKey.key_prefix,
94
+ permissions: apiKey.permissions,
95
+ rate_limit: apiKey.rate_limit,
96
+ created_by: apiKey.created_by,
97
+ created_at: apiKey.created_at,
98
+ updated_at: apiKey.updated_at,
99
+ last_used_at: apiKey.last_used_at,
100
+ expires_at: apiKey.expires_at,
101
+ revoked_at: apiKey.revoked_at,
102
+ };
103
+ // Store apiKey in the context for permission checking in api-generator
104
+ c.set("apiKey", masked);
105
+
106
+ // Scope the DataDriver — API keys bypass RLS (service identity)
107
+ try {
108
+ const scopedDriver = await scopeDataDriver(driver, {
109
+ uid: userId,
110
+ roles: ["service"],
111
+ });
112
+ c.set("driver", scopedDriver);
113
+ } catch (error) {
114
+ console.error("[AUTH] RLS scoping failed for API key:", error);
115
+ return c.json({
116
+ error: { message: "Internal authentication error", code: "INTERNAL_ERROR" },
117
+ }, 500);
118
+ }
119
+
120
+ // Touch last_used_at in the background (non-blocking)
121
+ store.updateLastUsed(apiKey.id).catch(() => {
122
+ // Swallowed intentionally — logged inside the store
123
+ });
124
+
125
+ return true;
126
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Permission guard for Service API Keys.
3
+ *
4
+ * Checks whether an API key's permission set allows a specific operation
5
+ * on a specific collection. Used by the REST API generator middleware to
6
+ * enforce fine-grained access control.
7
+ *
8
+ * @module
9
+ */
10
+
11
+ import type { ApiKeyPermission } from "./api-key-types";
12
+
13
+ /** Operations that map to HTTP methods. */
14
+ export type ApiKeyOperation = "read" | "write" | "delete";
15
+
16
+ /**
17
+ * Map an HTTP method string to an `ApiKeyOperation`.
18
+ *
19
+ * - `GET`, `HEAD`, `OPTIONS` → `"read"`
20
+ * - `POST`, `PUT`, `PATCH` → `"write"`
21
+ * - `DELETE` → `"delete"`
22
+ */
23
+ export function httpMethodToOperation(method: string): ApiKeyOperation {
24
+ const upper = method.toUpperCase();
25
+ switch (upper) {
26
+ case "GET":
27
+ case "HEAD":
28
+ case "OPTIONS":
29
+ return "read";
30
+ case "POST":
31
+ case "PUT":
32
+ case "PATCH":
33
+ return "write";
34
+ case "DELETE":
35
+ return "delete";
36
+ default:
37
+ return "read";
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Check whether the given permissions array allows `operation` on `collection`.
43
+ *
44
+ * Supports the `"*"` wildcard for the collection field, which matches any
45
+ * collection. Returns `true` if at least one permission entry grants access.
46
+ *
47
+ * @param permissions - The API key's permission entries.
48
+ * @param collection - The target collection slug.
49
+ * @param operation - The requested operation.
50
+ * @returns `true` if the operation is permitted.
51
+ */
52
+ export function isOperationAllowed(
53
+ permissions: ApiKeyPermission[],
54
+ collection: string,
55
+ operation: ApiKeyOperation,
56
+ ): boolean {
57
+ for (const perm of permissions) {
58
+ const collectionMatch = perm.collection === "*" || perm.collection === collection;
59
+ if (collectionMatch && perm.operations.includes(operation)) {
60
+ return true;
61
+ }
62
+ }
63
+ return false;
64
+ }
@@ -0,0 +1,183 @@
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, 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 (rate_limit !== undefined && rate_limit !== null) {
76
+ if (typeof rate_limit !== "number" || rate_limit < 1 || !Number.isInteger(rate_limit)) {
77
+ throw ApiError.badRequest("rate_limit must be a positive integer or null", "INVALID_INPUT");
78
+ }
79
+ }
80
+
81
+ if (expires_at !== undefined && expires_at !== null) {
82
+ const parsed = new Date(expires_at as string);
83
+ if (isNaN(parsed.getTime())) {
84
+ throw ApiError.badRequest("expires_at must be a valid ISO-8601 date", "INVALID_INPUT");
85
+ }
86
+ if (parsed <= new Date()) {
87
+ throw ApiError.badRequest("expires_at must be in the future", "INVALID_INPUT");
88
+ }
89
+ }
90
+
91
+ const user = c.get("user");
92
+ const createdBy = (user && typeof user === "object" && "userId" in user)
93
+ ? (user.userId as string)
94
+ : "unknown";
95
+
96
+ const request: CreateApiKeyRequest = {
97
+ name: name.trim(),
98
+ permissions: permissions as ApiKeyPermission[],
99
+ rate_limit: (rate_limit as number | null) ?? null,
100
+ expires_at: (expires_at as string | null) ?? null,
101
+ };
102
+
103
+ const keyWithSecret = await store.createApiKey(request, createdBy);
104
+
105
+ return c.json({ key: keyWithSecret }, 201);
106
+ });
107
+
108
+ // GET /:id — Get API key details (masked)
109
+ router.get("/:id", async (c) => {
110
+ const id = c.req.param("id");
111
+ const key = await store.getApiKeyById(id);
112
+
113
+ if (!key) {
114
+ throw ApiError.notFound("API key not found");
115
+ }
116
+
117
+ return c.json({ key });
118
+ });
119
+
120
+ // PUT /:id — Update API key
121
+ router.put("/:id", async (c) => {
122
+ const id = c.req.param("id");
123
+ const body = await c.req.json() as Record<string, unknown>;
124
+ const { name, permissions, rate_limit, expires_at } = body;
125
+
126
+ // Validate fields if provided
127
+ if (name !== undefined) {
128
+ if (typeof name !== "string" || name.trim().length === 0) {
129
+ throw ApiError.badRequest("Name must be a non-empty string", "INVALID_INPUT");
130
+ }
131
+ }
132
+
133
+ if (permissions !== undefined) {
134
+ if (!validatePermissions(permissions)) {
135
+ throw ApiError.badRequest(
136
+ "Permissions must be an array of { collection: string, operations: ('read' | 'write' | 'delete')[] }",
137
+ "INVALID_INPUT",
138
+ );
139
+ }
140
+ }
141
+
142
+ if (rate_limit !== undefined && rate_limit !== null) {
143
+ if (typeof rate_limit !== "number" || rate_limit < 1 || !Number.isInteger(rate_limit)) {
144
+ throw ApiError.badRequest("rate_limit must be a positive integer or null", "INVALID_INPUT");
145
+ }
146
+ }
147
+
148
+ if (expires_at !== undefined && expires_at !== null) {
149
+ const parsed = new Date(expires_at as string);
150
+ if (isNaN(parsed.getTime())) {
151
+ throw ApiError.badRequest("expires_at must be a valid ISO-8601 date", "INVALID_INPUT");
152
+ }
153
+ }
154
+
155
+ const updates: UpdateApiKeyRequest = {};
156
+ if (name !== undefined) updates.name = (name as string).trim();
157
+ if (permissions !== undefined) updates.permissions = permissions as ApiKeyPermission[];
158
+ if (rate_limit !== undefined) updates.rate_limit = rate_limit as number | null;
159
+ if (expires_at !== undefined) updates.expires_at = expires_at as string | null;
160
+
161
+ const key = await store.updateApiKey(id, updates);
162
+
163
+ if (!key) {
164
+ throw ApiError.notFound("API key not found");
165
+ }
166
+
167
+ return c.json({ key });
168
+ });
169
+
170
+ // DELETE /:id — Revoke (soft-delete)
171
+ router.delete("/:id", async (c) => {
172
+ const id = c.req.param("id");
173
+ const revoked = await store.revokeApiKey(id);
174
+
175
+ if (!revoked) {
176
+ throw ApiError.notFound("API key not found or already revoked");
177
+ }
178
+
179
+ return c.json({ success: true });
180
+ });
181
+
182
+ return router;
183
+ }