Skip to content

Commit d972876

Browse files
committed
fix(kiro): address remaining review feedback
- preserve explicit environment routing for metadata-less credentials without borrowing local CLI state - settle forced-login recovery only after credential and config persistence both succeed - distinguish same-PID process restarts with a durable process-instance marker - allow email fallback when reauthentication gains a profile ARN - isolate the local-CLI regression fixture from explicit environment routing - add focused regressions for all four review findings
1 parent b1aedd1 commit d972876

4 files changed

Lines changed: 302 additions & 32 deletions

File tree

‎src/oauth/index.ts‎

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { loginXai, refreshXaiToken, XAI_LOCAL_CLI_DETACH_WARNING, XaiTokenReques
88
import { ANTHROPIC_OAUTH_BETA, AnthropicTokenError, loginAnthropic, refreshAnthropicToken } from "./anthropic";
99
import { loginKimi, refreshKimiToken } from "./kimi";
1010
import { KiroTokenRefreshError, loginKiro, refreshKiroToken, settleKiroLoginTransaction } from "./kiro";
11+
import { requireKiroRegion } from "./kiro-credentials";
1112
import { loginChatGPT, refreshChatGPTToken } from "./chatgpt";
1213
import { loginAntigravity, refreshAntigravityToken } from "./google-antigravity";
1314
import { loginCursor, refreshCursorToken } from "./cursor";
@@ -199,21 +200,40 @@ export class OAuthLoginRequiredError extends Error {
199200
}
200201
}
201202

203+
function kiroEnvironmentRoutingMetadata(): Pick<KiroOAuthMetadata, "profileArn" | "apiRegion" | "ssoRegion"> | undefined {
204+
const profileArn = process.env.KIRO_PROFILE_ARN?.trim() || undefined;
205+
const apiRegion = process.env.KIRO_API_REGION !== undefined
206+
? requireKiroRegion(process.env.KIRO_API_REGION)
207+
: undefined;
208+
const ssoRegion = process.env.KIRO_REGION !== undefined
209+
? requireKiroRegion(process.env.KIRO_REGION)
210+
: undefined;
211+
if (!profileArn && !apiRegion && !ssoRegion) return undefined;
212+
return {
213+
...(profileArn ? { profileArn } : {}),
214+
...(apiRegion ? { apiRegion } : {}),
215+
...(ssoRegion ? { ssoRegion } : {}),
216+
};
217+
}
218+
202219
function accessSnapshot(provider: string, accountId: string, cred: OAuthCredentials): OAuthAccessSnapshot {
220+
const storedKiroRouting = {
221+
...(cred.kiro?.profileArn ? { profileArn: cred.kiro.profileArn } : {}),
222+
...(cred.kiro?.apiRegion ? { apiRegion: cred.kiro.apiRegion } : {}),
223+
...(cred.kiro?.ssoRegion ? { ssoRegion: cred.kiro.ssoRegion } : {}),
224+
};
203225
return {
204226
provider,
205227
accountId,
206228
generation: credentialGeneration(cred),
207229
accessToken: cred.access,
208-
// Presence is the account-scope marker: an empty object means this selected account has no
209-
// stored routing metadata and must not borrow metadata from the local Kiro CLI/environment.
230+
// Stored account metadata remains authoritative. Metadata-less legacy/environment credentials
231+
// may use explicit environment routing, but never borrow the currently signed-in local CLI account.
210232
...(provider === "kiro"
211233
? {
212-
kiro: {
213-
...(cred.kiro?.profileArn ? { profileArn: cred.kiro.profileArn } : {}),
214-
...(cred.kiro?.apiRegion ? { apiRegion: cred.kiro.apiRegion } : {}),
215-
...(cred.kiro?.ssoRegion ? { ssoRegion: cred.kiro.ssoRegion } : {}),
216-
},
234+
kiro: Object.keys(storedKiroRouting).length > 0
235+
? storedKiroRouting
236+
: kiroEnvironmentRoutingMetadata() ?? {},
217237
}
218238
: {}),
219239
};
@@ -569,6 +589,8 @@ export function upsertOAuthProvider(config: OcxConfig, provider: string): void {
569589
interface RunLoginDeps {
570590
saveCredential?: typeof saveCredential;
571591
saveAccountCredential?: typeof saveAccountCredential;
592+
loadConfig?: typeof loadConfig;
593+
saveConfig?: typeof saveConfig;
572594
settleKiroLoginTransaction?: typeof settleKiroLoginTransaction;
573595
}
574596

@@ -590,12 +612,15 @@ export async function runLogin(
590612
if (opts?.reauthAccountId) {
591613
const existing = getAccountCredential(provider, opts.reauthAccountId);
592614
if (!existing) throw new Error(`Unknown account for reauth: ${opts.reauthAccountId}`);
593-
const expected = existing.accountId ?? existing.email;
594-
const got = cred.accountId ?? cred.email;
595-
if (!expected) {
615+
if (!existing.accountId && !existing.email) {
596616
throw new Error("Could not verify signed-in account identity for reauth.");
597617
}
598-
if (!got || expected !== got) {
618+
const identityMatches = existing.accountId && cred.accountId
619+
? existing.accountId === cred.accountId
620+
: existing.email && cred.email
621+
? existing.email.toLowerCase() === cred.email.toLowerCase()
622+
: false;
623+
if (!identityMatches) {
599624
throw new Error("Signed-in account does not match the selected account. Sign in with the same account.");
600625
}
601626
await (deps.saveAccountCredential ?? saveAccountCredential)(provider, opts.reauthAccountId, cred);
@@ -604,22 +629,23 @@ export async function runLogin(
604629
preserveIdentityless: provider === "kiro" && opts?.forceLogin === true,
605630
});
606631
}
632+
if (provider !== "chatgpt") {
633+
const config = (deps.loadConfig ?? loadConfig)();
634+
upsertOAuthProvider(config, provider);
635+
(deps.saveConfig ?? saveConfig)(config);
636+
}
607637
} catch (error) {
608638
try {
609639
settleKiroTransaction(rawCred, false);
610640
} catch (restoreError) {
611641
throw new AggregateError(
612642
[error, restoreError],
613-
"Kiro credential persistence failed and the previous Kiro CLI session could not be restored.",
643+
"Kiro login persistence failed and the previous Kiro CLI session could not be restored.",
614644
);
615645
}
616646
throw error;
617647
}
618648
settleKiroTransaction(rawCred, true);
619-
if (provider === "chatgpt") return cred;
620-
const config = loadConfig();
621-
upsertOAuthProvider(config, provider);
622-
saveConfig(config);
623649
return cred;
624650
}
625651

‎src/oauth/kiro-credentials.ts‎

Lines changed: 48 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1+
import { randomUUID } from "node:crypto";
12
import { chmodSync, closeSync, existsSync, fsyncSync, linkSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
23
import { homedir } from "node:os";
34
import { isAbsolute, join } from "node:path";
45
import { Database } from "bun:sqlite";
56

67
const DEFAULT_EXPIRES_MS = 3600_000;
78
const KIRO_CLI_RECOVERY_SUFFIX = ".opencodex-recovery";
8-
const KIRO_CLI_RECOVERY_HEADER = Buffer.from("opencodex-kiro-session-v1\n", "utf8");
9+
const KIRO_CLI_RECOVERY_HEADER_V1 = Buffer.from("opencodex-kiro-session-v1\n", "utf8");
10+
const KIRO_CLI_RECOVERY_HEADER = Buffer.from("opencodex-kiro-session-v2\n", "utf8");
11+
const KIRO_CLI_RECOVERY_PROCESS_INSTANCE = randomUUID();
12+
const KIRO_CLI_RECOVERY_PROCESS_INSTANCE_PATTERN = /^[A-Za-z0-9._-]{1,128}$/;
913
const SQLITE_DATABASE_HEADER = Buffer.from("SQLite format 3\0", "binary");
1014
const KIRO_REGION_PATTERN = /^[a-z]{2}(?:-[a-z]+)+-\d$/;
1115
const CLIENT_ID_HASH_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
@@ -378,6 +382,7 @@ export function persistKiroCliSessionRecovery(snapshot: KiroCliSessionSnapshot):
378382
writeFileSync(staged, Buffer.concat([
379383
KIRO_CLI_RECOVERY_HEADER,
380384
Buffer.from(`${process.pid}\n`, "utf8"),
385+
Buffer.from(`${KIRO_CLI_RECOVERY_PROCESS_INSTANCE}\n`, "utf8"),
381386
snapshot.database,
382387
]), { flag: "wx", mode: 0o600 });
383388
try { chmodSync(staged, 0o600); } catch { /* platform may ignore chmod */ }
@@ -396,8 +401,43 @@ export function discardKiroCliSessionRecovery(snapshot: KiroCliSessionSnapshot):
396401
rmSync(snapshot.recoveryPath, { force: true });
397402
}
398403

399-
function isKiroRecoveryOwnerAlive(ownerPid: number): boolean {
400-
if (ownerPid === process.pid) return true;
404+
interface ParsedKiroCliSessionRecovery {
405+
ownerPid: number;
406+
ownerProcessInstance?: string;
407+
database: Buffer;
408+
}
409+
410+
function parseKiroCliSessionRecovery(payload: Buffer): ParsedKiroCliSessionRecovery | null {
411+
const isV2 = payload.subarray(0, KIRO_CLI_RECOVERY_HEADER.length).equals(KIRO_CLI_RECOVERY_HEADER);
412+
const isV1 = payload.subarray(0, KIRO_CLI_RECOVERY_HEADER_V1.length).equals(KIRO_CLI_RECOVERY_HEADER_V1);
413+
if (!isV2 && !isV1) return null;
414+
const headerLength = isV2 ? KIRO_CLI_RECOVERY_HEADER.length : KIRO_CLI_RECOVERY_HEADER_V1.length;
415+
const ownerEnd = payload.indexOf(0x0a, headerLength);
416+
if (ownerEnd <= headerLength) return null;
417+
const ownerPid = Number(payload.subarray(headerLength, ownerEnd).toString("utf8"));
418+
let databaseStart = ownerEnd + 1;
419+
let ownerProcessInstance: string | undefined;
420+
if (isV2) {
421+
const instanceEnd = payload.indexOf(0x0a, databaseStart);
422+
if (instanceEnd <= databaseStart) return null;
423+
ownerProcessInstance = payload.subarray(databaseStart, instanceEnd).toString("utf8");
424+
if (!KIRO_CLI_RECOVERY_PROCESS_INSTANCE_PATTERN.test(ownerProcessInstance)) return null;
425+
databaseStart = instanceEnd + 1;
426+
}
427+
const database = payload.subarray(databaseStart);
428+
if (
429+
!Number.isSafeInteger(ownerPid) || ownerPid <= 0 ||
430+
!database.subarray(0, SQLITE_DATABASE_HEADER.length).equals(SQLITE_DATABASE_HEADER)
431+
) {
432+
return null;
433+
}
434+
return { ownerPid, ...(ownerProcessInstance ? { ownerProcessInstance } : {}), database };
435+
}
436+
437+
function isKiroRecoveryOwnerAlive(ownerPid: number, ownerProcessInstance?: string): boolean {
438+
// A restarted supervisor may reuse the exact same PID (commonly PID 1). Only this process
439+
// instance's nonce proves that a same-PID recovery transaction is still live.
440+
if (ownerPid === process.pid) return ownerProcessInstance === KIRO_CLI_RECOVERY_PROCESS_INSTANCE;
401441
try {
402442
process.kill(ownerPid, 0);
403443
return true;
@@ -450,28 +490,20 @@ export function restoreStaleKiroCliSessionRecovery(): boolean {
450490
const recoveryPath = `${path}${KIRO_CLI_RECOVERY_SUFFIX}`;
451491
if (!existsSync(recoveryPath)) continue;
452492
const payload = readFileSync(recoveryPath);
453-
const ownerEnd = payload.indexOf(0x0a, KIRO_CLI_RECOVERY_HEADER.length);
454-
const ownerPid = ownerEnd > KIRO_CLI_RECOVERY_HEADER.length
455-
? Number(payload.subarray(KIRO_CLI_RECOVERY_HEADER.length, ownerEnd).toString("utf8"))
456-
: Number.NaN;
457-
const database = ownerEnd >= 0 ? payload.subarray(ownerEnd + 1) : Buffer.alloc(0);
458-
if (
459-
!payload.subarray(0, KIRO_CLI_RECOVERY_HEADER.length).equals(KIRO_CLI_RECOVERY_HEADER) ||
460-
!Number.isSafeInteger(ownerPid) || ownerPid <= 0 ||
461-
!database.subarray(0, SQLITE_DATABASE_HEADER.length).equals(SQLITE_DATABASE_HEADER)
462-
) {
493+
const recovery = parseKiroCliSessionRecovery(payload);
494+
if (!recovery) {
463495
throw new Error(
464496
`Kiro CLI session recovery data is invalid: ${recoveryPath}. Remove this file to continue.`,
465497
);
466498
}
467-
if (isKiroRecoveryOwnerAlive(ownerPid)) {
499+
if (isKiroRecoveryOwnerAlive(recovery.ownerPid, recovery.ownerProcessInstance)) {
468500
throw new Error(
469-
`Another Kiro CLI login transaction is still in progress (pid ${ownerPid}, ${recoveryPath}).`,
501+
`Another Kiro CLI login transaction is still in progress (pid ${recovery.ownerPid}, ${recoveryPath}).`,
470502
);
471503
}
472504
const snapshot: KiroCliSessionSnapshot = {
473505
path,
474-
database,
506+
database: recovery.database,
475507
recoveryPath,
476508
};
477509
restoreKiroCliSession(snapshot);

‎tests/kiro-adapter.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ describe("kiro adapter — buildRequest", () => {
111111
"arn:aws:codewhisperer:eu-west-1:123456789012:profile/local-other-account",
112112
"eu-west-1",
113113
);
114+
delete process.env.KIRO_REGION;
114115
await saveCredential("kiro", {
115116
access: "stored-access",
116117
refresh: "stored-refresh",

0 commit comments

Comments
 (0)