@rebasepro/server-core 0.2.3 → 0.2.5
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.
- package/dist/common/src/collections/default-collections.d.ts +9 -0
- package/dist/common/src/collections/index.d.ts +1 -0
- package/dist/common/src/util/permissions.d.ts +1 -0
- package/dist/{index-BZoAtuqi.js → index-Cr1D21av.js} +11 -3
- package/dist/index-Cr1D21av.js.map +1 -0
- package/dist/index.es.js +2309 -370
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +2298 -355
- package/dist/index.umd.js.map +1 -1
- package/dist/server-core/src/api/logs-routes.d.ts +37 -0
- package/dist/server-core/src/api/rest/api-generator.d.ts +6 -0
- package/dist/server-core/src/api/types.d.ts +6 -1
- package/dist/server-core/src/auth/adapter-middleware.d.ts +7 -3
- package/dist/server-core/src/auth/admin-routes.d.ts +3 -3
- package/dist/server-core/src/auth/api-keys/api-key-middleware.d.ts +39 -0
- package/dist/server-core/src/auth/api-keys/api-key-permission-guard.d.ts +32 -0
- package/dist/server-core/src/auth/api-keys/api-key-routes.d.ts +20 -0
- package/dist/server-core/src/auth/api-keys/api-key-store.d.ts +35 -0
- package/dist/server-core/src/auth/api-keys/api-key-types.d.ts +88 -0
- package/dist/server-core/src/auth/api-keys/index.d.ts +17 -0
- package/dist/server-core/src/auth/{auth-overrides.d.ts → auth-hooks.d.ts} +69 -11
- package/dist/server-core/src/auth/builtin-auth-adapter.d.ts +3 -3
- package/dist/server-core/src/auth/index.d.ts +5 -3
- package/dist/server-core/src/auth/interfaces.d.ts +93 -3
- package/dist/server-core/src/auth/jwt.d.ts +3 -1
- package/dist/server-core/src/auth/mfa.d.ts +49 -0
- package/dist/server-core/src/auth/middleware.d.ts +7 -0
- package/dist/server-core/src/auth/rate-limiter.d.ts +19 -0
- package/dist/server-core/src/auth/routes.d.ts +3 -3
- package/dist/server-core/src/env.d.ts +6 -0
- package/dist/server-core/src/index.d.ts +1 -0
- package/dist/server-core/src/init.d.ts +3 -3
- package/dist/server-core/src/services/webhook-service.d.ts +29 -0
- package/dist/server-core/src/storage/image-transform.d.ts +48 -0
- package/dist/server-core/src/storage/index.d.ts +3 -0
- package/dist/server-core/src/storage/tus-handler.d.ts +51 -0
- package/dist/types/src/controllers/auth.d.ts +4 -26
- package/dist/types/src/controllers/client.d.ts +25 -43
- package/dist/types/src/controllers/collection_registry.d.ts +1 -1
- package/dist/types/src/controllers/data.d.ts +4 -0
- package/dist/types/src/controllers/data_driver.d.ts +23 -0
- package/dist/types/src/controllers/registry.d.ts +5 -4
- package/dist/types/src/rebase_context.d.ts +1 -1
- package/dist/types/src/types/auth_adapter.d.ts +5 -60
- package/dist/types/src/types/backend.d.ts +2 -2
- package/dist/types/src/types/backend_hooks.d.ts +2 -17
- package/dist/types/src/types/collections.d.ts +0 -4
- package/dist/types/src/types/component_ref.d.ts +1 -1
- package/dist/types/src/types/cron.d.ts +1 -1
- package/dist/types/src/types/entity_views.d.ts +1 -0
- package/dist/types/src/types/export_import.d.ts +1 -1
- package/dist/types/src/types/formex.d.ts +2 -2
- package/dist/types/src/types/properties.d.ts +9 -7
- package/dist/types/src/types/translations.d.ts +28 -12
- package/dist/types/src/types/user_management_delegate.d.ts +22 -57
- package/dist/types/src/users/index.d.ts +0 -1
- package/dist/types/src/users/user.d.ts +0 -1
- package/package.json +8 -6
- package/src/api/ast-schema-editor.ts +4 -4
- package/src/api/errors.ts +16 -7
- package/src/api/logs-routes.ts +129 -0
- package/src/api/rest/api-generator.ts +42 -2
- package/src/api/rest/query-parser.ts +37 -1
- package/src/api/types.ts +6 -1
- package/src/auth/adapter-middleware.ts +20 -4
- package/src/auth/admin-routes.ts +36 -100
- package/src/auth/api-keys/api-key-middleware.ts +126 -0
- package/src/auth/api-keys/api-key-permission-guard.ts +64 -0
- package/src/auth/api-keys/api-key-routes.ts +183 -0
- package/src/auth/api-keys/api-key-store.ts +317 -0
- package/src/auth/api-keys/api-key-types.ts +94 -0
- package/src/auth/api-keys/index.ts +37 -0
- package/src/auth/{auth-overrides.ts → auth-hooks.ts} +81 -14
- package/src/auth/builtin-auth-adapter.ts +35 -73
- package/src/auth/custom-auth-adapter.ts +1 -1
- package/src/auth/index.ts +7 -3
- package/src/auth/interfaces.ts +111 -3
- package/src/auth/jwt.ts +19 -5
- package/src/auth/mfa.ts +160 -0
- package/src/auth/middleware.ts +20 -1
- package/src/auth/rate-limiter.ts +92 -0
- package/src/auth/routes.ts +455 -24
- package/src/cron/cron-loader.ts +5 -10
- package/src/cron/cron-scheduler.ts +11 -12
- package/src/cron/cron-store.ts +8 -7
- package/src/env.ts +2 -0
- package/src/functions/function-loader.ts +6 -9
- package/src/index.ts +1 -2
- package/src/init.ts +56 -8
- package/src/serve-spa.ts +5 -4
- package/src/services/webhook-service.ts +155 -0
- package/src/storage/image-transform.ts +202 -0
- package/src/storage/index.ts +3 -0
- package/src/storage/routes.ts +56 -3
- package/src/storage/tus-handler.ts +315 -0
- package/src/utils/dev-port.ts +14 -0
- package/src/utils/logging.ts +9 -7
- package/test/admin-routes.test.ts +62 -164
- package/test/api-generator.test.ts +0 -1
- package/test/api-key-permission-guard.test.ts +132 -0
- package/test/ast-schema-editor.test.ts +26 -0
- package/test/auth-routes.test.ts +1 -2
- package/test/backend-hooks-admin.test.ts +3 -29
- package/test/custom-auth-adapter.test.ts +2 -10
- package/test/email-templates.test.ts +169 -0
- package/test/function-loader.test.ts +124 -0
- package/test/jwt.test.ts +4 -2
- package/test/mfa.test.ts +197 -0
- package/test/middleware.test.ts +10 -5
- package/test/webhook-service.test.ts +249 -0
- package/vite.config.ts +3 -2
- package/dist/index-BZoAtuqi.js.map +0 -1
- package/dist/server-core/src/bootstrappers/index.d.ts +0 -0
- package/dist/types/src/users/roles.d.ts +0 -22
- package/src/bootstrappers/index.ts +0 -1
- package/src/singleton.test.ts +0 -28
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Database operations for Service API Keys.
|
|
3
|
+
*
|
|
4
|
+
* Uses the DataDriver's `admin.executeSql` capability (same pattern as
|
|
5
|
+
* the cron-store and ensure-tables modules). All data lives in the
|
|
6
|
+
* `rebase.api_keys` table.
|
|
7
|
+
*
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { randomBytes, createHash } from "crypto";
|
|
12
|
+
import type { DataDriver } from "@rebasepro/types";
|
|
13
|
+
import { isSQLAdmin } from "@rebasepro/types";
|
|
14
|
+
import { logger } from "../../utils/logger";
|
|
15
|
+
import type {
|
|
16
|
+
ApiKey,
|
|
17
|
+
ApiKeyMasked,
|
|
18
|
+
ApiKeyWithSecret,
|
|
19
|
+
CreateApiKeyRequest,
|
|
20
|
+
UpdateApiKeyRequest,
|
|
21
|
+
} from "./api-key-types";
|
|
22
|
+
|
|
23
|
+
const TABLE = "rebase.api_keys";
|
|
24
|
+
|
|
25
|
+
/** Characters used to generate the random portion of an API key. */
|
|
26
|
+
const HEX_CHARS = "abcdef0123456789";
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Generate a plaintext API key with the `rk_live_` prefix.
|
|
30
|
+
*
|
|
31
|
+
* Format: `rk_live_` + 32 random hex characters.
|
|
32
|
+
*/
|
|
33
|
+
function generateApiKey(): string {
|
|
34
|
+
const random = randomBytes(16).toString("hex"); // 32 hex chars
|
|
35
|
+
return `rk_live_${random}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* SHA-256 hash a plaintext API key for database storage.
|
|
40
|
+
*/
|
|
41
|
+
function hashKey(plaintext: string): string {
|
|
42
|
+
return createHash("sha256").update(plaintext).digest("hex");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Extract the display prefix from a plaintext key (first 12 chars).
|
|
47
|
+
*/
|
|
48
|
+
function keyPrefix(plaintext: string): string {
|
|
49
|
+
return plaintext.substring(0, 12);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Strip the `key_hash` field and return a safe-to-expose masked key.
|
|
54
|
+
*/
|
|
55
|
+
function toMasked(row: ApiKey): ApiKeyMasked {
|
|
56
|
+
return {
|
|
57
|
+
id: row.id,
|
|
58
|
+
name: row.name,
|
|
59
|
+
key_prefix: row.key_prefix,
|
|
60
|
+
permissions: row.permissions,
|
|
61
|
+
rate_limit: row.rate_limit,
|
|
62
|
+
created_by: row.created_by,
|
|
63
|
+
created_at: row.created_at,
|
|
64
|
+
updated_at: row.updated_at,
|
|
65
|
+
last_used_at: row.last_used_at,
|
|
66
|
+
expires_at: row.expires_at,
|
|
67
|
+
revoked_at: row.revoked_at,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Parse a raw DB row into the typed `ApiKey` shape.
|
|
73
|
+
*/
|
|
74
|
+
function rowToApiKey(row: Record<string, unknown>): ApiKey {
|
|
75
|
+
const permissions = typeof row.permissions === "string"
|
|
76
|
+
? JSON.parse(row.permissions)
|
|
77
|
+
: (row.permissions ?? []);
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
id: row.id as string,
|
|
81
|
+
name: row.name as string,
|
|
82
|
+
key_prefix: row.key_prefix as string,
|
|
83
|
+
key_hash: row.key_hash as string,
|
|
84
|
+
permissions,
|
|
85
|
+
rate_limit: row.rate_limit !== null && row.rate_limit !== undefined
|
|
86
|
+
? Number(row.rate_limit)
|
|
87
|
+
: null,
|
|
88
|
+
created_by: row.created_by as string,
|
|
89
|
+
created_at: new Date(row.created_at as string).toISOString(),
|
|
90
|
+
updated_at: new Date(row.updated_at as string).toISOString(),
|
|
91
|
+
last_used_at: row.last_used_at ? new Date(row.last_used_at as string).toISOString() : null,
|
|
92
|
+
expires_at: row.expires_at ? new Date(row.expires_at as string).toISOString() : null,
|
|
93
|
+
revoked_at: row.revoked_at ? new Date(row.revoked_at as string).toISOString() : null,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Escape a string for safe inline SQL usage.
|
|
99
|
+
*/
|
|
100
|
+
function esc(value: string): string {
|
|
101
|
+
return value.replace(/'/g, "''");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ─── Public API ──────────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
export interface ApiKeyStore {
|
|
107
|
+
/** Ensure the `rebase.api_keys` table exists. Called once on startup. */
|
|
108
|
+
ensureTable(): Promise<void>;
|
|
109
|
+
|
|
110
|
+
/** Create a new API key. Returns the full plaintext key exactly once. */
|
|
111
|
+
createApiKey(request: CreateApiKeyRequest, createdBy: string): Promise<ApiKeyWithSecret>;
|
|
112
|
+
|
|
113
|
+
/** Look up an API key by its SHA-256 hash. Returns `null` if not found. */
|
|
114
|
+
findByKeyHash(hash: string): Promise<ApiKey | null>;
|
|
115
|
+
|
|
116
|
+
/** List all API keys (masked, never includes hash). */
|
|
117
|
+
listApiKeys(): Promise<ApiKeyMasked[]>;
|
|
118
|
+
|
|
119
|
+
/** Get a single API key by ID (masked). */
|
|
120
|
+
getApiKeyById(id: string): Promise<ApiKeyMasked | null>;
|
|
121
|
+
|
|
122
|
+
/** Update name, permissions, rate_limit, or expires_at. */
|
|
123
|
+
updateApiKey(id: string, updates: UpdateApiKeyRequest): Promise<ApiKeyMasked | null>;
|
|
124
|
+
|
|
125
|
+
/** Soft-delete: set `revoked_at` to now. */
|
|
126
|
+
revokeApiKey(id: string): Promise<boolean>;
|
|
127
|
+
|
|
128
|
+
/** Touch `last_used_at` to the current timestamp. */
|
|
129
|
+
updateLastUsed(id: string): Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Create an `ApiKeyStore` backed by the driver's SQL admin capability.
|
|
134
|
+
*
|
|
135
|
+
* Returns `undefined` if the driver does not support `executeSql`.
|
|
136
|
+
*/
|
|
137
|
+
export function createApiKeyStore(driver: DataDriver): ApiKeyStore | undefined {
|
|
138
|
+
const admin = driver.admin;
|
|
139
|
+
if (!isSQLAdmin(admin)) {
|
|
140
|
+
logger.warn("⚠️ [api-key-store] DataDriver does not support SQL admin — API keys will not be available.");
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const exec = admin.executeSql.bind(admin);
|
|
145
|
+
|
|
146
|
+
return {
|
|
147
|
+
// ── Schema bootstrap ────────────────────────────────────────
|
|
148
|
+
async ensureTable(): Promise<void> {
|
|
149
|
+
try {
|
|
150
|
+
await exec("CREATE SCHEMA IF NOT EXISTS rebase");
|
|
151
|
+
await exec(`
|
|
152
|
+
CREATE TABLE IF NOT EXISTS ${TABLE} (
|
|
153
|
+
id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
|
154
|
+
name TEXT NOT NULL,
|
|
155
|
+
key_prefix TEXT NOT NULL,
|
|
156
|
+
key_hash TEXT NOT NULL UNIQUE,
|
|
157
|
+
permissions JSONB NOT NULL DEFAULT '[]'::jsonb,
|
|
158
|
+
rate_limit INTEGER,
|
|
159
|
+
created_by TEXT NOT NULL,
|
|
160
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
161
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
|
162
|
+
last_used_at TIMESTAMPTZ,
|
|
163
|
+
expires_at TIMESTAMPTZ,
|
|
164
|
+
revoked_at TIMESTAMPTZ
|
|
165
|
+
)
|
|
166
|
+
`);
|
|
167
|
+
|
|
168
|
+
await exec(`
|
|
169
|
+
CREATE INDEX IF NOT EXISTS idx_api_keys_hash
|
|
170
|
+
ON ${TABLE}(key_hash)
|
|
171
|
+
`);
|
|
172
|
+
|
|
173
|
+
await exec(`
|
|
174
|
+
CREATE INDEX IF NOT EXISTS idx_api_keys_prefix
|
|
175
|
+
ON ${TABLE}(key_prefix)
|
|
176
|
+
`);
|
|
177
|
+
|
|
178
|
+
logger.info("✅ API keys table ready");
|
|
179
|
+
} catch (err) {
|
|
180
|
+
logger.error("❌ Failed to create API keys table", { error: err });
|
|
181
|
+
logger.warn("⚠️ Continuing without API keys support.");
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
|
|
185
|
+
// ── Create ──────────────────────────────────────────────────
|
|
186
|
+
async createApiKey(request: CreateApiKeyRequest, createdBy: string): Promise<ApiKeyWithSecret> {
|
|
187
|
+
const plaintext = generateApiKey();
|
|
188
|
+
const hash = hashKey(plaintext);
|
|
189
|
+
const prefix = keyPrefix(plaintext);
|
|
190
|
+
const permissionsJson = JSON.stringify(request.permissions);
|
|
191
|
+
const rateLimitSql = request.rate_limit !== null && request.rate_limit !== undefined
|
|
192
|
+
? String(request.rate_limit)
|
|
193
|
+
: "NULL";
|
|
194
|
+
const expiresAtSql = request.expires_at
|
|
195
|
+
? `'${esc(request.expires_at)}'`
|
|
196
|
+
: "NULL";
|
|
197
|
+
|
|
198
|
+
const rows = await exec(`
|
|
199
|
+
INSERT INTO ${TABLE} (name, key_prefix, key_hash, permissions, rate_limit, created_by, expires_at)
|
|
200
|
+
VALUES (
|
|
201
|
+
'${esc(request.name)}',
|
|
202
|
+
'${esc(prefix)}',
|
|
203
|
+
'${esc(hash)}',
|
|
204
|
+
'${esc(permissionsJson)}'::jsonb,
|
|
205
|
+
${rateLimitSql},
|
|
206
|
+
'${esc(createdBy)}',
|
|
207
|
+
${expiresAtSql}
|
|
208
|
+
)
|
|
209
|
+
RETURNING *
|
|
210
|
+
`);
|
|
211
|
+
|
|
212
|
+
const apiKey = rowToApiKey(rows[0]);
|
|
213
|
+
return {
|
|
214
|
+
...toMasked(apiKey),
|
|
215
|
+
key: plaintext,
|
|
216
|
+
};
|
|
217
|
+
},
|
|
218
|
+
|
|
219
|
+
// ── Lookup by hash ──────────────────────────────────────────
|
|
220
|
+
async findByKeyHash(hash: string): Promise<ApiKey | null> {
|
|
221
|
+
const rows = await exec(`
|
|
222
|
+
SELECT * FROM ${TABLE}
|
|
223
|
+
WHERE key_hash = '${esc(hash)}'
|
|
224
|
+
LIMIT 1
|
|
225
|
+
`);
|
|
226
|
+
if (rows.length === 0) return null;
|
|
227
|
+
return rowToApiKey(rows[0]);
|
|
228
|
+
},
|
|
229
|
+
|
|
230
|
+
// ── List all (masked) ───────────────────────────────────────
|
|
231
|
+
async listApiKeys(): Promise<ApiKeyMasked[]> {
|
|
232
|
+
const rows = await exec(`
|
|
233
|
+
SELECT * FROM ${TABLE}
|
|
234
|
+
ORDER BY created_at DESC
|
|
235
|
+
`);
|
|
236
|
+
return rows.map(r => toMasked(rowToApiKey(r)));
|
|
237
|
+
},
|
|
238
|
+
|
|
239
|
+
// ── Get by ID (masked) ──────────────────────────────────────
|
|
240
|
+
async getApiKeyById(id: string): Promise<ApiKeyMasked | null> {
|
|
241
|
+
const rows = await exec(`
|
|
242
|
+
SELECT * FROM ${TABLE}
|
|
243
|
+
WHERE id = '${esc(id)}'
|
|
244
|
+
LIMIT 1
|
|
245
|
+
`);
|
|
246
|
+
if (rows.length === 0) return null;
|
|
247
|
+
return toMasked(rowToApiKey(rows[0]));
|
|
248
|
+
},
|
|
249
|
+
|
|
250
|
+
// ── Update ──────────────────────────────────────────────────
|
|
251
|
+
async updateApiKey(id: string, updates: UpdateApiKeyRequest): Promise<ApiKeyMasked | null> {
|
|
252
|
+
const setClauses: string[] = [];
|
|
253
|
+
|
|
254
|
+
if (updates.name !== undefined) {
|
|
255
|
+
setClauses.push(`name = '${esc(updates.name)}'`);
|
|
256
|
+
}
|
|
257
|
+
if (updates.permissions !== undefined) {
|
|
258
|
+
setClauses.push(`permissions = '${esc(JSON.stringify(updates.permissions))}'::jsonb`);
|
|
259
|
+
}
|
|
260
|
+
if (updates.rate_limit !== undefined) {
|
|
261
|
+
setClauses.push(
|
|
262
|
+
updates.rate_limit !== null
|
|
263
|
+
? `rate_limit = ${updates.rate_limit}`
|
|
264
|
+
: "rate_limit = NULL"
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
if (updates.expires_at !== undefined) {
|
|
268
|
+
setClauses.push(
|
|
269
|
+
updates.expires_at !== null
|
|
270
|
+
? `expires_at = '${esc(updates.expires_at)}'`
|
|
271
|
+
: "expires_at = NULL"
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
if (setClauses.length === 0) {
|
|
276
|
+
return this.getApiKeyById(id);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
setClauses.push("updated_at = NOW()");
|
|
280
|
+
|
|
281
|
+
const rows = await exec(`
|
|
282
|
+
UPDATE ${TABLE}
|
|
283
|
+
SET ${setClauses.join(", ")}
|
|
284
|
+
WHERE id = '${esc(id)}'
|
|
285
|
+
RETURNING *
|
|
286
|
+
`);
|
|
287
|
+
|
|
288
|
+
if (rows.length === 0) return null;
|
|
289
|
+
return toMasked(rowToApiKey(rows[0]));
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
// ── Revoke (soft-delete) ────────────────────────────────────
|
|
293
|
+
async revokeApiKey(id: string): Promise<boolean> {
|
|
294
|
+
const rows = await exec(`
|
|
295
|
+
UPDATE ${TABLE}
|
|
296
|
+
SET revoked_at = NOW(), updated_at = NOW()
|
|
297
|
+
WHERE id = '${esc(id)}' AND revoked_at IS NULL
|
|
298
|
+
RETURNING id
|
|
299
|
+
`);
|
|
300
|
+
return rows.length > 0;
|
|
301
|
+
},
|
|
302
|
+
|
|
303
|
+
// ── Touch last_used_at ──────────────────────────────────────
|
|
304
|
+
async updateLastUsed(id: string): Promise<void> {
|
|
305
|
+
try {
|
|
306
|
+
await exec(`
|
|
307
|
+
UPDATE ${TABLE}
|
|
308
|
+
SET last_used_at = NOW()
|
|
309
|
+
WHERE id = '${esc(id)}'
|
|
310
|
+
`);
|
|
311
|
+
} catch (err) {
|
|
312
|
+
// Non-blocking — don't fail requests because of a usage timestamp update
|
|
313
|
+
logger.error("[api-key-store] Failed to update last_used_at", { error: err });
|
|
314
|
+
}
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
}
|