Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,6 @@ bun.lockb
# One-off / local scripts (keep on disk, not versioned)
/scripts/



.cursorrules
16 changes: 16 additions & 0 deletions drizzle/0006_add_api_keys.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- API keys for MCP server authentication
CREATE TABLE "api_keys" (
"id" text PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" text NOT NULL,
"key_hash" text NOT NULL,
"key_prefix" text NOT NULL,
"label" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"last_used_at" timestamp with time zone,
"revoked_at" timestamp with time zone,
CONSTRAINT "api_keys_key_hash_key" UNIQUE("key_hash")
);
--> statement-breakpoint
ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;
--> statement-breakpoint
CREATE INDEX "api_keys_user_id_idx" ON "api_keys" USING btree ("user_id" text_ops);
7 changes: 7 additions & 0 deletions drizzle/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@
"when": 1771800001000,
"tag": "0005_add_chat_messages_thread_message_unique",
"breakpoints": true
},
{
"idx": 6,
"version": "7",
"when": 1744156800000,
"tag": "0006_add_api_keys",
"breakpoints": true
}
]
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"dependencies": {
"@ai-sdk/devtools": "^0.0.15",
"@ai-sdk/google": "^3.0.58",
"@modelcontextprotocol/sdk": "^1.0.4",
"@assistant-ui/react": "^0.12.23",
"@assistant-ui/react-ai-sdk": "^1.3.17",
"@assistant-ui/react-devtools": "^1.0.4",
Expand Down
36 changes: 36 additions & 0 deletions src/app/api/mcp-keys/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NextResponse } from "next/server";
import { db } from "@/lib/db/client";
import { apiKeys } from "@/lib/db/schema";
import { eq, and } from "drizzle-orm";
import { requireAuth, withErrorHandling } from "@/lib/api/workspace-helpers";

async function handleDELETE(
_req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const userId = await requireAuth();
const { id } = await params;

const [key] = await db
.select({ userId: apiKeys.userId })
.from(apiKeys)
.where(eq(apiKeys.id, id))
.limit(1);

if (!key) {
return NextResponse.json({ error: "API key not found" }, { status: 404 });
}

if (key.userId !== userId) {
return NextResponse.json({ error: "Access denied" }, { status: 403 });
}

await db
.update(apiKeys)
.set({ revokedAt: new Date().toISOString() })
.where(eq(apiKeys.id, id));

return NextResponse.json({ success: true });
}

export const DELETE = withErrorHandling(handleDELETE, "DELETE /api/mcp-keys/[id]");
96 changes: 96 additions & 0 deletions src/app/api/mcp-keys/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { NextResponse } from "next/server";
import { createHash, randomBytes } from "crypto";
import { db } from "@/lib/db/client";
import { apiKeys } from "@/lib/db/schema";
import { eq, and, isNull, count, sql } from "drizzle-orm";
import { requireAuth, withErrorHandling } from "@/lib/api/workspace-helpers";

const MAX_KEYS_PER_USER = 10;

// Deterministic i64 from a userId string — used as the advisory lock key.
// XOR-folds the SHA-256 bytes into 8 bytes so the result fits in a pg bigint.
function userIdToLockKey(userId: string): bigint {
const hash = createHash("sha256").update(userId).digest();
let lo = 0n;
for (let i = 0; i < 32; i++) {
lo ^= BigInt(hash[i]) << BigInt((i % 8) * 8);
}
// Clamp to signed int64 range so Postgres accepts it
const MAX_I64 = 9223372036854775807n;
return lo > MAX_I64 ? lo - (MAX_I64 + 1n) * 2n : lo;
}

async function handlePOST(req: Request) {
const userId = await requireAuth();
const body = await req.json().catch(() => ({}));
const label = typeof body?.label === "string" ? body.label.slice(0, 100) : null;

const rawKey = `tx_${randomBytes(32).toString("base64url")}`;
const keyHash = createHash("sha256").update(rawKey).digest("hex");
const keyPrefix = rawKey.substring(0, 8);
const lockKey = userIdToLockKey(userId);

const result = await db.transaction(async (tx) => {
// Acquire a per-user advisory lock that is automatically released when
// the transaction ends, serialising concurrent key-creation requests.
await tx.execute(sql`SELECT pg_advisory_xact_lock(${lockKey}::bigint)`);

const [{ total }] = await tx
.select({ total: count() })
.from(apiKeys)
.where(and(eq(apiKeys.userId, userId), isNull(apiKeys.revokedAt)));

if (total >= MAX_KEYS_PER_USER) {
return null;
}

const [inserted] = await tx
.insert(apiKeys)
.values({
userId,
keyHash,
keyPrefix,
label,
createdAt: new Date().toISOString(),
revokedAt: null,
lastUsedAt: null,
})
.returning({ id: apiKeys.id, prefix: apiKeys.keyPrefix });

return inserted;
});

if (!result) {
return NextResponse.json(
{ error: `You can have at most ${MAX_KEYS_PER_USER} active API keys. Revoke an existing key first.` },
{ status: 422 }
);
}

return NextResponse.json({
id: result.id,
rawKey,
prefix: result.prefix,
});
}

async function handleGET() {
const userId = await requireAuth();

const keys = await db
.select({
id: apiKeys.id,
prefix: apiKeys.keyPrefix,
label: apiKeys.label,
createdAt: apiKeys.createdAt,
lastUsedAt: apiKeys.lastUsedAt,
})
.from(apiKeys)
.where(and(eq(apiKeys.userId, userId), isNull(apiKeys.revokedAt)))
.orderBy(apiKeys.createdAt);

return NextResponse.json({ keys });
}

export const POST = withErrorHandling(handlePOST, "POST /api/mcp-keys");
export const GET = withErrorHandling(handleGET, "GET /api/mcp-keys");
Loading