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

@@ -0,0 +1,167 @@
// Claude → Kiro (direct route) request translation + Kiro → Claude response.
// Verifies the direct claude:kiro / kiro:claude routes added to bypass the
// OpenAI pivot, and that the "Improperly formed request" 400-guards survive.
import { describe, it, expect } from "vitest";
import "./registerAll.js";
import { translateRequest, translateResponse } from "../../open-sse/translator/index.js";
import { FORMATS } from "../../open-sse/translator/formats.js";
const C2K = (body) =>
translateRequest(FORMATS.CLAUDE, FORMATS.KIRO, "claude-sonnet-4.5", body, true, null, "kiro");
describe("Claude → Kiro (direct route)", () => {
it("produces a Kiro conversationState payload", () => {
const out = C2K({ messages: [{ role: "user", content: "hello" }] });
expect(out.conversationState).toBeTruthy();
expect(out.conversationState.currentMessage.userInputMessage.content).toContain("hello");
});
it("guard 1: with no tools, a dangling tool_result is flattened to text (no structured ref)", () => {
// Client omitted `tools` but kept a tool_result after compaction.
const out = C2K({
messages: [
{ role: "user", content: "go" },
{ role: "assistant", content: [{ type: "tool_use", id: "t1", name: "f", input: {} }] },
{ role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "result" }] },
],
});
// No userInputMessageContext.tools/toolResults anywhere → won't trip the
// "tools required" validator.
const cur = out.conversationState.currentMessage.userInputMessage;
expect(cur.userInputMessageContext?.toolResults).toBeFalsy();
const everyHistoryClean = out.conversationState.history.every(
(h) => !h.userInputMessage?.userInputMessageContext?.toolResults
);
expect(everyHistoryClean).toBe(true);
});
it("guard 2: with tools, an orphaned tool_result is folded into user text", () => {
const out = C2K({
tools: [{ name: "f", description: "fn", input_schema: { type: "object", properties: {} } }],
messages: [
{ role: "user", content: "go" },
// tool_result references a tool_use that never appears → orphan
{ role: "user", content: [{ type: "tool_result", tool_use_id: "ghost", content: "salvage me" }] },
],
});
const cur = out.conversationState.currentMessage.userInputMessage;
// The orphan content survives as text, not as a dangling structured ref.
expect(cur.content).toContain("salvage me");
expect(cur.userInputMessageContext?.toolResults?.length ?? 0).toBe(0);
});
it("injects thinking_mode tag when model implies thinking", () => {
const out = translateRequest(
FORMATS.CLAUDE,
FORMATS.KIRO,
"claude-sonnet-4.5-thinking",
{ messages: [{ role: "user", content: "hi" }] },
true,
null,
"kiro"
);
expect(out.conversationState.currentMessage.userInputMessage.content).toContain(
"<thinking_mode>enabled</thinking_mode>"
);
});
});
describe("Kiro → Claude (direct route, OpenAI-shaped chunks from executor)", () => {
// KiroExecutor emits chat.completion.chunk objects; translateResponse must
// convert them to Claude SSE events.
const R = (chunk, state) => translateResponse(FORMATS.KIRO, FORMATS.CLAUDE, chunk, state);
it("first text chunk emits message_start + content_block_start + text_delta", () => {
const state = {};
const events = R(
{
id: "chatcmpl-1",
object: "chat.completion.chunk",
model: "claude-sonnet-4.5",
choices: [{ index: 0, delta: { role: "assistant", content: "Hi" }, finish_reason: null }],
},
state
);
const types = events.map((e) => e.type);
expect(types).toContain("message_start");
expect(types).toContain("content_block_start");
expect(types).toContain("content_block_delta");
const delta = events.find((e) => e.type === "content_block_delta");
expect(delta.delta).toEqual({ type: "text_delta", text: "Hi" });
});
it("finish chunk emits message_delta + message_stop with stop_reason", () => {
const state = {};
R(
{
id: "chatcmpl-1",
object: "chat.completion.chunk",
model: "m",
choices: [{ index: 0, delta: { content: "x" }, finish_reason: null }],
},
state
);
const events = R(
{
id: "chatcmpl-1",
object: "chat.completion.chunk",
model: "m",
choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
usage: { prompt_tokens: 5, completion_tokens: 3 },
},
state
);
const md = events.find((e) => e.type === "message_delta");
expect(md.delta.stop_reason).toBe("end_turn");
expect(md.usage).toEqual({ input_tokens: 5, output_tokens: 3 });
expect(events.some((e) => e.type === "message_stop")).toBe(true);
});
it("reasoning_content maps to a thinking block", () => {
const state = {};
const events = R(
{
id: "chatcmpl-1",
object: "chat.completion.chunk",
model: "m",
choices: [{ index: 0, delta: { reasoning_content: "pondering" }, finish_reason: null }],
},
state
);
const start = events.find((e) => e.type === "content_block_start");
expect(start.content_block.type).toBe("thinking");
const delta = events.find((e) => e.type === "content_block_delta");
expect(delta.delta).toEqual({ type: "thinking_delta", thinking: "pondering" });
});
it("tool_calls map to a tool_use block with buffered input_json_delta", () => {
const state = {};
R(
{
id: "c", object: "chat.completion.chunk", model: "m",
choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "tu1", type: "function", function: { name: "search", arguments: "" } }] }, finish_reason: null }],
},
state
);
R(
{
id: "c", object: "chat.completion.chunk", model: "m",
choices: [{ index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: '{"q":"x"}' } }] }, finish_reason: null }],
},
state
);
const events = R(
{
id: "c", object: "chat.completion.chunk", model: "m",
choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }],
},
state
);
const jsonDelta = events.find(
(e) => e.type === "content_block_delta" && e.delta.type === "input_json_delta"
);
expect(jsonDelta.delta.partial_json).toBe('{"q":"x"}');
const md = events.find((e) => e.type === "message_delta");
expect(md.delta.stop_reason).toBe("tool_use");
});
});

View File

@@ -11,6 +11,7 @@ import "../../open-sse/translator/request/openai-to-kiro.js";
import "../../open-sse/translator/request/openai-to-cursor.js";
import "../../open-sse/translator/request/openai-to-ollama.js";
import "../../open-sse/translator/request/openai-to-commandcode.js";
import "../../open-sse/translator/request/claude-to-kiro.js";
import "../../open-sse/translator/response/claude-to-openai.js";
import "../../open-sse/translator/response/openai-to-claude.js";
import "../../open-sse/translator/response/gemini-to-openai.js";
@@ -20,3 +21,4 @@ import "../../open-sse/translator/response/kiro-to-openai.js";
import "../../open-sse/translator/response/cursor-to-openai.js";
import "../../open-sse/translator/response/ollama-to-openai.js";
import "../../open-sse/translator/response/commandcode-to-openai.js";
import "../../open-sse/translator/response/kiro-to-claude.js";

View File

@@ -0,0 +1,63 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { KiroService } from "../../src/lib/oauth/services/kiro.js";
/**
* Regression tests for Kiro API-key auth.
*
* KiroService.validateApiKey resolves a profileArn with the key (via
* CodeWhisperer ListAvailableProfiles) and returns a credential shaped for
* persistence with authMethod="api_key". The response profile field name
* varies (`arn` vs `profileArn`) — both are accepted by listAvailableProfiles.
*
* Note: OAuth (Builder ID / IDC) profileArn resolution is handled upstream by
* fetchKiroProfileArn in providers.js and is covered there — not here.
*/
describe("kiro API-key auth (KiroService.validateApiKey)", () => {
beforeEach(() => vi.restoreAllMocks());
afterEach(() => vi.restoreAllMocks());
it("validates an API key and resolves a credential with profileArn", async () => {
const expectedArn = "arn:aws:codewhisperer:us-east-1:444:profile/KEY";
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
json: async () => ({ profiles: [{ arn: expectedArn }] }),
});
const svc = new KiroService();
const cred = await svc.validateApiKey(" my-secret-key ");
expect(cred).toEqual({
accessToken: "my-secret-key",
refreshToken: null,
profileArn: expectedArn,
region: "us-east-1",
authMethod: "api_key",
});
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("https://codewhisperer.us-east-1.amazonaws.com");
expect(init.headers.Authorization).toBe("Bearer my-secret-key");
expect(init.headers["x-amz-target"]).toBe(
"AmazonCodeWhispererService.ListAvailableProfiles"
);
});
it("rejects an empty API key without a network call", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch");
const svc = new KiroService();
await expect(svc.validateApiKey(" ")).rejects.toThrow("API key is required");
expect(fetchMock).not.toHaveBeenCalled();
});
it("surfaces a validation error when the key is rejected", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: false,
status: 401,
text: async () => "Unauthorized",
});
const svc = new KiroService();
await expect(svc.validateApiKey("bad-key")).rejects.toThrow(
/API key validation failed/
);
});
});

View File

@@ -9,6 +9,10 @@ export default defineConfig({
environment: "node",
globals: true,
include: ["**/*.test.js"],
// Don't scan into git worktrees nested under .claude/ — they carry their
// own copies of the test files but lack an installed node_modules (open-sse,
// etc.), which makes provider imports fail during collection.
exclude: ["**/node_modules/**", "**/.claude/**", "**/dist/**"],
// Allow many it.concurrent cases (real provider smoke runs ~50 providers in parallel)
maxConcurrency: 60,
// Suppress noisy console output from handlers under test