feat(kiro): headless API-key auth + direct Claude/Kiro route

Adds long-lived API-key (ksk_) authentication for Kiro/AWS CodeWhisperer
and a direct claude:kiro / kiro:claude translation route that avoids the
lossy OpenAI two-hop pivot.

- translator: claude-to-kiro request + kiro-to-claude response translators,
  registered on the exact source:target pair (direct route ahead of the
  OpenAI pivot in index.js). claude-to-kiro uses shared schema constants
  (ROLE/CLAUDE_BLOCK/DEFAULT_IMAGE_MIME) per app convention.
- auth: POST /api/oauth/kiro/api-key imports + validates a key via
  ListAvailableProfiles, persists authMethod="api_key" (no refresh token).
- executor: send tokentype: API_KEY header and try *.amazonaws.com hosts
  first for api-key creds; OAuth keeps kiro.dev first.
- fix: never inject the default placeholder profileArn for api-key auth
  (CodeWhisperer 403s an ARN not owned by the key's account).
- ui: API Key method in the Kiro connect modal; surface api-key accounts
  on the Quota Tracker and provider count.
- stream: env-overridable TTFT vs stall timeouts + Kiro keepalive frame.
- tests: claude-kiro-direct + kiro-profile-arn (11 tests).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
thienpv
2026-06-17 10:01:30 +07:00
committed by decolua
parent 3de6ce157c
commit 706e6513c9
20 changed files with 1437 additions and 57 deletions

View File

@@ -166,8 +166,9 @@ export default function ProvidersPage() {
}, []);
const getProviderStats = (providerId, authType) => {
const authTypes = Array.isArray(authType) ? authType : [authType];
const providerConnections = connections.filter(
(c) => c.provider === providerId && c.authType === authType,
(c) => c.provider === providerId && authTypes.includes(c.authType),
);
const getEffectiveStatus = (conn) => {
@@ -208,17 +209,15 @@ export default function ProvidersPage() {
return { connected, error, total, errorCode, errorTime, allDisabled };
};
// Toggle all connections for a provider on/off
// Toggle all connections for a provider on/off. authType may be a single
// string or an array (kiro counts oauth + api_key/apikey together).
const handleToggleProvider = async (providerId, authType, newActive) => {
const providerConns = connections.filter(
(c) => c.provider === providerId && c.authType === authType,
);
const authTypes = Array.isArray(authType) ? authType : [authType];
const matches = (c) =>
c.provider === providerId && authTypes.includes(c.authType);
const providerConns = connections.filter(matches);
setConnections((prev) =>
prev.map((c) =>
c.provider === providerId && c.authType === authType
? { ...c, isActive: newActive }
: c,
),
prev.map((c) => (matches(c) ? { ...c, isActive: newActive } : c)),
);
await Promise.allSettled(
providerConns.map((c) =>
@@ -465,16 +464,26 @@ export default function ProvidersPage() {
</button>
</div>
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3 xl:grid-cols-4">
{freeEntries.map(([key, info]) => (
<ProviderCard
key={key}
providerId={key}
provider={info}
stats={getProviderStats(key, "oauth")}
authType="free"
onToggle={(active) => handleToggleProvider(key, "oauth", active)}
/>
))}
{freeEntries.map(([key, info]) => {
// Kiro accepts both OAuth and api-key connections; count/toggle both
// so the card total matches the provider detail page (#kiro-apikey).
// Kiro's headless api-key flow persists authType "api_key" (underscore),
// while generic apikey providers use "apikey" — include both spellings.
const freeAuthTypes =
key === "kiro" ? ["oauth", "apikey", "api_key"] : "oauth";
return (
<ProviderCard
key={key}
providerId={key}
provider={info}
stats={getProviderStats(key, freeAuthTypes)}
authType="free"
onToggle={(active) =>
handleToggleProvider(key, freeAuthTypes, active)
}
/>
);
})}
{freeTierEntries.map(([key, info]) => (
<ApiKeyProviderCard
key={key}

View File

@@ -37,6 +37,36 @@ import {
import Card from "@/shared/components/Card";
import { ConfirmModal, EditConnectionModal } from "@/shared/components";
import { USAGE_SUPPORTED_PROVIDERS } from "@/shared/constants/providers";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
// Maps the stored providerSpecificData.authMethod to a human label for Kiro.
// Values come from the Kiro connect flows: builder-id/idc (device code),
// google/github (social), imported (refresh-token paste), api_key (headless).
const KIRO_METHOD_LABELS = {
"builder-id": "AWS Builder ID",
idc: "IAM Identity Center",
google: "Google",
github: "GitHub",
imported: "Imported Token",
api_key: "API Key",
};
function kiroMethodLabel(conn) {
const m = conn.providerSpecificData?.authMethod;
if (m && KIRO_METHOD_LABELS[m]) return KIRO_METHOD_LABELS[m];
return conn.authType === "api_key" ? "API Key" : "OAuth";
}
// Region is stored for builder-id/idc/api_key flows; social and imported flows
// omit it, so fall back to the region segment of the profileArn
// (arn:aws:codewhisperer:<region>:...).
function kiroRegion(conn) {
const r = conn.providerSpecificData?.region;
if (r) return r;
const arn = conn.providerSpecificData?.profileArn;
const seg = typeof arn === "string" ? arn.split(":")[3] : "";
return seg || "";
}
function getCodexResetCreditCount(quota) {
const value = quota?.raw?.resetCredits?.availableCount;
@@ -45,6 +75,7 @@ function getCodexResetCreditCount(quota) {
}
export default function ProviderLimits() {
const { copied, copy } = useCopyToClipboard();
const [connections, setConnections] = useState([]);
const [quotaData, setQuotaData] = useState({});
const [loading, setLoading] = useState({});
@@ -892,6 +923,46 @@ export default function ProviderLimits() {
Reset eligible: {resetCreditCount}
</p>
)}
{conn.provider === "kiro" && (
<div className="mt-1 flex flex-wrap items-center gap-1">
<span className="rounded-full bg-brand-500/10 px-2 py-0.5 text-[10px] font-semibold text-brand-600 dark:text-brand-300">
{kiroMethodLabel(conn)}
</span>
{kiroRegion(conn) && (
<span className="rounded-full bg-blue-500/10 px-2 py-0.5 text-[10px] font-semibold text-blue-600 dark:text-blue-400">
{kiroRegion(conn)}
</span>
)}
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${
isInactive
? "bg-surface-2 text-text-muted"
: conn.testStatus === "active" || conn.testStatus === "success"
? "bg-green-500/10 text-green-600 dark:text-green-400"
: conn.testStatus === "error" || conn.testStatus === "expired" || conn.testStatus === "unavailable"
? "bg-red-500/10 text-red-600 dark:text-red-400"
: "bg-surface-2 text-text-muted"
}`}
>
{isInactive ? "disabled" : conn.testStatus || "unknown"}
</span>
{conn.providerSpecificData?.profileArn && (
<button
type="button"
onClick={() => copy(conn.providerSpecificData.profileArn, conn.id)}
title={conn.providerSpecificData.profileArn}
className="inline-flex max-w-full items-center gap-1 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] text-text-muted transition-colors hover:text-primary"
>
<span className="material-symbols-outlined text-[12px]">
{copied === conn.id ? "check" : "content_copy"}
</span>
<code className="truncate font-mono">
{conn.providerSpecificData.profileArn}
</code>
</button>
)}
</div>
)}
</div>
</div>

View File

@@ -0,0 +1,63 @@
import { NextResponse } from "next/server";
import { KiroService } from "@/lib/oauth/services/kiro";
import { createProviderConnection } from "@/models";
/**
* POST /api/oauth/kiro/api-key
* Import a Kiro API key (headless auth). The key is a long-lived bearer
* credential — there is no refresh token. It is validated by listing
* CodeWhisperer profiles, then stored with authMethod="api_key".
*/
export async function POST(request) {
try {
const { apiKey, region } = await request.json();
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
return NextResponse.json(
{ error: "API key is required" },
{ status: 400 }
);
}
const kiroService = new KiroService();
// Validate the key and resolve its profileArn via ListAvailableProfiles
const credential = await kiroService.validateApiKey(
apiKey,
region || "us-east-1"
);
// Extract email from JWT if the key happens to be a JWT (optional display)
const email = kiroService.extractEmailFromJWT(credential.accessToken);
// API keys never expire on a fixed schedule; persist a long horizon so the
// proactive refresh path (which requires a refreshToken anyway) is skipped.
const connection = await createProviderConnection({
provider: "kiro",
authType: "api_key",
accessToken: credential.accessToken,
refreshToken: null,
expiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString(),
email: email || null,
providerSpecificData: {
profileArn: credential.profileArn,
region: credential.region,
authMethod: "api_key",
provider: "API Key",
},
testStatus: "active",
});
return NextResponse.json({
success: true,
connection: {
id: connection.id,
provider: connection.provider,
email: connection.email,
},
});
} catch (error) {
console.log("Kiro API key import error:", error);
return NextResponse.json({ error: error.message }, { status: 500 });
}
}

View File

@@ -17,6 +17,7 @@ const SAFE_PSD_FIELDS = [
"connectionProxyEnabled", "connectionProxyUrl", "connectionNoProxy",
"githubLogin", "githubName", "githubEmail", "githubUserId",
"username", "firstName", "lastName", "authMethod", "authKind",
"profileArn",
];
const DEFAULT_PAGE_SIZE = 20;

View File

@@ -131,11 +131,14 @@ export async function GET(request, { params }) {
return Response.json({ error: "Connection not found" }, { status: 404 });
}
// Allow OAuth connections, plus whitelisted apikey providers (glm/minimax/...)
// Allow OAuth connections, plus whitelisted apikey providers (glm/minimax/kiro/...)
// Kiro's headless api-key flow persists authType "api_key" (underscore) while
// generic apikey providers persist "apikey" — accept both spellings here.
const isOAuth = connection.authType === "oauth";
const isApikeyAuth =
connection.authType === "apikey" || connection.authType === "api_key";
const isApikeyEligible =
connection.authType === "apikey" &&
USAGE_APIKEY_PROVIDERS.includes(connection.provider);
isApikeyAuth && USAGE_APIKEY_PROVIDERS.includes(connection.provider);
if (!isOAuth && !isApikeyEligible) {
return Response.json({ message: "Usage not available for this connection" });

View File

@@ -254,6 +254,67 @@ export class KiroService {
}
}
/**
* List available CodeWhisperer profiles for a token (or API key) and return
* the best-matching profileArn. AWS SSO OIDC logins return no profileArn, so
* it must be fetched separately — the same call works for API-key auth.
* Accepts both `arn` and `profileArn` response field names (the API-key
* JSON-1.0 surface returns `arn`).
*/
async listAvailableProfiles(accessToken, region = "us-east-1") {
const endpoint = `https://codewhisperer.${region}.amazonaws.com`;
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-amz-json-1.0",
"x-amz-target": "AmazonCodeWhispererService.ListAvailableProfiles",
"Authorization": `Bearer ${accessToken}`,
"Accept": "application/json",
},
body: JSON.stringify({ maxResults: 10 }),
});
if (!response.ok) {
const error = await response.text();
throw new Error(`Failed to list profiles: ${error}`);
}
const data = await response.json();
const profiles = Array.isArray(data?.profiles) ? data.profiles : [];
const arnOf = (p) => p?.arn || p?.profileArn || null;
const match = profiles.find((p) => arnOf(p)?.split(":")[3] === region) || profiles[0];
return arnOf(match);
}
/**
* Validate an API-key credential by listing profiles with it. API keys are
* long-lived bearer tokens (no refresh), so the only way to validate one is
* to make an authenticated CodeWhisperer call. Returns a credential object
* ready to persist as a "kiro" connection with authMethod="api_key".
*/
async validateApiKey(apiKey, region = "us-east-1") {
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
throw new Error("API key is required");
}
const trimmed = apiKey.trim();
let profileArn = null;
try {
profileArn = await this.listAvailableProfiles(trimmed, region);
} catch (error) {
throw new Error(`API key validation failed: ${error.message}`);
}
return {
accessToken: trimmed,
refreshToken: null,
profileArn,
region,
authMethod: "api_key",
};
}
/**
* List available models from CodeWhisperer API
*/

View File

@@ -13,6 +13,8 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
const [idcStartUrl, setIdcStartUrl] = useState("");
const [idcRegion, setIdcRegion] = useState("us-east-1");
const [refreshToken, setRefreshToken] = useState("");
const [apiKey, setApiKey] = useState("");
const [apiKeyRegion, setApiKeyRegion] = useState("us-east-1");
const [error, setError] = useState(null);
const [importing, setImporting] = useState(false);
const [autoDetecting, setAutoDetecting] = useState(false);
@@ -96,6 +98,40 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
onMethodSelect("idc", { startUrl: idcStartUrl.trim(), region: idcRegion });
};
const handleApiKeyImport = async () => {
if (!apiKey.trim()) {
setError("Please enter an API key");
return;
}
setImporting(true);
setError(null);
try {
const res = await fetch("/api/oauth/kiro/api-key", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
apiKey: apiKey.trim(),
region: apiKeyRegion.trim() || "us-east-1",
}),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "Import failed");
}
// Success - notify parent to refresh connections
onMethodSelect("api-key");
} catch (err) {
setError(err.message);
} finally {
setImporting(false);
}
};
const handleSocialLogin = (provider) => {
onMethodSelect("social", { provider });
};
@@ -142,6 +178,22 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
</div>
</button>
{/* AWS API Key */}
<button
onClick={() => handleMethodSelect("api-key")}
className="w-full p-4 text-left border border-border rounded-lg hover:bg-sidebar transition-colors"
>
<div className="flex items-start gap-3">
<span className="material-symbols-outlined text-primary mt-0.5">key</span>
<div className="flex-1">
<h3 className="font-semibold mb-1">API Key</h3>
<p className="text-sm text-text-muted">
Use a long-lived Kiro/CodeWhisperer API key (headless auth).
</p>
</div>
</div>
</button>
{/* Google Social Login - HIDDEN */}
<button
onClick={() => handleMethodSelect("social-google")}
@@ -240,6 +292,63 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
</div>
)}
{/* API Key */}
{selectedMethod === "api-key" && (
<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">
<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">
Paste a long-lived Kiro/CodeWhisperer API key. It is validated
against AWS and stored directly as a bearer credential (no refresh).
</p>
</div>
</div>
<div>
<label className="block text-sm font-medium mb-2">
API Key <span className="text-red-500">*</span>
</label>
<Input
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="Paste your Kiro API key..."
className="font-mono text-sm"
/>
</div>
<div>
<label className="block text-sm font-medium mb-2">
AWS Region
</label>
<Input
value={apiKeyRegion}
onChange={(e) => setApiKeyRegion(e.target.value)}
placeholder="us-east-1"
className="font-mono text-sm"
/>
<p className="text-xs text-text-muted mt-1">
AWS region for the key (default: us-east-1)
</p>
</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={handleApiKeyImport} fullWidth disabled={importing || !apiKey.trim()}>
{importing ? "Validating..." : "Add API Key"}
</Button>
<Button onClick={handleBack} variant="ghost" fullWidth>
Back
</Button>
</div>
</div>
)}
{/* Social Login Info (Google) */}
{selectedMethod === "social-google" && (
<div className="space-y-4">

View File

@@ -27,8 +27,8 @@ export default function KiroOAuthWrapper({ isOpen, providerInfo, onSuccess, onCl
// Use social login with manual callback
setAuthMethod("social");
setSocialProvider(config.provider);
} else if (method === "import") {
// Import handled in KiroAuthModal, just close
} else if (method === "import" || method === "api-key") {
// Import / API-key handled in KiroAuthModal, just close
onSuccess?.();
}
}, [onSuccess]);