⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(mcp): harden install/auth tools and align device auth docs
Tind7b4cda244e8
diff --git a/ENVIRONMENT_SETUP.md b/ENVIRONMENT_SETUP.mdindex 460cbfe3c..8209a6e47 100644--- a/ENVIRONMENT_SETUP.md+++ b/ENVIRONMENT_SETUP.md@@ -26,13 +26,13 @@ For development, you'll need at minimum:- `KANEO_CLIENT_URL` - The URL of the web application (e.g., `http://localhost:5173`)- `KANEO_API_URL` - The URL of the API (e.g., `http://localhost:1337`)- `AUTH_SECRET` - Secret key for JWT token generation (**must be at least 32 characters long**; use a long, random value in production)-- `DEVICE_AUTH_CLIENT_IDS` - Optional comma-separated list of allowed device-flow client IDs (for example `kaneo-cli,my-app`)+- `DEVICE_AUTH_CLIENT_IDS` - **Optional.** Comma-separated list of allowed device-flow OAuth client IDs. When unset, Kaneo implicitly allows `kaneo-cli` and `kaneo-mcp` by default (no extra configuration for the CLI or MCP). Override only when you need additional trusted clients, for example `kaneo-cli,kaneo-mcp,my-desktop-app`.- `DATABASE_URL` - PostgreSQL connection string- `POSTGRES_DB` - PostgreSQL database name- `POSTGRES_USER` - PostgreSQL username- `POSTGRES_PASSWORD` - PostgreSQL password-If you are testing a CLI or external app against your local Kaneo instance, set `DEVICE_AUTH_CLIENT_IDS` to include the client ID your app sends to `/api/auth/device/code`.+If your app uses a device client ID that is not included in the defaults, set `DEVICE_AUTH_CLIENT_IDS` to the full comma-separated list of allowed IDs (including any defaults you still need), so it includes the client ID your app sends to `/api/auth/device/code`.### Development-Specific Variablesdiff --git a/apps/docs/core/installation/environment-variables.mdx b/apps/docs/core/installation/environment-variables.mdxindex c3065741e..3f84367cd 100644--- a/apps/docs/core/installation/environment-variables.mdx+++ b/apps/docs/core/installation/environment-variables.mdx@@ -50,7 +50,7 @@ This section will cover all the variables related to the authentication.Name | Description |--- | --- || `AUTH_SECRET` | The secret key for the JWT token. **Must be at least 32 characters long**, use a long, random value in production. Example: use `openssl rand -base64 32` to generate a secure key in Linux/macOS.-| `DEVICE_AUTH_CLIENT_IDS` | Comma-separated list of allowed device authorization client IDs. When unset, Kaneo allows `kaneo-cli` and `kaneo-mcp` by default. Use this to permit trusted external app identifiers such as `kaneo-cli,kaneo-mcp,my-desktop-app`. |+| `DEVICE_AUTH_CLIENT_IDS` | **Optional.** Comma-separated list of allowed device authorization client IDs. When unset, Kaneo implicitly allows `kaneo-cli` and `kaneo-mcp` by default, so no extra configuration is required for the CLI or MCP. Override only when you need additional trusted clients, for example `kaneo-cli,kaneo-mcp,my-desktop-app`. |## Optional variables@@ -139,4 +139,4 @@ Name | Description |- If you enable Discord SSO, you need to set up the Discord application which is used to authenticate users in the [Discord Developer Portal](https://discord.com/developers/applications). See the [Discord SSO guide](/core/social-providers/discord).- If you enable Custom OAuth/OIDC, you need to configure your identity provider with the appropriate redirect URI. See the [Custom OAuth/OIDC guide](/core/social-providers/custom-oauth).- If you have enabled SMTP, your sign in will be done via email using a magic link.-- If you want to allow CLI or external-app sign-in through device authorization, set `DEVICE_AUTH_CLIENT_IDS` to the trusted client IDs for your deployment.+- If you need device authorization for clients beyond the defaults (`kaneo-cli`, `kaneo-mcp` when `DEVICE_AUTH_CLIENT_IDS` is unset), set `DEVICE_AUTH_CLIENT_IDS` to the full comma-separated list of trusted client IDs for your deployment.diff --git a/apps/mcp/package.json b/apps/mcp/package.jsonindex e66ec6005..159a4bb69 100644--- a/apps/mcp/package.json+++ b/apps/mcp/package.json@@ -28,7 +28,7 @@],"scripts": {"build": "tsc -p tsconfig.json",- "prepublishOnly": "npm run build",+ "prepublishOnly": "pnpm run build","dev": "tsx watch src/index.ts","lint": "biome check --write .","start": "node dist/index.js",diff --git a/apps/mcp/src/auth/auth-service.ts b/apps/mcp/src/auth/auth-service.tsindex a2fcefd61..28c7d9986 100644--- a/apps/mcp/src/auth/auth-service.ts+++ b/apps/mcp/src/auth/auth-service.ts@@ -65,6 +65,10 @@ export class AuthService {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;}diff --git a/apps/mcp/src/auth/device-flow.ts b/apps/mcp/src/auth/device-flow.tsindex 155500e8b..81f1769ca 100644--- a/apps/mcp/src/auth/device-flow.ts+++ b/apps/mcp/src/auth/device-flow.ts@@ -70,6 +70,10 @@ export async function pollDeviceAccessToken(}),});+ if (Date.now() - started > maxWait) {+ throw new Error("Device authorization timed out waiting for approval.");+ }+const body = (await res.json().catch(() => ({}))) as {access_token?: string;error?: string;diff --git a/apps/mcp/src/install/index.ts b/apps/mcp/src/install/index.tsindex 896df848a..f6914e6f0 100644--- a/apps/mcp/src/install/index.ts+++ b/apps/mcp/src/install/index.ts@@ -10,6 +10,14 @@ import {promptTargetSelect,} from "./wizard.js";+/** True if `v` looks like a CLI flag (`--long` or single-letter `-y`), not a value like `-my-server`. */+function isFlagLikeToken(v: string): boolean {+ if (v.startsWith("--")) {+ return true;+ }+ return /^-[A-Za-z]$/.test(v);+}+export type ParsedInstallArgs = {target?: string;output?: string;@@ -44,7 +52,7 @@ export function parseInstallArgs(argv: string[]): ParsedInstallArgs {}if (a === "--target") {const v = argv[i + 1];- if (!v || v.startsWith("-")) {+ if (!v || isFlagLikeToken(v)) {throw new Error("--target requires a value");}target = v;@@ -57,7 +65,7 @@ export function parseInstallArgs(argv: string[]): ParsedInstallArgs {}if (a === "--output") {const v = argv[i + 1];- if (!v || v.startsWith("-")) {+ if (!v || isFlagLikeToken(v)) {throw new Error("--output requires a value");}output = v;@@ -70,7 +78,7 @@ export function parseInstallArgs(argv: string[]): ParsedInstallArgs {}if (a === "--name") {const v = argv[i + 1];- if (!v || v.startsWith("-")) {+ if (!v || isFlagLikeToken(v)) {throw new Error("--name requires a value");}name = v;@@ -83,7 +91,7 @@ export function parseInstallArgs(argv: string[]): ParsedInstallArgs {}if (a === "--api-url") {const v = argv[i + 1];- if (!v || v.startsWith("-")) {+ if (!v || isFlagLikeToken(v)) {throw new Error("--api-url requires a value");}apiUrl = v;@@ -96,7 +104,7 @@ export function parseInstallArgs(argv: string[]): ParsedInstallArgs {}if (a === "--project-dir") {const v = argv[i + 1];- if (!v || v.startsWith("-")) {+ if (!v || isFlagLikeToken(v)) {throw new Error("--project-dir requires a value");}projectDir = v;@@ -217,6 +225,8 @@ export async function runInstall(argv: string[]): Promise<void> {};const writtenPaths: string[] = [];+ const pending: Array<{ configPath: string; existingText: string | null }> =+ [];for (const targetId of targetIds) {const configPath = resolveTargetConfigPath(targetId, {@@ -249,20 +259,28 @@ export async function runInstall(argv: string[]): Promise<void> {}}+ pending.push({ configPath, existingText });+ }++ const mergedWrites: Array<{ configPath: string; merged: string }> = [];+ for (const p of pending) {let merged: string;try {- merged = mergeMcpServerEntry(existingText, parsed.name, serverConfig);+ merged = mergeMcpServerEntry(p.existingText, parsed.name, serverConfig);} catch {console.error(- `Cannot update config (invalid JSON or merge error): ${configPath}`,+ `Cannot update config (invalid JSON or merge error): ${p.configPath}`,);process.exitCode = 1;return;}+ mergedWrites.push({ configPath: p.configPath, merged });+ }- await mkdir(dirname(configPath), { recursive: true });- await writeFile(configPath, merged, { encoding: "utf8", mode: 0o600 });- writtenPaths.push(configPath);+ for (const w of mergedWrites) {+ await mkdir(dirname(w.configPath), { recursive: true });+ await writeFile(w.configPath, w.merged, { encoding: "utf8", mode: 0o600 });+ writtenPaths.push(w.configPath);}if (writtenPaths.length === 0) {diff --git a/apps/mcp/src/install/merge-config.ts b/apps/mcp/src/install/merge-config.tsindex 8f5ec2d99..34001f321 100644--- a/apps/mcp/src/install/merge-config.ts+++ b/apps/mcp/src/install/merge-config.ts@@ -15,13 +15,19 @@ export function mergeMcpServerEntry(): string {let root: Record<string, unknown> = {};if (existingJson) {- const parsed: unknown = JSON.parse(existingJson);- if (- typeof parsed === "object" &&- parsed !== null &&- !Array.isArray(parsed)- ) {- root = { ...(parsed as Record<string, unknown>) };+ try {+ const parsed: unknown = JSON.parse(existingJson);+ if (+ typeof parsed === "object" &&+ parsed !== null &&+ !Array.isArray(parsed)+ ) {+ root = { ...(parsed as Record<string, unknown>) };+ }+ } catch {+ console.warn(+ "[kaneo-mcp] Existing MCP config is not valid JSON; overwriting with a fresh object.",+ );}}diff --git a/apps/mcp/src/install/parse-install-args.test.ts b/apps/mcp/src/install/parse-install-args.test.tsindex aa183afaa..c277d525a 100644--- a/apps/mcp/src/install/parse-install-args.test.ts+++ b/apps/mcp/src/install/parse-install-args.test.ts@@ -3,17 +3,17 @@ import { parseInstallArgs } from "./index.js";describe("parseInstallArgs", () => {it("parses flags", () => {- expect(- parseInstallArgs([- "--target",- "cursor-user",- "--name",- "my-kaneo",- "-y",- "--api-url",- "http://example.com",- ]),- ).toEqual({+ // Arrange+ const argv = [+ "--target",+ "cursor-user",+ "--name",+ "my-kaneo",+ "-y",+ "--api-url",+ "http://example.com",+ ];+ const expected = {target: "cursor-user",output: undefined,name: "my-kaneo",@@ -21,10 +21,42 @@ describe("parseInstallArgs", () => {apiUrl: "http://example.com",projectDir: process.cwd(),help: false,- });+ };++ // Act+ const result = parseInstallArgs(argv);++ // Assert+ expect(result).toEqual(expected);});it("throws on unknown option", () => {- expect(() => parseInstallArgs(["--nope"])).toThrow("Unknown option");+ // Arrange+ const argv = ["--nope"];+ // Act+ const act = () => parseInstallArgs(argv);++ // Assert+ expect(act).toThrow("Unknown option");+ });++ it("allows --target values that start with '-' when they are not flags", () => {+ // Arrange+ const argv = ["--target", "-my-server", "-y"];+ const expected = {+ target: "-my-server",+ output: undefined,+ name: "kaneo",+ yes: true,+ apiUrl: undefined,+ projectDir: process.cwd(),+ help: false,+ };++ // Act+ const result = parseInstallArgs(argv);++ // Assert+ expect(result).toEqual(expected);});});diff --git a/apps/mcp/src/install/wizard.ts b/apps/mcp/src/install/wizard.tsindex 03d102259..2ce1c1b5a 100644--- a/apps/mcp/src/install/wizard.ts+++ b/apps/mcp/src/install/wizard.ts@@ -1,3 +1,4 @@+import path from "node:path";import prompts from "prompts";import { INSTALL_TARGETS, type InstallTargetId } from "./targets.js";@@ -41,10 +42,22 @@ export async function promptCustomConfigPath(): Promise<string> {type: "text",name: "path",message: "Absolute path to the JSON config file (create or update):",- validate: (v) =>- typeof v === "string" && v.trim().length > 0- ? true- : "Path is required",+ validate: (v) => {+ if (typeof v !== "string") {+ return "Path is required";+ }+ const trimmed = v.trim();+ if (trimmed.length === 0) {+ return "Path is required";+ }+ if (!path.isAbsolute(trimmed)) {+ return "Path must be absolute";+ }+ if (!trimmed.toLowerCase().endsWith(".json")) {+ return "Path must end with .json";+ }+ return true;+ },},{ onCancel },);diff --git a/apps/mcp/src/kaneo/task-helpers.test.ts b/apps/mcp/src/kaneo/task-helpers.test.tsindex 55bdcc2b2..6df6f71c6 100644--- a/apps/mcp/src/kaneo/task-helpers.test.ts+++ b/apps/mcp/src/kaneo/task-helpers.test.ts@@ -3,18 +3,22 @@ import { buildFullTaskUpdateBody } from "./task-helpers.js";describe("buildFullTaskUpdateBody", () => {it("merges patch onto existing task", () => {- const body = buildFullTaskUpdateBody(- {- title: "T",- description: "D",- status: "open",- priority: "low",- projectId: "p1",- position: 1,- userId: "u1",- },- { status: "done" },- );+ // Arrange+ const original = {+ title: "T",+ description: "D",+ status: "open",+ priority: "low",+ projectId: "p1",+ position: 1,+ userId: "u1",+ };+ const patch = { status: "done" as const };++ // Act+ const body = buildFullTaskUpdateBody(original, patch);++ // Assertexpect(body.status).toBe("done");expect(body.title).toBe("T");expect(body.position).toBe(1);diff --git a/apps/mcp/src/kaneo/task-helpers.ts b/apps/mcp/src/kaneo/task-helpers.tsindex 77811c4b4..0e183fca3 100644--- a/apps/mcp/src/kaneo/task-helpers.ts+++ b/apps/mcp/src/kaneo/task-helpers.ts@@ -75,6 +75,9 @@ export function buildFullTaskUpdateBody(throw new Error("Cannot update task: missing projectId.");}+ // When patch.userId is explicitly null, we set userId to "" so the API clears assignee; the API+ // treats "" as unassigned (userId || null). When patch.userId is undefined, keep existing.userId+ // unchanged (leave assignee as-is).const userId =patch.userId !== undefined? patch.userId === nulldiff --git a/apps/mcp/src/tools/register.test.ts b/apps/mcp/src/tools/register.test.tsindex 847991fea..e81d450c8 100644--- a/apps/mcp/src/tools/register.test.ts+++ b/apps/mcp/src/tools/register.test.ts@@ -105,9 +105,13 @@ describe("registerTools", () => {expect(client.json).toHaveBeenNthCalledWith(1, "/api/task/task-1", {method: "GET",});- expect(client.json).toHaveBeenNthCalledWith(2, "/api/task/task-1", {- method: "PUT",- body: JSON.stringify({+ const putCall = client.json.mock.calls[1];+ expect(putCall?.[0]).toBe("/api/task/task-1");+ const putBody = JSON.parse(+ String((putCall?.[1] as { body?: string })?.body ?? "{}"),+ );+ expect(putBody).toEqual(+ expect.objectContaining({title: "Draft spec",description: "Write docs",status: "done",@@ -115,7 +119,7 @@ describe("registerTools", () => {projectId: "project-1",position: 4,}),- });+ );expect(result?.isError).toBe(false);});diff --git a/apps/mcp/src/tools/register.ts b/apps/mcp/src/tools/register.tsindex 88e579ca8..3c1f0edbd 100644--- a/apps/mcp/src/tools/register.ts+++ b/apps/mcp/src/tools/register.ts@@ -126,29 +126,65 @@ export function registerTools(server.registerTool("update_project",{- description: "Update project metadata.",+ description:+ "Update project metadata (PATCH-style: only provided fields are changed).",inputSchema: z.object({id: nonEmptyString,- name: nonEmptyString,- icon: nonEmptyString,- slug: nonEmptyString,- description: z.string(),- isPublic: z.boolean(),+ name: optionalNonEmptyString,+ icon: z.string().optional(),+ slug: optionalNonEmptyString,+ description: z.string().optional(),+ isPublic: z.boolean().optional(),}),},- async (args) =>- run(() =>- client.json(`/api/project/${encodeURIComponent(args.id)}`, {+ async (args) => {+ const { id, ...patch } = args;+ return run(async () => {+ const existing = (await client.json(+ `/api/project/${encodeURIComponent(id)}`,+ { method: "GET" },+ )) as Record<string, unknown>;+ const name =+ patch.name ??+ (typeof existing.name === "string" ? existing.name : "");+ if (!name) {+ throw new Error("Cannot update project: missing name.");+ }+ const icon =+ patch.icon !== undefined+ ? patch.icon+ : existing.icon != null+ ? String(existing.icon)+ : "";+ const slug =+ patch.slug ??+ (typeof existing.slug === "string" ? existing.slug : "");+ if (!slug) {+ throw new Error("Cannot update project: missing slug.");+ }+ const description =+ patch.description !== undefined+ ? patch.description+ : typeof existing.description === "string"+ ? existing.description+ : "";+ const isPublic =+ patch.isPublic !== undefined+ ? patch.isPublic+ : Boolean(existing.isPublic);++ return client.json(`/api/project/${encodeURIComponent(id)}`, {method: "PUT",body: JSON.stringify({- name: args.name,- icon: args.icon,- slug: args.slug,- description: args.description,- isPublic: args.isPublic,+ name,+ icon,+ slug,+ description,+ isPublic,}),- }),- ),+ });+ });+ },);const listTasksSchema = z.object({diff --git a/apps/mcp/src/utils/mcp-result.ts b/apps/mcp/src/utils/mcp-result.tsindex 63bbba487..3e206b6c6 100644--- a/apps/mcp/src/utils/mcp-result.ts+++ b/apps/mcp/src/utils/mcp-result.ts@@ -1,11 +1,13 @@import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";export function textResult(data: unknown, isError = false): CallToolResult {+ const text =+ typeof data === "string" ? data : (JSON.stringify(data, null, 2) ?? "");return {content: [{type: "text",- text: typeof data === "string" ? data : JSON.stringify(data, null, 2),+ text,},],isError,diff --git a/apps/mcp/src/utils/normalize-base-url.test.ts b/apps/mcp/src/utils/normalize-base-url.test.tsindex d79166120..6f8fd8f86 100644--- a/apps/mcp/src/utils/normalize-base-url.test.ts+++ b/apps/mcp/src/utils/normalize-base-url.test.ts@@ -3,14 +3,24 @@ import { normalizeBaseUrl } from "./normalize-base-url.js";describe("normalizeBaseUrl", () => {it("strips trailing slashes", () => {- expect(normalizeBaseUrl("http://localhost:1337/")).toBe(- "http://localhost:1337",- );+ // Arrange+ const input = "http://localhost:1337/";++ // Act+ const result = normalizeBaseUrl(input);++ // Assert+ expect(result).toBe("http://localhost:1337");});it("removes /api suffix from path", () => {- expect(normalizeBaseUrl("http://localhost:1337/api")).toBe(- "http://localhost:1337",- );+ // Arrange+ const input = "http://localhost:1337/api";++ // Act+ const result = normalizeBaseUrl(input);++ // Assert+ expect(result).toBe("http://localhost:1337");});});diff --git a/apps/web/package.json b/apps/web/package.jsonindex dcd61c15b..a6ed56ecb 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -73,12 +73,13 @@"framer-motion": "^12.34.3","highlight.js": "^11.11.1","hono": "^4.12.4",+ "i18next": "^25.5.3","immer": "^11.1.4","input-otp": "^1.4.2",- "i18next": "^25.5.3","lowlight": "^3.3.0","lucide-react": "^0.577.0","marked": "^17.0.4",+ "nanostores": "^1.1.1","radix-ui": "^1.4.3","react": "^19.2.4","react-day-picker": "9.14.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex afdf011ab..b500beeb3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -456,6 +456,9 @@ importers:marked:specifier: ^17.0.4version: 17.0.4+ nanostores:+ specifier: ^1.1.1+ version: 1.1.1radix-ui:specifier: ^1.4.3version: 1.4.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])