Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

fix(server): persist Kimi device identity (#21)

Leo46816ac832d0
diff --git a/apps/server/src/subscription-auth/providers/kimi.ts b/apps/server/src/subscription-auth/providers/kimi.ts
index 57eb7ee03..96900e333 100644
--- a/apps/server/src/subscription-auth/providers/kimi.ts
+++ b/apps/server/src/subscription-auth/providers/kimi.ts
@@ -6,7 +6,7 @@
* (`mastracode/sdk/src/auth/providers/kimi-coding.ts`), Apache-2.0.
*
* RFC 8628-style device flow against auth.kimi.com. Device metadata headers
- * identify the client; the device id is random per process.
+ * identify the client; one device id follows the account through login and refresh.
*/
import * as NodeCrypto from "node:crypto";
@@ -28,13 +28,21 @@ function asciiHeaderValue(value: string): string {
return sanitized || "unknown";
}
-const KIMI_DEVICE_HEADERS = {
- "X-Msh-Platform": "akeru",
- "X-Msh-Device-Name": asciiHeaderValue(NodeOS.hostname()),
- "X-Msh-Device-Model": "Akeru server",
- "X-Msh-Os-Version": asciiHeaderValue(NodeOS.release()),
- "X-Msh-Device-Id": NodeCrypto.randomUUID().replaceAll("-", ""),
-};
+export function isKimiCodingDeviceId(value: unknown): value is string {
+ return typeof value === "string" && /^[0-9a-f]{32}$/.test(value);
+}
+
+export function getKimiCodingDeviceHeaders(deviceId: string): Record<string, string> {
+ if (!isKimiCodingDeviceId(deviceId)) throw new Error("Invalid Kimi For Coding device id");
+ return {
+ "X-Msh-Platform": "akeru",
+ "X-Msh-Version": "0.0.34",
+ "X-Msh-Device-Name": asciiHeaderValue(NodeOS.hostname()),
+ "X-Msh-Device-Model": "Akeru server",
+ "X-Msh-Os-Version": asciiHeaderValue(NodeOS.release()),
+ "X-Msh-Device-Id": deviceId,
+ };
+}
function requestSignal(signal?: AbortSignal): AbortSignal {
const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
@@ -60,7 +68,11 @@ async function readJson(response: Response): Promise<Record<string, unknown> | n
}
}
-function credentialsFromTokenResponse(value: unknown, operation: string): OAuthCredentials {
+function credentialsFromTokenResponse(
+ value: unknown,
+ operation: string,
+ deviceId: string,
+): OAuthCredentials {
const data = (value ?? {}) as Record<string, unknown>;
const access = data.access_token;
const refresh = data.refresh_token;
@@ -76,10 +88,11 @@ function credentialsFromTokenResponse(value: unknown, operation: string): OAuthC
) {
throw new Error(`Kimi For Coding token ${operation} response missing fields`);
}
- return { access, refresh, expires: Date.now() + expiresIn * 1000 };
+ return { access, refresh, expires: Date.now() + expiresIn * 1000, deviceId };
}
export interface KimiDeviceLoginPending {
+ deviceId: string;
deviceCode: string;
userCode: string;
url: string;
@@ -95,10 +108,11 @@ export type KimiDevicePollResult =
export async function startKimiDeviceLogin(options?: {
signal?: AbortSignal;
}): Promise<KimiDeviceLoginPending> {
+ const deviceId = NodeCrypto.randomUUID().replaceAll("-", "");
const response = await fetch(`${OAUTH_HOST}/api/oauth/device_authorization`, {
method: "POST",
headers: {
- ...KIMI_DEVICE_HEADERS,
+ ...getKimiCodingDeviceHeaders(deviceId),
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
@@ -131,6 +145,7 @@ export async function startKimiDeviceLogin(options?: {
const interval = data?.interval;
const expiresIn = data?.expires_in;
return {
+ deviceId,
deviceCode,
userCode,
url: verificationUriComplete,
@@ -155,7 +170,7 @@ async function pollKimiTokenOnce(
const response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {
method: "POST",
headers: {
- ...KIMI_DEVICE_HEADERS,
+ ...getKimiCodingDeviceHeaders(pending.deviceId),
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
@@ -169,7 +184,10 @@ async function pollKimiTokenOnce(
const data = await readJson(response);
if (response.ok && typeof data?.access_token === "string") {
try {
- return { status: "complete", result: credentialsFromTokenResponse(data, "poll") };
+ return {
+ status: "complete",
+ result: credentialsFromTokenResponse(data, "poll", pending.deviceId),
+ };
} catch (error) {
return { status: "failed", error: error instanceof Error ? error.message : String(error) };
}
@@ -241,7 +259,11 @@ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
export async function refreshKimiToken(
refreshToken: string,
signal?: AbortSignal,
+ deviceId?: string,
): Promise<OAuthCredentials> {
+ if (!isKimiCodingDeviceId(deviceId)) {
+ throw new Error("Kimi For Coding credentials have no valid device id. Reconnect the account.");
+ }
let lastError: Error | undefined;
for (let attempt = 0; attempt <= REFRESH_MAX_RETRIES; attempt++) {
if (attempt > 0) await sleep(1000 * 2 ** (attempt - 1), signal);
@@ -250,7 +272,7 @@ export async function refreshKimiToken(
response = await fetch(`${OAUTH_HOST}/api/oauth/token`, {
method: "POST",
headers: {
- ...KIMI_DEVICE_HEADERS,
+ ...getKimiCodingDeviceHeaders(deviceId),
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
@@ -267,7 +289,7 @@ export async function refreshKimiToken(
continue;
}
const data = await readJson(response);
- if (response.ok) return credentialsFromTokenResponse(data, "refresh");
+ if (response.ok) return credentialsFromTokenResponse(data, "refresh", deviceId);
const errorSuffix = typeof data?.error === "string" ? ` ${data.error}` : "";
lastError = new Error(`Kimi For Coding token refresh failed: ${response.status}${errorSuffix}`);
diff --git a/apps/server/src/subscription-auth/service.test.ts b/apps/server/src/subscription-auth/service.test.ts
index a6c797af1..f9935d87f 100644
--- a/apps/server/src/subscription-auth/service.test.ts
+++ b/apps/server/src/subscription-auth/service.test.ts
@@ -67,6 +67,40 @@ describe("subscription auth storage", () => {
expect(NodeFS.readFileSync(authPath, "utf-8")).toBe(before);
});
+ it("returns Kimi access only with its persisted device identity", async () => {
+ const { authPath } = fixture();
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ "kimi-for-coding": {
+ type: "oauth",
+ access: "kimi-access",
+ refresh: "kimi-refresh",
+ expires: Date.now() + 60_000,
+ deviceId: "0123456789abcdef0123456789abcdef",
+ },
+ }),
+ );
+ const service = new SubscriptionAuthService(authPath);
+ await expect(service.getKimiForCodingAccess()).resolves.toEqual({
+ accessToken: "kimi-access",
+ deviceId: "0123456789abcdef0123456789abcdef",
+ });
+
+ NodeFS.writeFileSync(
+ authPath,
+ JSON.stringify({
+ "kimi-for-coding": {
+ type: "oauth",
+ access: "old-access",
+ refresh: "old-refresh",
+ expires: Date.now() + 60_000,
+ },
+ }),
+ );
+ await expect(service.getKimiForCodingAccess()).resolves.toBeUndefined();
+ });
+
it("persists pending logins across a server restart", async () => {
const { authPath } = fixture();
const first = new SubscriptionAuthService(authPath);
diff --git a/apps/server/src/subscription-auth/service.ts b/apps/server/src/subscription-auth/service.ts
index 6420af1c1..a4bb27232 100644
--- a/apps/server/src/subscription-auth/service.ts
+++ b/apps/server/src/subscription-auth/service.ts
@@ -37,6 +37,7 @@ import {
type CursorLoginPending,
} from "./providers/cursor.ts";
import {
+ isKimiCodingDeviceId,
pollKimiDeviceLogin,
refreshKimiToken,
startKimiDeviceLogin,
@@ -618,6 +619,15 @@ export class SubscriptionAuthService {
: undefined;
}
+ async getKimiForCodingAccess(): Promise<
+ { readonly accessToken: string; readonly deviceId: string } | undefined
+ > {
+ this.reload();
+ const accessToken = await this.getAccessToken("kimi-for-coding");
+ const deviceId = this.data["kimi-for-coding"]?.deviceId;
+ return accessToken && isKimiCodingDeviceId(deviceId) ? { accessToken, deviceId } : undefined;
+ }
+
private async refreshCredential(
provider: SubscriptionProviderId,
credential: OAuthCredential,
@@ -652,7 +662,11 @@ export class SubscriptionAuthService {
case "xai":
return refreshXAIToken(credential.refresh);
case "kimi-for-coding":
- return refreshKimiToken(credential.refresh);
+ return refreshKimiToken(
+ credential.refresh,
+ undefined,
+ typeof credential.deviceId === "string" ? credential.deviceId : undefined,
+ );
}
}
}