mirror of
https://github.com/Nezumi-2711/9router.git
synced 2026-09-22 20:00:47 +00:00
feat(kiro): add external_idp CLIProxyAPI import for Microsoft SSO
Import Kiro accounts authenticated via Microsoft Entra/365 SSO using CLIProxyAPI JSON. Adds external_idp refresh path (form-encoded OAuth2, Microsoft login host allowlist), TokenType: EXTERNAL_IDP header for runtime and usage/quota requests, dashboard import UI, and unit tests. Scoped to authMethod === "external_idp"; existing Kiro auth unchanged. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
committed by
decolua
co-authored by
Cursor
parent
49a3ec7a72
commit
a4f44e3e12
@@ -0,0 +1,40 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { createProviderConnection } from "@/models";
|
||||
import { normalizeKiroExternalIdpAuth } from "@/lib/oauth/kiroExternalIdp";
|
||||
|
||||
/**
|
||||
* POST /api/oauth/kiro/import-cli-proxy
|
||||
* Import Kiro CLIProxyAPI auth JSON for Microsoft external_idp accounts.
|
||||
*/
|
||||
export async function POST(request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const rawAuth = body?.cliProxyAuth ?? body?.auth ?? body?.json ?? body;
|
||||
const tokenData = normalizeKiroExternalIdpAuth(rawAuth);
|
||||
|
||||
const connection = await createProviderConnection({
|
||||
provider: "kiro",
|
||||
authType: "oauth",
|
||||
accessToken: tokenData.accessToken,
|
||||
refreshToken: tokenData.refreshToken,
|
||||
expiresAt: tokenData.expiresAt,
|
||||
email: tokenData.email || null,
|
||||
providerSpecificData: tokenData.providerSpecificData,
|
||||
testStatus: "active",
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
connection: {
|
||||
id: connection.id,
|
||||
provider: connection.provider,
|
||||
email: connection.email,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: error?.message || "CLIProxyAPI import failed" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
const MICROSOFT_TOKEN_ENDPOINT_HOSTS = new Set([
|
||||
"login.microsoftonline.com",
|
||||
"login.microsoft.com",
|
||||
"login.windows.net",
|
||||
]);
|
||||
|
||||
const DEFAULT_REGION = "us-east-1";
|
||||
const DEFAULT_EXPIRES_IN = 3600;
|
||||
|
||||
function normalizeString(value) {
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export function validateMicrosoftTokenEndpoint(rawEndpoint) {
|
||||
const tokenEndpoint = normalizeString(rawEndpoint);
|
||||
if (!tokenEndpoint) throw new Error("token_endpoint is required");
|
||||
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(tokenEndpoint);
|
||||
} catch {
|
||||
throw new Error("token_endpoint must be a valid URL");
|
||||
}
|
||||
|
||||
if (parsed.protocol !== "https:") {
|
||||
throw new Error("token_endpoint must use https");
|
||||
}
|
||||
|
||||
const host = parsed.hostname.toLowerCase();
|
||||
if (!MICROSOFT_TOKEN_ENDPOINT_HOSTS.has(host)) {
|
||||
throw new Error("token_endpoint must be a Microsoft login endpoint");
|
||||
}
|
||||
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
export function normalizeScope(scopes) {
|
||||
if (Array.isArray(scopes)) {
|
||||
return scopes.map(normalizeString).filter(Boolean).join(" ");
|
||||
}
|
||||
return normalizeString(scopes);
|
||||
}
|
||||
|
||||
export function decodeJwtPayload(jwt) {
|
||||
try {
|
||||
if (!jwt || typeof jwt !== "string") return null;
|
||||
const parts = jwt.split(".");
|
||||
if (parts.length !== 3) return null;
|
||||
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
||||
const padding = (4 - (base64.length % 4)) % 4;
|
||||
return JSON.parse(Buffer.from(`${base64}${"=".repeat(padding)}`, "base64").toString("utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveExpiresAt(input) {
|
||||
const explicit = input.expired || input.expires_at || input.expiresAt;
|
||||
if (explicit) {
|
||||
const ms = new Date(explicit).getTime();
|
||||
if (Number.isFinite(ms)) return new Date(ms).toISOString();
|
||||
}
|
||||
|
||||
const expiresIn = Number(input.expires_in || input.expiresIn || 0);
|
||||
if (Number.isFinite(expiresIn) && expiresIn > 0) {
|
||||
return new Date(Date.now() + expiresIn * 1000).toISOString();
|
||||
}
|
||||
|
||||
const payload = decodeJwtPayload(input.access_token || input.accessToken);
|
||||
if (payload?.exp) {
|
||||
return new Date(payload.exp * 1000).toISOString();
|
||||
}
|
||||
|
||||
return new Date(Date.now() + DEFAULT_EXPIRES_IN * 1000).toISOString();
|
||||
}
|
||||
|
||||
export function normalizeKiroExternalIdpAuth(rawAuth) {
|
||||
let input = rawAuth;
|
||||
if (typeof input === "string") {
|
||||
try {
|
||||
input = JSON.parse(input);
|
||||
} catch {
|
||||
throw new Error("CLIProxyAPI auth JSON is invalid");
|
||||
}
|
||||
}
|
||||
|
||||
if (!input || typeof input !== "object") {
|
||||
throw new Error("CLIProxyAPI auth JSON is required");
|
||||
}
|
||||
|
||||
const authMethod = normalizeString(input.auth_method || input.authMethod);
|
||||
if (authMethod && authMethod !== "external_idp") {
|
||||
throw new Error("Only external_idp Kiro auth is supported by this importer");
|
||||
}
|
||||
|
||||
const accessToken = normalizeString(input.access_token || input.accessToken);
|
||||
const refreshToken = normalizeString(input.refresh_token || input.refreshToken);
|
||||
const clientId = normalizeString(input.client_id || input.clientId);
|
||||
const tokenEndpoint = validateMicrosoftTokenEndpoint(input.token_endpoint || input.tokenEndpoint);
|
||||
const profileArn = normalizeString(input.profile_arn || input.profileArn);
|
||||
const region = normalizeString(input.region) || DEFAULT_REGION;
|
||||
const scope = normalizeScope(input.scopes || input.scope);
|
||||
|
||||
if (!accessToken) throw new Error("access_token is required");
|
||||
if (!refreshToken) throw new Error("refresh_token is required");
|
||||
if (!clientId) throw new Error("client_id is required");
|
||||
if (!scope) throw new Error("scopes is required");
|
||||
if (!profileArn) throw new Error("profile_arn is required");
|
||||
|
||||
const payload = decodeJwtPayload(accessToken);
|
||||
const email = input.email || payload?.email || payload?.preferred_username || payload?.upn || payload?.sub || null;
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken,
|
||||
expiresAt: resolveExpiresAt(input),
|
||||
email,
|
||||
providerSpecificData: {
|
||||
profileArn,
|
||||
region,
|
||||
authMethod: "external_idp",
|
||||
provider: "CLIProxyAPI",
|
||||
clientId,
|
||||
tokenEndpoint,
|
||||
scope,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildExternalIdpRefreshParams(refreshToken, providerSpecificData = {}) {
|
||||
const clientId = normalizeString(providerSpecificData.clientId || providerSpecificData.client_id);
|
||||
const tokenEndpoint = validateMicrosoftTokenEndpoint(providerSpecificData.tokenEndpoint || providerSpecificData.token_endpoint);
|
||||
const scope = normalizeScope(providerSpecificData.scope || providerSpecificData.scopes);
|
||||
|
||||
if (!refreshToken) throw new Error("refresh token is required");
|
||||
if (!clientId) throw new Error("clientId is required for external_idp refresh");
|
||||
if (!scope) throw new Error("scope is required for external_idp refresh");
|
||||
|
||||
return {
|
||||
tokenEndpoint,
|
||||
body: new URLSearchParams({
|
||||
grant_type: "refresh_token",
|
||||
client_id: clientId,
|
||||
refresh_token: refreshToken,
|
||||
scope,
|
||||
}),
|
||||
providerSpecificData: {
|
||||
...providerSpecificData,
|
||||
authMethod: "external_idp",
|
||||
clientId,
|
||||
tokenEndpoint,
|
||||
scope,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,7 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
|
||||
const [idcStartUrl, setIdcStartUrl] = useState("");
|
||||
const [idcRegion, setIdcRegion] = useState("us-east-1");
|
||||
const [refreshToken, setRefreshToken] = useState("");
|
||||
const [cliProxyJson, setCliProxyJson] = useState("");
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [apiKeyRegion, setApiKeyRegion] = useState("us-east-1");
|
||||
const [error, setError] = useState(null);
|
||||
@@ -105,6 +106,36 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportCliProxyJson = async () => {
|
||||
if (!cliProxyJson.trim()) {
|
||||
setError("Please paste CLIProxyAPI auth JSON");
|
||||
return;
|
||||
}
|
||||
|
||||
setImporting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/oauth/kiro/import-cli-proxy", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ json: cliProxyJson.trim() }),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || "CLIProxyAPI import failed");
|
||||
}
|
||||
|
||||
onMethodSelect("import-cli-proxy");
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleIdcContinue = () => {
|
||||
if (!idcStartUrl.trim()) {
|
||||
setError("Please enter your IDC start URL");
|
||||
@@ -256,6 +287,22 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{/* Import CLIProxyAPI JSON */}
|
||||
<button
|
||||
onClick={() => handleMethodSelect("import-cli-proxy")}
|
||||
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">data_object</span>
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold mb-1">Import CLIProxyAPI JSON</h3>
|
||||
<p className="text-sm text-text-muted">
|
||||
Paste external_idp auth JSON from CLIProxyAPI/Kiro Microsoft login.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -495,6 +542,47 @@ export default function KiroAuthModal({ isOpen, onMethodSelect, onClose }) {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import CLIProxyAPI JSON */}
|
||||
{selectedMethod === "import-cli-proxy" && (
|
||||
<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 the Kiro CLIProxyAPI auth JSON containing auth_method=external_idp. Only Microsoft login token endpoints are accepted.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium mb-2">
|
||||
CLIProxyAPI Auth JSON <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<textarea
|
||||
value={cliProxyJson}
|
||||
onChange={(e) => setCliProxyJson(e.target.value)}
|
||||
placeholder={'{"auth_method":"external_idp","access_token":"...","refresh_token":"...","client_id":"...","token_endpoint":"https://login.microsoftonline.com/.../oauth2/v2.0/token","profile_arn":"...","scopes":"..."}'}
|
||||
className="min-h-40 w-full rounded-md border border-border bg-background p-3 font-mono text-sm outline-none focus:border-primary"
|
||||
/>
|
||||
</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={handleImportCliProxyJson} fullWidth disabled={importing || !cliProxyJson.trim()}>
|
||||
{importing ? "Importing..." : "Import CLIProxyAPI JSON"}
|
||||
</Button>
|
||||
<Button onClick={handleBack} variant="ghost" fullWidth>
|
||||
Back
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user