⚡ 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
fix(mcp): harden auth and tool validation
Tincf0a832f63e7
diff --git a/apps/mcp/src/auth/auth-service.test.ts b/apps/mcp/src/auth/auth-service.test.tsnew file mode 100644index 000000000..e0fe10bea--- /dev/null+++ b/apps/mcp/src/auth/auth-service.test.ts@@ -0,0 +1,136 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { AuthService } from "./auth-service.js";++const {+ loadCredentialsMock,+ clearCredentialsMock,+ saveCredentialsMock,+ requestDeviceCodeMock,+ pollDeviceAccessTokenMock,+ openMock,+} = vi.hoisted(() => ({+ loadCredentialsMock: vi.fn(),+ clearCredentialsMock: vi.fn(),+ saveCredentialsMock: vi.fn(),+ requestDeviceCodeMock: vi.fn(),+ pollDeviceAccessTokenMock: vi.fn(),+ openMock: vi.fn(),+}));++vi.mock("./token-store.js", () => ({+ loadCredentials: loadCredentialsMock,+ clearCredentials: clearCredentialsMock,+ saveCredentials: saveCredentialsMock,+}));++vi.mock("./device-flow.js", () => ({+ requestDeviceCode: requestDeviceCodeMock,+ pollDeviceAccessToken: pollDeviceAccessTokenMock,+}));++vi.mock("open", () => ({+ default: openMock,+}));++describe("AuthService", () => {+ const originalFetch = globalThis.fetch;++ beforeEach(() => {+ loadCredentialsMock.mockReset();+ clearCredentialsMock.mockReset();+ saveCredentialsMock.mockReset();+ requestDeviceCodeMock.mockReset();+ pollDeviceAccessTokenMock.mockReset();+ openMock.mockReset();+ });++ afterEach(() => {+ globalThis.fetch = originalFetch;+ vi.restoreAllMocks();+ });++ it("reuses the cached token when validation succeeds", async () => {+ loadCredentialsMock.mockResolvedValue({+ version: 1,+ baseUrl: "https://api.example.com",+ clientId: "kaneo-mcp",+ accessToken: "cached-token",+ });+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ user: { id: "user-1" } }), {+ status: 200,+ }),+ ) as typeof fetch;++ const service = new AuthService({+ baseUrl: "https://api.example.com",+ clientId: "kaneo-mcp",+ });++ await expect(service.getAccessToken()).resolves.toBe("cached-token");+ expect(clearCredentialsMock).not.toHaveBeenCalled();+ expect(requestDeviceCodeMock).not.toHaveBeenCalled();+ });++ it("keeps the cached token when validation cannot confirm validity", async () => {+ loadCredentialsMock.mockResolvedValue({+ version: 1,+ baseUrl: "https://api.example.com",+ clientId: "kaneo-mcp",+ accessToken: "cached-token",+ });+ globalThis.fetch = vi+ .fn()+ .mockRejectedValue(+ new Error("temporary network failure"),+ ) as typeof fetch;++ const service = new AuthService({+ baseUrl: "https://api.example.com",+ clientId: "kaneo-mcp",+ });++ await expect(service.getAccessToken()).resolves.toBe("cached-token");+ expect(clearCredentialsMock).not.toHaveBeenCalled();+ expect(requestDeviceCodeMock).not.toHaveBeenCalled();+ });++ it("clears the cached token and starts device auth after a 401", async () => {+ loadCredentialsMock.mockResolvedValue({+ version: 1,+ baseUrl: "https://api.example.com",+ clientId: "kaneo-mcp",+ accessToken: "expired-token",+ });+ globalThis.fetch = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ message: "Unauthorized" }), {+ status: 401,+ }),+ ) as typeof fetch;+ requestDeviceCodeMock.mockResolvedValue({+ device_code: "device-code",+ user_code: "ABCD-EFGH",+ verification_uri: "https://verify.example.com",+ interval: 5,+ });+ pollDeviceAccessTokenMock.mockResolvedValue("fresh-token");++ const service = new AuthService({+ baseUrl: "https://api.example.com",+ clientId: "kaneo-mcp",+ });++ await expect(service.getAccessToken()).resolves.toBe("fresh-token");+ expect(clearCredentialsMock).toHaveBeenCalledTimes(1);+ expect(requestDeviceCodeMock).toHaveBeenCalledWith(+ "https://api.example.com",+ "kaneo-mcp",+ );+ expect(saveCredentialsMock).toHaveBeenCalledWith({+ version: 1,+ baseUrl: "https://api.example.com",+ clientId: "kaneo-mcp",+ accessToken: "fresh-token",+ });+ });+});diff --git a/apps/mcp/src/auth/auth-service.ts b/apps/mcp/src/auth/auth-service.tsindex 8533d7165..a2fcefd61 100644--- a/apps/mcp/src/auth/auth-service.ts+++ b/apps/mcp/src/auth/auth-service.ts@@ -12,6 +12,8 @@ export type AuthServiceOptions = {clientId: string;};+type TokenValidationResult = "valid" | "invalid" | "unknown";+export class AuthService {readonly baseUrl: string;readonly clientId: string;@@ -25,20 +27,26 @@ export class AuthService {await clearCredentials();}- private async validateAccessToken(token: string): Promise<boolean> {- const res = await fetch(`${this.baseUrl}/api/auth/get-session`, {- headers: { Authorization: `Bearer ${token}` },- });- if (res.status === 401) {- return false;- }- if (!res.ok) {- return false;+ private async validateAccessToken(+ token: string,+ ): Promise<TokenValidationResult> {+ try {+ const res = await fetch(`${this.baseUrl}/api/auth/get-session`, {+ headers: { Authorization: `Bearer ${token}` },+ });+ if (res.status === 401) {+ return "invalid";+ }+ if (!res.ok) {+ return "unknown";+ }+ const data = (await res.json().catch(() => null)) as {+ user?: { id?: string };+ } | null;+ return data?.user?.id ? "valid" : "unknown";+ } catch {+ return "unknown";}- const data = (await res.json().catch(() => null)) as {- user?: { id?: string };- } | null;- return Boolean(data?.user?.id);}private log(msg: string): void {@@ -56,8 +64,8 @@ export class AuthService {cached.clientId === this.clientId &&cached.accessToken) {- const ok = await this.validateAccessToken(cached.accessToken);- if (ok) {+ const validation = await this.validateAccessToken(cached.accessToken);+ if (validation === "valid" || validation === "unknown") {return cached.accessToken;}await this.clearToken();diff --git a/apps/mcp/src/tools/register.test.ts b/apps/mcp/src/tools/register.test.tsindex 0624d815b..847991fea 100644--- a/apps/mcp/src/tools/register.test.ts+++ b/apps/mcp/src/tools/register.test.ts@@ -3,6 +3,7 @@ import { registerTools } from "./register.js";type RegisteredTool = {name: string;+ config: { inputSchema?: { parse: (args: unknown) => unknown } };handler: (args: Record<string, unknown>) => Promise<{content: Array<{ type: string; text: string }>;isError?: boolean;@@ -10,17 +11,17 @@ type RegisteredTool = {};function createServerMock() {- const tools = new Map<string, RegisteredTool["handler"]>();+ const tools = new Map<string, RegisteredTool>();return {server: {registerTool: vi.fn((name: string,- _config: unknown,+ config: RegisteredTool["config"],handler: RegisteredTool["handler"],) => {- tools.set(name, handler);+ tools.set(name, { name, config, handler });},),},@@ -56,7 +57,7 @@ describe("registerTools", () => {registerTools(server as never, { client: client as never });- const result = await tools.get("list_tasks")?.({+ const result = await tools.get("list_tasks")?.handler({projectId: "project 1",status: "open",page: 2,@@ -96,7 +97,7 @@ describe("registerTools", () => {registerTools(server as never, { client: client as never });- const result = await tools.get("update_task")?.({+ const result = await tools.get("update_task")?.handler({taskId: "task-1",status: "done",});@@ -126,7 +127,7 @@ describe("registerTools", () => {registerTools(server as never, { client: client as never });- const result = await tools.get("whoami")?.({});+ const result = await tools.get("whoami")?.handler({});expect(result).toEqual({content: [@@ -138,4 +139,37 @@ describe("registerTools", () => {isError: true,});});++ it("validates label colors as hex values", () => {+ const { server, tools } = createServerMock();+ const client = { json: vi.fn() };++ registerTools(server as never, { client: client as never });++ const schema = tools.get("create_label")?.config.inputSchema;+ expect(schema).toBeDefined();+ expect(() =>+ schema?.parse({+ name: "Bug",+ color: "red",+ workspaceId: "workspace-1",+ }),+ ).toThrow(/hex color/i);+ });++ it("validates task date filters as ISO datetimes with timezone", () => {+ const { server, tools } = createServerMock();+ const client = { json: vi.fn() };++ registerTools(server as never, { client: client as never });++ const schema = tools.get("list_tasks")?.config.inputSchema;+ expect(schema).toBeDefined();+ expect(() =>+ schema?.parse({+ projectId: "project-1",+ dueBefore: "2026-04-04",+ }),+ ).toThrow();+ });});diff --git a/apps/mcp/src/tools/register.ts b/apps/mcp/src/tools/register.tsindex 71995a42a..88e579ca8 100644--- a/apps/mcp/src/tools/register.ts+++ b/apps/mcp/src/tools/register.ts@@ -13,6 +13,21 @@ const prioritySchema = z.enum(["urgent",]);+const nonEmptyString = z.string().trim().min(1);+const optionalNonEmptyString = nonEmptyString.optional();+const nullableOptionalNonEmptyString = nonEmptyString.nullable().optional();+const isoDateTimeSchema = z.string().datetime({ offset: true });+const optionalIsoDateTimeSchema = isoDateTimeSchema.optional();+const nullableOptionalIsoDateTimeSchema = isoDateTimeSchema+ .nullable()+ .optional();+const hexColorSchema = z+ .string()+ .regex(+ /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,+ "Expected a hex color like #FF6600",+ );+function run(fn: () => Promise<unknown>): Promise<CallToolResult> {return fn().then((data) => textResult(data))@@ -54,7 +69,7 @@ export function registerTools({description: "List projects in a workspace.",inputSchema: z.object({- workspaceId: z.string().describe("Workspace ID"),+ workspaceId: nonEmptyString.describe("Workspace ID"),includeArchived: z.boolean().optional()@@ -77,7 +92,7 @@ export function registerTools("get_project",{description: "Get a single project by ID.",- inputSchema: z.object({ id: z.string() }),+ inputSchema: z.object({ id: nonEmptyString }),},async (args) =>run(() => client.json(`/api/project/${encodeURIComponent(args.id)}`)),@@ -88,10 +103,10 @@ export function registerTools({description: "Create a project in a workspace.",inputSchema: z.object({- name: z.string(),- workspaceId: z.string(),- icon: z.string(),- slug: z.string(),+ name: nonEmptyString,+ workspaceId: nonEmptyString,+ icon: nonEmptyString,+ slug: nonEmptyString,}),},async (args) =>@@ -113,10 +128,10 @@ export function registerTools({description: "Update project metadata.",inputSchema: z.object({- id: z.string(),- name: z.string(),- icon: z.string(),- slug: z.string(),+ id: nonEmptyString,+ name: nonEmptyString,+ icon: nonEmptyString,+ slug: nonEmptyString,description: z.string(),isPublic: z.boolean(),}),@@ -137,18 +152,18 @@ export function registerTools();const listTasksSchema = z.object({- projectId: z.string(),- status: z.string().optional(),- priority: z.string().optional(),- assigneeId: z.string().optional(),+ projectId: nonEmptyString,+ status: optionalNonEmptyString,+ priority: prioritySchema.optional(),+ assigneeId: optionalNonEmptyString,page: z.number().int().positive().optional(),limit: z.number().int().positive().optional(),sortBy: z.enum(["createdAt", "priority", "dueDate", "position", "title", "number"]).optional(),sortOrder: z.enum(["asc", "desc"]).optional(),- dueBefore: z.string().optional(),- dueAfter: z.string().optional(),+ dueBefore: optionalIsoDateTimeSchema,+ dueAfter: optionalIsoDateTimeSchema,});server.registerTool(@@ -176,7 +191,7 @@ export function registerTools("get_task",{description: "Get a task by ID.",- inputSchema: z.object({ taskId: z.string() }),+ inputSchema: z.object({ taskId: nonEmptyString }),},async (args) =>run(() =>@@ -191,14 +206,14 @@ export function registerTools({description: "Create a task in a project.",inputSchema: z.object({- projectId: z.string(),- title: z.string(),+ projectId: nonEmptyString,+ title: nonEmptyString,description: z.string(),priority: prioritySchema,- status: z.string(),- startDate: z.string().optional(),- dueDate: z.string().optional(),- userId: z.string().optional(),+ status: nonEmptyString,+ startDate: optionalIsoDateTimeSchema,+ dueDate: optionalIsoDateTimeSchema,+ userId: optionalNonEmptyString,}),},async (args) => {@@ -227,16 +242,16 @@ export function registerTools();const updateTaskSchema = z.object({- taskId: z.string(),- title: z.string().optional(),+ taskId: nonEmptyString,+ title: optionalNonEmptyString,description: z.string().nullable().optional(),- status: z.string().optional(),+ status: optionalNonEmptyString,priority: prioritySchema.optional(),- projectId: z.string().optional(),+ projectId: optionalNonEmptyString,position: z.number().optional(),- startDate: z.string().nullable().optional(),- dueDate: z.string().nullable().optional(),- userId: z.string().nullable().optional(),+ startDate: nullableOptionalIsoDateTimeSchema,+ dueDate: nullableOptionalIsoDateTimeSchema,+ userId: nullableOptionalNonEmptyString,});server.registerTool(@@ -268,9 +283,9 @@ export function registerTools(description:"Move a task to another project (and optional column status).",inputSchema: z.object({- taskId: z.string(),- destinationProjectId: z.string(),- destinationStatus: z.string().optional(),+ taskId: nonEmptyString,+ destinationProjectId: nonEmptyString,+ destinationStatus: optionalNonEmptyString,}),},async (args) =>@@ -292,8 +307,8 @@ export function registerTools({description: "Update only the status (column) of a task.",inputSchema: z.object({- taskId: z.string(),- status: z.string(),+ taskId: nonEmptyString,+ status: nonEmptyString,}),},async (args) =>@@ -309,7 +324,7 @@ export function registerTools("list_task_comments",{description: "List comments on a task.",- inputSchema: z.object({ taskId: z.string() }),+ inputSchema: z.object({ taskId: nonEmptyString }),},async (args) =>run(() =>@@ -324,8 +339,8 @@ export function registerTools({description: "Add a comment to a task.",inputSchema: z.object({- taskId: z.string(),- content: z.string().min(1),+ taskId: nonEmptyString,+ content: nonEmptyString,}),},async (args) =>@@ -341,7 +356,7 @@ export function registerTools("list_workspace_labels",{description: "List labels defined in a workspace.",- inputSchema: z.object({ workspaceId: z.string() }),+ inputSchema: z.object({ workspaceId: nonEmptyString }),},async (args) =>run(() =>@@ -358,10 +373,10 @@ export function registerTools(description:"Create a label in a workspace (optionally attach to a task).",inputSchema: z.object({- name: z.string(),- color: z.string(),- workspaceId: z.string(),- taskId: z.string().optional(),+ name: nonEmptyString,+ color: hexColorSchema,+ workspaceId: nonEmptyString,+ taskId: optionalNonEmptyString,}),},async (args) =>@@ -383,8 +398,8 @@ export function registerTools({description: "Attach an existing label to a task.",inputSchema: z.object({- labelId: z.string(),- taskId: z.string(),+ labelId: nonEmptyString,+ taskId: nonEmptyString,}),},async (args) =>@@ -400,7 +415,7 @@ export function registerTools("detach_label_from_task",{description: "Detach a label from its current task.",- inputSchema: z.object({ labelId: z.string() }),+ inputSchema: z.object({ labelId: nonEmptyString }),},async (args) =>run(() =>