feat(cursor): Add cursor Provider

This commit is contained in:
decolua
2026-02-05 11:06:20 +07:00
parent abaeb22863
commit 0a026c7af6
16 changed files with 1111 additions and 935 deletions
@@ -0,0 +1,84 @@
import { NextResponse } from "next/server";
import { homedir } from "os";
import { join } from "path";
import Database from "better-sqlite3";
/**
* GET /api/oauth/cursor/auto-import
* Auto-detect and extract Cursor tokens from local SQLite database
*/
export async function GET() {
try {
const platform = process.platform;
let dbPath;
// Determine database path based on platform
if (platform === "darwin") {
dbPath = join(homedir(), "Library/Application Support/Cursor/User/globalStorage/state.vscdb");
} else if (platform === "linux") {
dbPath = join(homedir(), ".config/Cursor/User/globalStorage/state.vscdb");
} else if (platform === "win32") {
dbPath = join(process.env.APPDATA || "", "Cursor/User/globalStorage/state.vscdb");
} else {
return NextResponse.json(
{ error: "Unsupported platform", found: false },
{ status: 400 }
);
}
// Try to open database
let db;
try {
db = new Database(dbPath, { readonly: true, fileMustExist: true });
} catch (error) {
return NextResponse.json({
found: false,
error: "Cursor database not found. Make sure Cursor IDE is installed and you are logged in.",
});
}
try {
// Extract tokens from database
const rows = db.prepare(
"SELECT key, value FROM itemTable WHERE key IN (?, ?)"
).all("cursorAuth/accessToken", "storage.serviceMachineId");
const tokens = {};
for (const row of rows) {
if (row.key === "cursorAuth/accessToken") {
tokens.accessToken = row.value;
} else if (row.key === "storage.serviceMachineId") {
tokens.machineId = row.value;
}
}
db.close();
// Validate tokens exist
if (!tokens.accessToken || !tokens.machineId) {
return NextResponse.json({
found: false,
error: "Tokens not found in database. Please login to Cursor IDE first.",
});
}
return NextResponse.json({
found: true,
accessToken: tokens.accessToken,
machineId: tokens.machineId,
});
} catch (error) {
db?.close();
return NextResponse.json({
found: false,
error: `Failed to read database: ${error.message}`,
});
}
} catch (error) {
console.log("Cursor auto-import error:", error);
return NextResponse.json(
{ found: false, error: error.message },
{ status: 500 }
);
}
}
@@ -0,0 +1,85 @@
import { NextResponse } from "next/server";
import { readFile, readdir } from "fs/promises";
import { homedir } from "os";
import { join } from "path";
/**
* GET /api/oauth/kiro/auto-import
* Auto-detect and extract Kiro refresh token from AWS SSO cache
*/
export async function GET() {
try {
const cachePath = join(homedir(), ".aws/sso/cache");
// Try to read cache directory
let files;
try {
files = await readdir(cachePath);
} catch (error) {
return NextResponse.json({
found: false,
error: "AWS SSO cache not found. Please login to Kiro IDE first.",
});
}
// Look for kiro-auth-token.json or any .json file with refreshToken
let refreshToken = null;
let foundFile = null;
// First try kiro-auth-token.json
const kiroTokenFile = "kiro-auth-token.json";
if (files.includes(kiroTokenFile)) {
try {
const content = await readFile(join(cachePath, kiroTokenFile), "utf-8");
const data = JSON.parse(content);
if (data.refreshToken && data.refreshToken.startsWith("aorAAAAAG")) {
refreshToken = data.refreshToken;
foundFile = kiroTokenFile;
}
} catch (error) {
// Continue to search other files
}
}
// If not found, search all .json files
if (!refreshToken) {
for (const file of files) {
if (!file.endsWith(".json")) continue;
try {
const content = await readFile(join(cachePath, file), "utf-8");
const data = JSON.parse(content);
// Look for Kiro refresh token (starts with aorAAAAAG)
if (data.refreshToken && data.refreshToken.startsWith("aorAAAAAG")) {
refreshToken = data.refreshToken;
foundFile = file;
break;
}
} catch (error) {
// Skip invalid JSON files
continue;
}
}
}
if (!refreshToken) {
return NextResponse.json({
found: false,
error: "Kiro token not found in AWS SSO cache. Please login to Kiro IDE first.",
});
}
return NextResponse.json({
found: true,
refreshToken,
source: foundFile,
});
} catch (error) {
console.log("Kiro auto-import error:", error);
return NextResponse.json(
{ found: false, error: error.message },
{ status: 500 }
);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
import { getRecentLogs } from "@/lib/usageDb";
export async function GET() {
try {
const logs = await getRecentLogs(200);
return NextResponse.json(logs);
} catch (error) {
console.error("[API ERROR] /api/usage/logs failed:", error);
console.error("[API ERROR] Stack:", error?.stack);
return NextResponse.json({ error: "Failed to fetch logs" }, { status: 500 });
}
}
+42 -12
View File
@@ -26,15 +26,21 @@ function getAppName() {
function getUserDataDir() {
if (isCloud) return "/tmp"; // Fallback for Workers
const platform = process.platform;
const homeDir = os.homedir();
const appName = getAppName();
try {
const platform = process.platform;
const homeDir = os.homedir();
const appName = getAppName();
if (platform === "win32") {
return path.join(process.env.APPDATA || path.join(homeDir, "AppData", "Roaming"), appName);
} else {
// macOS & Linux: ~/.{appName}
return path.join(homeDir, `.${appName}`);
if (platform === "win32") {
return path.join(process.env.APPDATA || path.join(homeDir, "AppData", "Roaming"), appName);
} else {
// macOS & Linux: ~/.{appName}
return path.join(homeDir, `.${appName}`);
}
} catch (error) {
console.error("[usageDb] Failed to get user data directory:", error.message);
// Fallback to cwd if homedir fails
return path.join(process.cwd(), ".9router");
}
}
@@ -44,8 +50,15 @@ const DB_FILE = isCloud ? null : path.join(DATA_DIR, "usage.json");
const LOG_FILE = isCloud ? null : path.join(DATA_DIR, "log.txt");
// Ensure data directory exists
if (!isCloud && !fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
if (!isCloud && fs && typeof fs.existsSync === "function") {
try {
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR, { recursive: true });
console.log(`[usageDb] Created data directory: ${DATA_DIR}`);
}
} catch (error) {
console.error("[usageDb] Failed to create data directory:", error.message);
}
}
// Default data structure
@@ -245,13 +258,30 @@ export async function appendRequestLog({ model, provider, connectionId, tokens,
*/
export async function getRecentLogs(limit = 200) {
if (isCloud) return []; // Skip in Workers
if (!fs.existsSync(LOG_FILE)) return [];
// Runtime check: ensure fs module is available
if (!fs || typeof fs.existsSync !== "function") {
console.error("[usageDb] fs module not available in this environment");
return [];
}
if (!LOG_FILE) {
console.error("[usageDb] LOG_FILE path not defined");
return [];
}
if (!fs.existsSync(LOG_FILE)) {
console.log(`[usageDb] Log file does not exist: ${LOG_FILE}`);
return [];
}
try {
const content = fs.readFileSync(LOG_FILE, "utf-8");
const lines = content.trim().split("\n");
return lines.slice(-limit).reverse();
} catch (error) {
console.error("Failed to read log.txt:", error.message);
console.error("[usageDb] Failed to read log.txt:", error.message);
console.error("[usageDb] LOG_FILE path:", LOG_FILE);
return [];
}
}
+122 -131
View File
@@ -1,29 +1,50 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import PropTypes from "prop-types";
import { Modal, Button, Input } from "@/shared/components";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
/**
* Cursor Auth Modal
* Import token from Cursor IDE's local SQLite database
*
* Token Location:
* - Linux: ~/.config/Cursor/User/globalStorage/state.vscdb
* - macOS: /Users/<user>/Library/Application Support/Cursor/User/globalStorage/state.vscdb
* - Windows: %APPDATA%\Cursor\User\globalStorage\state.vscdb
*
* Database Keys:
* - cursorAuth/accessToken: The access token
* - storage.serviceMachineId: Machine ID for checksum
* Auto-detect and import token from Cursor IDE's local SQLite database
*/
export default function CursorAuthModal({ isOpen, onSuccess, onClose }) {
const [accessToken, setAccessToken] = useState("");
const [machineId, setMachineId] = useState("");
const [error, setError] = useState(null);
const [importing, setImporting] = useState(false);
const { copied, copy } = useCopyToClipboard();
const [autoDetecting, setAutoDetecting] = useState(false);
const [autoDetected, setAutoDetected] = useState(false);
// Auto-detect tokens when modal opens
useEffect(() => {
if (!isOpen) return;
const autoDetect = async () => {
setAutoDetecting(true);
setError(null);
setAutoDetected(false);
try {
const res = await fetch("/api/oauth/cursor/auto-import");
const data = await res.json();
if (data.found) {
setAccessToken(data.accessToken);
setMachineId(data.machineId);
setAutoDetected(true);
} else {
setError(data.error || "Could not auto-detect tokens");
}
} catch (err) {
setError("Failed to auto-detect tokens");
} finally {
setAutoDetecting(false);
}
};
autoDetect();
}, [isOpen]);
const handleImportToken = async () => {
if (!accessToken.trim()) {
@@ -65,130 +86,100 @@ export default function CursorAuthModal({ isOpen, onSuccess, onClose }) {
}
};
const linuxCommand = `sqlite3 ~/.config/Cursor/User/globalStorage/state.vscdb "SELECT key, value FROM itemTable WHERE key IN ('cursorAuth/accessToken', 'storage.serviceMachineId')"`;
const macCommand = `sqlite3 "/Users/$USER/Library/Application Support/Cursor/User/globalStorage/state.vscdb" "SELECT key, value FROM itemTable WHERE key IN ('cursorAuth/accessToken', 'storage.serviceMachineId')"`;
return (
<Modal isOpen={isOpen} title="Connect Cursor IDE" onClose={onClose} size="lg">
<Modal isOpen={isOpen} title="Connect Cursor IDE" onClose={onClose}>
<div className="flex flex-col gap-4">
{/* Info Box */}
<div className="bg-blue-50 dark:bg-blue-900/20 p-4 rounded-lg border border-blue-200 dark:border-blue-800">
<div className="flex gap-2">
<span className="material-symbols-outlined text-blue-600 dark:text-blue-400">info</span>
<div className="flex-1 text-sm">
<p className="font-medium text-blue-900 dark:text-blue-100 mb-1">
Prerequisites
</p>
<p className="text-blue-800 dark:text-blue-200">
Make sure you are logged in to Cursor IDE first. Tokens are stored in the local SQLite database.
</p>
{/* Auto-detecting state */}
{autoDetecting && (
<div className="text-center py-6">
<div className="size-16 mx-auto mb-4 rounded-full bg-primary/10 flex items-center justify-center">
<span className="material-symbols-outlined text-3xl text-primary animate-spin">
progress_activity
</span>
</div>
</div>
</div>
{/* Instructions */}
<div className="space-y-3">
<p className="text-sm font-medium">How to get your tokens:</p>
<div className="bg-sidebar/50 p-3 rounded-lg space-y-2">
<p className="text-xs text-text-muted">Linux:</p>
<div className="flex items-start gap-2">
<code className="text-xs bg-sidebar px-2 py-1 rounded flex-1 overflow-x-auto whitespace-pre">
{linuxCommand}
</code>
<button
onClick={() => copy(linuxCommand, "linux-cmd")}
className="p-1 hover:bg-sidebar rounded text-text-muted hover:text-primary flex-shrink-0"
title="Copy command"
>
<span className="material-symbols-outlined text-sm">
{copied === "linux-cmd" ? "check" : "content_copy"}
</span>
</button>
</div>
</div>
<div className="bg-sidebar/50 p-3 rounded-lg space-y-2">
<p className="text-xs text-text-muted">macOS:</p>
<div className="flex items-start gap-2">
<code className="text-xs bg-sidebar px-2 py-1 rounded flex-1 overflow-x-auto whitespace-pre">
{macCommand}
</code>
<button
onClick={() => copy(macCommand, "mac-cmd")}
className="p-1 hover:bg-sidebar rounded text-text-muted hover:text-primary flex-shrink-0"
title="Copy command"
>
<span className="material-symbols-outlined text-sm">
{copied === "mac-cmd" ? "check" : "content_copy"}
</span>
</button>
</div>
</div>
<div className="text-xs text-text-muted">
<p className="mb-1">Database locations:</p>
<ul className="list-disc list-inside space-y-0.5">
<li>Linux: <code className="bg-sidebar px-1 rounded">~/.config/Cursor/User/globalStorage/state.vscdb</code></li>
<li>macOS: <code className="bg-sidebar px-1 rounded">/Users/&lt;user&gt;/Library/Application Support/Cursor/User/globalStorage/state.vscdb</code></li>
<li>Windows: <code className="bg-sidebar px-1 rounded">%APPDATA%\Cursor\User\globalStorage\state.vscdb</code></li>
</ul>
</div>
</div>
{/* Access Token Input */}
<div>
<label className="block text-sm font-medium mb-2">
Access Token <span className="text-red-500">*</span>
</label>
<textarea
value={accessToken}
onChange={(e) => setAccessToken(e.target.value)}
placeholder="Paste your access token here..."
rows={3}
className="w-full px-3 py-2 text-sm font-mono border border-border rounded-lg bg-background focus:outline-none focus:border-primary resize-none"
/>
<p className="text-xs text-text-muted mt-1">
From key: <code className="bg-sidebar px-1 rounded">cursorAuth/accessToken</code>
</p>
</div>
{/* Machine ID Input */}
<div>
<label className="block text-sm font-medium mb-2">
Machine ID <span className="text-red-500">*</span>
</label>
<Input
value={machineId}
onChange={(e) => setMachineId(e.target.value)}
placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
className="font-mono text-sm"
/>
<p className="text-xs text-text-muted mt-1">
From key: <code className="bg-sidebar px-1 rounded">storage.serviceMachineId</code>
</p>
</div>
{/* Error Display */}
{error && (
<div className="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg border border-red-200 dark:border-red-800">
<p className="text-sm text-red-600 dark:text-red-400">{error}</p>
<h3 className="text-lg font-semibold mb-2">Auto-detecting tokens...</h3>
<p className="text-sm text-text-muted">
Reading from Cursor IDE database
</p>
</div>
)}
{/* Action Buttons */}
<div className="flex gap-2">
<Button
onClick={handleImportToken}
fullWidth
disabled={importing || !accessToken.trim() || !machineId.trim()}
>
{importing ? "Importing..." : "Import Token"}
</Button>
<Button onClick={onClose} variant="ghost" fullWidth>
Cancel
</Button>
</div>
{/* Form (shown after auto-detect completes) */}
{!autoDetecting && (
<>
{/* Success message if auto-detected */}
{autoDetected && (
<div className="bg-green-50 dark:bg-green-900/20 p-3 rounded-lg border border-green-200 dark:border-green-800">
<div className="flex gap-2">
<span className="material-symbols-outlined text-green-600 dark:text-green-400">check_circle</span>
<p className="text-sm text-green-800 dark:text-green-200">
Tokens auto-detected from Cursor IDE successfully!
</p>
</div>
</div>
)}
{/* Info message if not auto-detected */}
{!autoDetected && !error && (
<div className="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg border border-blue-200 dark:border-blue-800">
<div className="flex gap-2">
<span className="material-symbols-outlined text-blue-600 dark:text-blue-400">info</span>
<p className="text-sm text-blue-800 dark:text-blue-200">
Cursor IDE not detected. Please paste your tokens manually.
</p>
</div>
</div>
)}
{/* Access Token Input */}
<div>
<label className="block text-sm font-medium mb-2">
Access Token <span className="text-red-500">*</span>
</label>
<textarea
value={accessToken}
onChange={(e) => setAccessToken(e.target.value)}
placeholder="Access token will be auto-filled..."
rows={3}
className="w-full px-3 py-2 text-sm font-mono border border-border rounded-lg bg-background focus:outline-none focus:border-primary resize-none"
/>
</div>
{/* Machine ID Input */}
<div>
<label className="block text-sm font-medium mb-2">
Machine ID <span className="text-red-500">*</span>
</label>
<Input
value={machineId}
onChange={(e) => setMachineId(e.target.value)}
placeholder="Machine ID will be auto-filled..."
className="font-mono text-sm"
/>
</div>
{/* Error Display */}
{error && (
<div className="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg border border-red-200 dark:border-red-800">
<p className="text-sm text-red-600 dark:text-red-400">{error}</p>
</div>
)}
{/* Action Buttons */}
<div className="flex gap-2">
<Button
onClick={handleImportToken}
fullWidth
disabled={importing || !accessToken.trim() || !machineId.trim()}
>
{importing ? "Importing..." : "Import Token"}
</Button>
<Button onClick={onClose} variant="ghost" fullWidth>
Cancel
</Button>
</div>
</>
)}
</div>
</Modal>
);
+100 -42
View File
@@ -1,18 +1,12 @@
"use client";
import { useState } from "react";
import { useState, useEffect } from "react";
import PropTypes from "prop-types";
import { Modal, Button, Input } from "@/shared/components";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
/**
* Kiro Auth Method Selection Modal
* Allows user to choose between multiple Kiro authentication methods:
* 1. AWS Builder ID (Device Code)
* 2. AWS IAM Identity Center/IDC (Device Code with custom startUrl/region)
* 3. Google Social Login (Manual callback)
* 4. GitHub Social Login (Manual callback)
* 5. Import Token (Paste refresh token)
* Auto-detects token from AWS SSO cache or allows manual import
*/
export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
const [selectedMethod, setSelectedMethod] = useState(null);
@@ -21,7 +15,37 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
const [refreshToken, setRefreshToken] = useState("");
const [error, setError] = useState(null);
const [importing, setImporting] = useState(false);
const { copied, copy } = useCopyToClipboard();
const [autoDetecting, setAutoDetecting] = useState(false);
const [autoDetected, setAutoDetected] = useState(false);
// Auto-detect token when import method is selected
useEffect(() => {
if (selectedMethod !== "import" || !isOpen) return;
const autoDetect = async () => {
setAutoDetecting(true);
setError(null);
setAutoDetected(false);
try {
const res = await fetch("/api/oauth/kiro/auto-import");
const data = await res.json();
if (data.found) {
setRefreshToken(data.refreshToken);
setAutoDetected(true);
} else {
setError(data.error || "Could not auto-detect token");
}
} catch (err) {
setError("Failed to auto-detect token");
} finally {
setAutoDetecting(false);
}
};
autoDetect();
}, [selectedMethod, isOpen]);
const handleMethodSelect = (method) => {
setSelectedMethod(method);
@@ -275,42 +299,76 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
{/* Import Token */}
{selectedMethod === "import" && (
<div className="space-y-4">
<div className="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg border border-blue-200 dark:border-blue-800 mb-4">
<p className="text-sm text-blue-800 dark:text-blue-200">
💡 Please login to Kiro IDE first.
</p>
</div>
<div>
<label className="block text-sm font-medium mb-2">
Refresh Token <span className="text-red-500">*</span>
</label>
<Input
value={refreshToken}
onChange={(e) => setRefreshToken(e.target.value)}
placeholder="aorAAAAAG..."
className="font-mono text-sm"
type="password"
/>
<p className="text-xs text-text-muted mt-1">
Find it in Kiro IDE at: <code className="bg-sidebar px-1 rounded">~/.aws/sso/cache/kiro-auth-token.json</code>
</p>
</div>
{error && (
<div className="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg">
<p className="text-sm text-red-600 dark:text-red-400">{error}</p>
{/* Auto-detecting state */}
{autoDetecting && (
<div className="text-center py-6">
<div className="size-16 mx-auto mb-4 rounded-full bg-primary/10 flex items-center justify-center">
<span className="material-symbols-outlined text-3xl text-primary animate-spin">
progress_activity
</span>
</div>
<h3 className="text-lg font-semibold mb-2">Auto-detecting token...</h3>
<p className="text-sm text-text-muted">
Reading from AWS SSO cache
</p>
</div>
)}
<div className="flex gap-2">
<Button onClick={handleImportToken} fullWidth disabled={importing}>
{importing ? "Importing..." : "Import Token"}
</Button>
<Button onClick={handleBack} variant="ghost" fullWidth>
Back
</Button>
</div>
{/* Form (shown after auto-detect completes) */}
{!autoDetecting && (
<>
{/* Success message if auto-detected */}
{autoDetected && (
<div className="bg-green-50 dark:bg-green-900/20 p-3 rounded-lg border border-green-200 dark:border-green-800">
<div className="flex gap-2">
<span className="material-symbols-outlined text-green-600 dark:text-green-400">check_circle</span>
<p className="text-sm text-green-800 dark:text-green-200">
Token auto-detected from Kiro IDE successfully!
</p>
</div>
</div>
)}
{/* Info message if not auto-detected */}
{!autoDetected && !error && (
<div className="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-lg border border-blue-200 dark:border-blue-800">
<div className="flex gap-2">
<span className="material-symbols-outlined text-blue-600 dark:text-blue-400">info</span>
<p className="text-sm text-blue-800 dark:text-blue-200">
Kiro IDE not detected. Please paste your refresh token manually.
</p>
</div>
</div>
)}
<div>
<label className="block text-sm font-medium mb-2">
Refresh Token <span className="text-red-500">*</span>
</label>
<Input
value={refreshToken}
onChange={(e) => setRefreshToken(e.target.value)}
placeholder="Token will be auto-filled..."
className="font-mono text-sm"
/>
</div>
{error && (
<div className="bg-red-50 dark:bg-red-900/20 p-3 rounded-lg border border-red-200 dark:border-red-800">
<p className="text-sm text-red-600 dark:text-red-400">{error}</p>
</div>
)}
<div className="flex gap-2">
<Button onClick={handleImportToken} fullWidth disabled={importing || !refreshToken.trim()}>
{importing ? "Importing..." : "Import Token"}
</Button>
<Button onClick={handleBack} variant="ghost" fullWidth>
Back
</Button>
</div>
</>
)}
</div>
)}
</div>
+1 -1
View File
@@ -25,7 +25,7 @@ export default function RequestLogger() {
const fetchLogs = async (showLoading = true) => {
if (showLoading) setLoading(true);
try {
const res = await fetch("/api/usage/logs");
const res = await fetch("/api/usage/request-logs");
if (res.ok) {
const data = await res.json();
setLogs(data);