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" });