Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(mcp): harden auth, timeouts, and project update payloads

Tin64b912f8cf6d
diff --git a/packages/mcp/src/auth/auth-service.ts b/packages/mcp/src/auth/auth-service.ts
index 28c7d9986..fffd1b99d 100644
--- a/packages/mcp/src/auth/auth-service.ts
+++ b/packages/mcp/src/auth/auth-service.ts
@@ -17,6 +17,7 @@ type TokenValidationResult = "valid" | "invalid" | "unknown";
export class AuthService {
readonly baseUrl: string;
readonly clientId: string;
+ private activeGetAccessTokenPromise?: Promise<string>;
constructor(options: AuthServiceOptions) {
this.baseUrl = options.baseUrl;
@@ -57,51 +58,63 @@ export class AuthService {
* Returns a valid access token, running the device authorization flow if needed.
*/
async getAccessToken(): Promise<string> {
- const cached = await loadCredentials();
- if (
- cached &&
- cached.baseUrl === this.baseUrl &&
- cached.clientId === this.clientId &&
- cached.accessToken
- ) {
- const validation = await this.validateAccessToken(cached.accessToken);
- // Fail-open for "unknown": validateAccessToken returns "unknown" on transient HTTP/network
- // errors or ambiguous responses. Treating "unknown" like "valid" avoids clearToken() and a full
- // device re-auth so flaky connectivity does not wipe cached.accessToken; only "invalid" forces
- // a fresh login. Tests should cover both unknown and invalid paths.
- if (validation === "valid" || validation === "unknown") {
- return cached.accessToken;
- }
- await this.clearToken();
+ if (this.activeGetAccessTokenPromise) {
+ return await this.activeGetAccessTokenPromise;
}
- const code = await requestDeviceCode(this.baseUrl, this.clientId);
- const verifyUrl = code.verification_uri_complete || code.verification_uri;
- this.log(
- `Open ${verifyUrl} and approve this device. User code: ${code.user_code}`,
- );
+ this.activeGetAccessTokenPromise = (async () => {
+ const cached = await loadCredentials();
+ if (
+ cached &&
+ cached.baseUrl === this.baseUrl &&
+ cached.clientId === this.clientId &&
+ cached.accessToken
+ ) {
+ const validation = await this.validateAccessToken(cached.accessToken);
+ // Fail-open for "unknown": validateAccessToken returns "unknown" on transient HTTP/network
+ // errors or ambiguous responses. Treating "unknown" like "valid" avoids clearToken() and a full
+ // device re-auth so flaky connectivity does not wipe cached.accessToken; only "invalid" forces
+ // a fresh login. Tests should cover both unknown and invalid paths.
+ if (validation === "valid" || validation === "unknown") {
+ return cached.accessToken;
+ }
+ await this.clearToken();
+ }
- try {
- await open(verifyUrl);
- } catch {
- this.log("Could not open a browser automatically; use the URL above.");
- }
+ const code = await requestDeviceCode(this.baseUrl, this.clientId);
+ const verifyUrl = code.verification_uri_complete || code.verification_uri;
+ this.log(
+ `Open ${verifyUrl} and approve this device. User code: ${code.user_code}`,
+ );
- const accessToken = await pollDeviceAccessToken(
- this.baseUrl,
- this.clientId,
- code.device_code,
- code.interval,
- { log: (m) => this.log(m) },
- );
+ try {
+ await open(verifyUrl);
+ } catch {
+ this.log("Could not open a browser automatically; use the URL above.");
+ }
+
+ const accessToken = await pollDeviceAccessToken(
+ this.baseUrl,
+ this.clientId,
+ code.device_code,
+ code.interval,
+ { log: (m) => this.log(m) },
+ );
+
+ const toStore: StoredCredentials = {
+ version: 1,
+ baseUrl: this.baseUrl,
+ clientId: this.clientId,
+ accessToken,
+ };
+ await saveCredentials(toStore);
+ return accessToken;
+ })();
- const toStore: StoredCredentials = {
- version: 1,
- baseUrl: this.baseUrl,
- clientId: this.clientId,
- accessToken,
- };
- await saveCredentials(toStore);
- return accessToken;
+ try {
+ return await this.activeGetAccessTokenPromise;
+ } finally {
+ this.activeGetAccessTokenPromise = undefined;
+ }
}
}
diff --git a/packages/mcp/src/auth/device-flow.ts b/packages/mcp/src/auth/device-flow.ts
index 97a0fb544..f69d9b057 100644
--- a/packages/mcp/src/auth/device-flow.ts
+++ b/packages/mcp/src/auth/device-flow.ts
@@ -12,19 +12,49 @@ export type DeviceTokenErrorBody = {
error_description?: string;
};
+const REQUEST_TIMEOUT_MS = 10_000;
+
function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
+function isAbortError(err: unknown): boolean {
+ return err instanceof DOMException
+ ? err.name === "AbortError"
+ : err instanceof Error && err.name === "AbortError";
+}
+
+async function fetchWithTimeout(
+ input: string,
+ init: RequestInit,
+ timeoutMs = REQUEST_TIMEOUT_MS,
+): Promise<Response> {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
+ try {
+ return await fetch(input, { ...init, signal: controller.signal });
+ } finally {
+ clearTimeout(timeout);
+ }
+}
+
export async function requestDeviceCode(
baseUrl: string,
clientId: string,
): Promise<DeviceCodeResponse> {
- const res = await fetch(`${baseUrl}/api/auth/device/code`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ client_id: clientId }),
- });
+ let res: Response;
+ try {
+ res = await fetchWithTimeout(`${baseUrl}/api/auth/device/code`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ client_id: clientId }),
+ });
+ } catch (err) {
+ if (isAbortError(err)) {
+ throw new Error("device/code request timed out after 10s.");
+ }
+ throw err;
+ }
const body = (await res.json().catch(() => ({}))) as
| DeviceCodeResponse
| DeviceTokenErrorBody;
@@ -92,15 +122,24 @@ export async function pollDeviceAccessToken(
await sleep(intervalMs);
}
- const res = await fetch(`${baseUrl}/api/auth/device/token`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
- device_code: deviceCode,
- client_id: clientId,
- }),
- });
+ let res: Response;
+ try {
+ res = await fetchWithTimeout(`${baseUrl}/api/auth/device/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
+ device_code: deviceCode,
+ client_id: clientId,
+ }),
+ });
+ } catch (err) {
+ if (isAbortError(err)) {
+ log("Device token poll request timed out; retrying.");
+ continue;
+ }
+ throw err;
+ }
if (Date.now() - started > maxWait) {
throw new Error("Device authorization timed out waiting for approval.");
diff --git a/packages/mcp/src/install/index.ts b/packages/mcp/src/install/index.ts
index af42a6888..7a539d5ec 100644
--- a/packages/mcp/src/install/index.ts
+++ b/packages/mcp/src/install/index.ts
@@ -1,4 +1,4 @@
-import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { stdin as input, stdout as output } from "node:process";
import { type McpServerEntry, mergeMcpServerEntry } from "./merge-config.js";
@@ -303,6 +303,7 @@ export async function runInstall(argv: string[]): Promise<void> {
for (const w of mergedWrites) {
await mkdir(dirname(w.configPath), { recursive: true });
await writeFile(w.configPath, w.merged, { encoding: "utf8", mode: 0o600 });
+ await chmod(w.configPath, 0o600);
writtenPaths.push(w.configPath);
}
diff --git a/packages/mcp/src/install/wizard.ts b/packages/mcp/src/install/wizard.ts
index 0c16328f5..a7c89c932 100644
--- a/packages/mcp/src/install/wizard.ts
+++ b/packages/mcp/src/install/wizard.ts
@@ -5,7 +5,7 @@ import {
validateCustomConfigPathInput,
} from "./targets.js";
-function onCancel(): void {
+function onCancel(): never {
console.log("\nCancelled.");
process.exit(0);
}
diff --git a/packages/mcp/src/kaneo/client.ts b/packages/mcp/src/kaneo/client.ts
index 75c38e9aa..e72c62e76 100644
--- a/packages/mcp/src/kaneo/client.ts
+++ b/packages/mcp/src/kaneo/client.ts
@@ -30,7 +30,11 @@ export class KaneoClient {
}
const url = `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`;
- const res = await fetch(url, { ...init, headers });
+ const timeoutSignal = AbortSignal.timeout(10_000);
+ const signal = init?.signal
+ ? AbortSignal.any([init.signal, timeoutSignal])
+ : timeoutSignal;
+ const res = await fetch(url, { ...init, headers, signal });
if (res.status === 401 && !didRetry) {
await this.auth.clearToken();
diff --git a/packages/mcp/src/tools/register.ts b/packages/mcp/src/tools/register.ts
index 3c1f0edbd..792860a1f 100644
--- a/packages/mcp/src/tools/register.ts
+++ b/packages/mcp/src/tools/register.ts
@@ -155,7 +155,7 @@ export function registerTools(
? patch.icon
: existing.icon != null
? String(existing.icon)
- : "";
+ : undefined;
const slug =
patch.slug ??
(typeof existing.slug === "string" ? existing.slug : "");
@@ -167,21 +167,28 @@ export function registerTools(
? patch.description
: typeof existing.description === "string"
? existing.description
- : "";
+ : undefined;
const isPublic =
patch.isPublic !== undefined
? patch.isPublic
- : Boolean(existing.isPublic);
+ : existing.isPublic != null
+ ? Boolean(existing.isPublic)
+ : undefined;
+
+ const body: Record<string, unknown> = { name, slug };
+ if (icon !== undefined) {
+ body.icon = icon;
+ }
+ if (description !== undefined) {
+ body.description = description;
+ }
+ if (isPublic !== undefined) {
+ body.isPublic = isPublic;
+ }
return client.json(`/api/project/${encodeURIComponent(id)}`, {
method: "PUT",
- body: JSON.stringify({
- name,
- icon,
- slug,
- description,
- isPublic,
- }),
+ body: JSON.stringify(body),
});
});
},