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(cli): harden terminal output and address review findings

Andrej74233d53701e
diff --git a/packages/cli/package.json b/packages/cli/package.json
index d3c6e7245..bc54159cc 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -44,14 +44,13 @@
},
"devDependencies": {
"@effect/platform-node": "4.0.2",
- "@gabrielbryk/jq-ts": "^1.7.0",
+ "@gabrielbryk/jq-ts": "1.7.0",
"@kaneo/mcp": "workspace:*",
"@kaneo/typescript-config": "workspace:*",
"@types/node": "^26.6.2",
- "@types/pngjs": "^6.0.5",
"effect": "4.0.2",
- "jpeg-js": "^0.4.4",
- "pngjs": "^7.0.0",
+ "jpeg-js": "0.4.4",
+ "pngjs": "7.0.0",
"tsx": "^4.23.15",
"typescript": "^7.0.2",
"vite-plus": "catalog:"
diff --git a/packages/cli/src/api/error-body.ts b/packages/cli/src/api/error-body.ts
index a4ae3c0cd..354698122 100644
--- a/packages/cli/src/api/error-body.ts
+++ b/packages/cli/src/api/error-body.ts
@@ -1,3 +1,5 @@
+import { sanitizeText } from "../render/sanitize.js";
+
export type ErrorBody = {
readonly message: string;
readonly code: string | null;
@@ -5,6 +7,15 @@ export type ErrorBody = {
};
export function parseErrorBody(text: string, status: number): ErrorBody {
+ const body = readErrorBody(text, status);
+ return {
+ message: sanitizeText(body.message),
+ code: body.code === null ? null : sanitizeText(body.code),
+ missingPermissions: body.missingPermissions.map(sanitizeText),
+ };
+}
+
+function readErrorBody(text: string, status: number): ErrorBody {
const fallback = text.trim().slice(0, 500) || `HTTP ${status}`;
try {
const body: unknown = JSON.parse(text);
diff --git a/packages/cli/src/api/kaneo-api.ts b/packages/cli/src/api/kaneo-api.ts
index 8f57d5efb..0862d8202 100644
--- a/packages/cli/src/api/kaneo-api.ts
+++ b/packages/cli/src/api/kaneo-api.ts
@@ -20,6 +20,7 @@ import {
UnexpectedResponse,
} from "../errors/errors.js";
import { type Credentials, Session } from "../services/session.js";
+import { sanitizeDeep } from "../render/sanitize.js";
import { parseErrorBody, parseRetryAfter } from "./error-body.js";
import { toApiFailure } from "./to-api-failure.js";
@@ -33,6 +34,7 @@ export type RequestOptions = {
readonly query?: Query;
readonly body?: unknown;
readonly credentials?: Credentials;
+ readonly raw?: boolean;
};
export type KaneoApiShape = {
@@ -177,7 +179,7 @@ export const KaneoApiLayer = Layer.effect(
}),
),
);
- return yield* decode(json).pipe(
+ return yield* decode(options.raw ? json : sanitizeDeep(json)).pipe(
Effect.mapError(
(error) =>
new UnexpectedResponse({
diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.ts
index b03b5428e..2709d9deb 100644
--- a/packages/cli/src/commands/api.ts
+++ b/packages/cli/src/commands/api.ts
@@ -84,6 +84,7 @@ export const runApi = Effect.fn("command.api")(function* (options: {
const api = yield* KaneoApi;
const response = yield* withSpinner(`${method} ${target.success.path}`)(
api.request(method, target.success.path, Schema.Unknown, {
+ raw: true,
query: { ...target.success.query, ...query.success },
body,
}),
diff --git a/packages/cli/src/commands/task/attach.ts b/packages/cli/src/commands/task/attach.ts
index 9e7a42a19..f6f8d8600 100644
--- a/packages/cli/src/commands/task/attach.ts
+++ b/packages/cli/src/commands/task/attach.ts
@@ -113,6 +113,8 @@ const previewLines = Effect.fnUntraced(function* (
return lines;
});
+const PLACEHOLDER_ASSET_URL = `https://${"x".repeat(64)}/api/asset/${"x".repeat(64)}`;
+
export const runTaskAttach = Effect.fn("command.task.attach")(
function* (options: {
readonly task: string;
@@ -143,6 +145,25 @@ export const runTaskAttach = Effect.fn("command.task.attach")(
);
const label = resolved.ticketId ?? resolved.task.id.slice(0, 8);
+ if (target === "comment") {
+ const estimate = commentWithFiles(
+ text,
+ files.map((file) => ({
+ name: file.name,
+ url: PLACEHOLDER_ASSET_URL,
+ contentType: file.contentType,
+ size: file.bytes.byteLength,
+ kind: isInlineImageType(file.contentType) ? "image" : "attachment",
+ })),
+ );
+ if (estimate.length > COMMENT_MAX_LENGTH) {
+ return yield* new InvalidArgument({
+ message: `The comment would be about ${estimate.length} characters long, and the limit is ${COMMENT_MAX_LENGTH}.`,
+ hint: "Attach fewer files, or shorten the message.",
+ });
+ }
+ }
+
const uploaded: UploadedFile[] = [];
for (const [index, file] of files.entries()) {
const progress =
diff --git a/packages/cli/src/commands/unlink.ts b/packages/cli/src/commands/unlink.ts
index 25e41ba57..6b41c1d7f 100644
--- a/packages/cli/src/commands/unlink.ts
+++ b/packages/cli/src/commands/unlink.ts
@@ -4,6 +4,7 @@ import { Command, Flag } from "effect/cli";
import {
deleteRepoConfig,
hasRepoLink,
+ linkFilePath,
readRepoConfigObject,
removeRepoLink,
writeRepoConfig,
@@ -13,7 +14,7 @@ import { emit } from "../output/emit.js";
import { Output } from "../output/output.js";
import { confirm } from "../prompts/confirm.js";
import type { Ui } from "../render/ui.js";
-import { Session } from "../services/session.js";
+import { CliEnvironment } from "../services/cli-environment.js";
import { ApiLayer } from "./api-layer.js";
type UnlinkResult = {
@@ -40,10 +41,10 @@ export function renderUnlink(ui: Ui, result: UnlinkResult): string[] {
export const runUnlink = Effect.fn("command.unlink")(function* (options: {
readonly yes: boolean;
}) {
- const session = yield* Session;
+ const environment = yield* CliEnvironment;
const output = yield* Output;
- const path = session.repo?.path;
- const existing = path ? yield* readRepoConfigObject(path) : undefined;
+ const path = linkFilePath(environment.cwd);
+ const existing = yield* readRepoConfigObject(path);
if (!path || !existing || !hasRepoLink(existing)) {
yield* emit<UnlinkResult>(
diff --git a/packages/cli/src/images/pngjs.d.ts b/packages/cli/src/images/pngjs.d.ts
new file mode 100644
index 000000000..54c67dccd
--- /dev/null
+++ b/packages/cli/src/images/pngjs.d.ts
@@ -0,0 +1,12 @@
+declare module "pngjs" {
+ export class PNG {
+ constructor(options?: { width?: number; height?: number });
+ width: number;
+ height: number;
+ data: Buffer;
+ static sync: {
+ read(buffer: Buffer): PNG;
+ write(png: PNG): Buffer;
+ };
+ }
+}
diff --git a/packages/cli/src/render/cell.ts b/packages/cli/src/render/cell.ts
index 48aa95395..7d8355811 100644
--- a/packages/cli/src/render/cell.ts
+++ b/packages/cli/src/render/cell.ts
@@ -1,4 +1,5 @@
import { hyperlink } from "./link.js";
+import { sanitizeText } from "./sanitize.js";
import type { Style } from "./theme.js";
import type { Ui } from "./ui.js";
import { stringWidth, truncate } from "./width.js";
@@ -42,7 +43,8 @@ export function fitCell(cell: Cell, width: number, ellipsis: string): Cell {
export function renderCell(cell: Cell, ui: Ui): string {
return cell
.map((segment) => {
- const styled = segment.style ? segment.style(segment.text) : segment.text;
+ const clean = sanitizeText(segment.text);
+ const styled = segment.style ? segment.style(clean) : clean;
return segment.href
? hyperlink(styled, segment.href, ui.caps.hyperlinks)
: styled;
diff --git a/packages/cli/src/render/link.ts b/packages/cli/src/render/link.ts
index f81f0ad19..d28fbfb20 100644
--- a/packages/cli/src/render/link.ts
+++ b/packages/cli/src/render/link.ts
@@ -1,4 +1,6 @@
+import { isSafeUrl } from "./sanitize.js";
+
export function hyperlink(text: string, url: string, enabled: boolean): string {
- if (!enabled || !text) return text;
+ if (!enabled || !text || !isSafeUrl(url)) return text;
return `\u001b]8;;${url}\u001b\\${text}\u001b]8;;\u001b\\`;
}
diff --git a/packages/cli/src/render/sanitize.test.ts b/packages/cli/src/render/sanitize.test.ts
new file mode 100644
index 000000000..9299688a7
--- /dev/null
+++ b/packages/cli/src/render/sanitize.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vite-plus/test";
+import { isSafeUrl, sanitizeDeep, sanitizeText } from "./sanitize.js";
+
+const ESC = "\u001b";
+
+describe("sanitizeText", () => {
+ it("removes escape sequences and other control characters", () => {
+ expect(sanitizeText(`Fix ${ESC}[2J${ESC}]0;pwned\u0007login`)).toBe(
+ "Fix [2J]0;pwnedlogin",
+ );
+ expect(sanitizeText("a\u009bb\u007fc")).toBe("abc");
+ });
+
+ it("keeps tabs and line breaks, normalizing carriage returns", () => {
+ expect(sanitizeText("one\ttwo\r\nthree\rfour")).toBe(
+ "one\ttwo\nthree\nfour",
+ );
+ });
+
+ it("keeps ordinary Unicode", () => {
+ expect(sanitizeText("Café 日本 🚀")).toBe("Café 日本 🚀");
+ });
+});
+
+describe("sanitizeDeep", () => {
+ it("cleans every string in nested data and leaves other values alone", () => {
+ expect(
+ sanitizeDeep({
+ title: `x${ESC}[31m`,
+ tags: [`a${ESC}`],
+ count: 2,
+ ok: true,
+ none: null,
+ }),
+ ).toEqual({ title: "x[31m", tags: ["a"], count: 2, ok: true, none: null });
+ });
+});
+
+describe("isSafeUrl", () => {
+ it("accepts plain http and https URLs only", () => {
+ expect(isSafeUrl("https://cloud.kaneo.app/dashboard?x=1&y=2")).toBe(true);
+ expect(isSafeUrl("http://localhost:1337/device")).toBe(true);
+ expect(isSafeUrl(`https://x.test/${ESC}]8;;evil`)).toBe(false);
+ expect(isSafeUrl("https://x.test/a b")).toBe(false);
+ expect(isSafeUrl("file:///etc/passwd")).toBe(false);
+ expect(isSafeUrl("javascript:alert(1)")).toBe(false);
+ });
+});
diff --git a/packages/cli/src/render/sanitize.ts b/packages/cli/src/render/sanitize.ts
new file mode 100644
index 000000000..facaee9a7
--- /dev/null
+++ b/packages/cli/src/render/sanitize.ts
@@ -0,0 +1,28 @@
+const range = (from: number, to: number) =>
+ `${String.fromCharCode(from)}-${String.fromCharCode(to)}`;
+
+const CONTROL = new RegExp(
+ `[${range(0, 8)}${range(11, 31)}${range(127, 159)}]`,
+ "g",
+);
+
+export function sanitizeText(value: string): string {
+ return value.replace(/\r\n?/g, "\n").replace(CONTROL, "");
+}
+
+export function sanitizeDeep(value: unknown): unknown {
+ if (typeof value === "string") return sanitizeText(value);
+ if (Array.isArray(value)) return value.map(sanitizeDeep);
+ if (value !== null && typeof value === "object") {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, entry]) => [key, sanitizeDeep(entry)]),
+ );
+ }
+ return value;
+}
+
+const SAFE_URL = /^https?:\/\/[\x21-\x7e]+$/i;
+
+export function isSafeUrl(url: string): boolean {
+ return SAFE_URL.test(url);
+}
diff --git a/packages/cli/src/services/desktop.ts b/packages/cli/src/services/desktop.ts
index 4dab23371..dd828e49e 100644
--- a/packages/cli/src/services/desktop.ts
+++ b/packages/cli/src/services/desktop.ts
@@ -1,5 +1,6 @@
import { spawn } from "node:child_process";
import { Context, Effect, Layer } from "effect";
+import { isSafeUrl } from "../render/sanitize.js";
import { CliEnvironment } from "./cli-environment.js";
export type DesktopShape = {
@@ -61,7 +62,7 @@ export const DesktopLive = Layer.effect(
: platform === "darwin"
? { command: "open", args: [] }
: platform === "win32"
- ? { command: "cmd", args: ["/c", "start", '""'] }
+ ? { command: "rundll32", args: ["url.dll,FileProtocolHandler"] }
: { command: "xdg-open", args: [] };
const clipboards: ReadonlyArray<Launch> =
@@ -77,7 +78,7 @@ export const DesktopLive = Layer.effect(
return {
openUrl: (url) =>
- opener
+ opener && isSafeUrl(url)
? Effect.promise(() =>
run({ command: opener.command, args: [...opener.args, url] }),
)
diff --git a/packages/cli/src/services/device-auth.test.ts b/packages/cli/src/services/device-auth.test.ts
index 769e729d5..e91cc1031 100644
--- a/packages/cli/src/services/device-auth.test.ts
+++ b/packages/cli/src/services/device-auth.test.ts
@@ -1,6 +1,6 @@
import { DeviceCodeRequestError } from "@kaneo/mcp/device-flow";
import { describe, expect, it } from "vite-plus/test";
-import { toDeviceFailure } from "./device-auth.js";
+import { sanitizeDeviceCode, toDeviceFailure } from "./device-auth.js";
const toFailure = toDeviceFailure(
"https://cloud.kaneo.app",
@@ -34,3 +34,21 @@ describe("toDeviceFailure", () => {
);
});
});
+
+describe("sanitizeDeviceCode", () => {
+ it("strips escape sequences from server supplied fields", () => {
+ const code = sanitizeDeviceCode({
+ device_code: "device",
+ user_code: "ABCD\u001b[2JEFGH",
+ verification_uri: "https://x.test/device\u0007",
+ verification_uri_complete: "https://x.test/device?c=1\u001b]8;;",
+ interval: 5,
+ expires_in: 600,
+ });
+ expect(code.user_code).toBe("ABCD[2JEFGH");
+ expect(code.verification_uri).toBe("https://x.test/device");
+ expect(code.verification_uri_complete).toBe(
+ "https://x.test/device?c=1]8;;",
+ );
+ });
+});
diff --git a/packages/cli/src/services/device-auth.ts b/packages/cli/src/services/device-auth.ts
index 3bfc3f317..b6ffca152 100644
--- a/packages/cli/src/services/device-auth.ts
+++ b/packages/cli/src/services/device-auth.ts
@@ -11,6 +11,7 @@ import {
ServerUnreachable,
UnexpectedResponse,
} from "../errors/errors.js";
+import { sanitizeText } from "../render/sanitize.js";
export const DEVICE_CLIENT_ID = "kaneo-cli";
@@ -46,12 +47,29 @@ export function toDeviceFailure(apiUrl: string, endpoint: string) {
};
}
+export function sanitizeDeviceCode(
+ code: DeviceCodeResponse,
+): DeviceCodeResponse {
+ return {
+ ...code,
+ user_code: sanitizeText(code.user_code),
+ verification_uri: sanitizeText(code.verification_uri),
+ ...(code.verification_uri_complete === undefined
+ ? {}
+ : {
+ verification_uri_complete: sanitizeText(
+ code.verification_uri_complete,
+ ),
+ }),
+ };
+}
+
export const DeviceAuthLive = Layer.succeed(DeviceAuth, {
requestCode: (apiUrl) =>
Effect.tryPromise({
try: () => requestDeviceCode(apiUrl, DEVICE_CLIENT_ID),
catch: toDeviceFailure(apiUrl, "POST /api/auth/device/code"),
- }),
+ }).pipe(Effect.map(sanitizeDeviceCode)),
poll: (apiUrl, deviceCode) =>
Effect.tryPromise({
try: () => pollDeviceTokenOnce(apiUrl, DEVICE_CLIENT_ID, deviceCode),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index dd191ec07..3b39b8498 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -105,7 +105,7 @@ importers:
version: 7.0.2
vite-plus:
specifier: 'catalog:'
apps/api:
dependencies:
@@ -223,7 +223,7 @@ importers:
vitest:
specifier: 'catalog:'
apps/site:
dependencies:
@@ -633,7 +633,7 @@ importers:
vite-plus:
specifier: 'catalog:'
packages/cli:
devDependencies:
@@ -641,7 +641,7 @@ importers:
specifier: 4.0.2
version: 4.0.2([email protected])([email protected](@opentelemetry/[email protected]))
'@gabrielbryk/jq-ts':
- specifier: ^1.7.0
+ specifier: 1.7.0
version: 1.7.0([email protected])
'@kaneo/mcp':
specifier: workspace:*
@@ -652,17 +652,14 @@ importers:
'@types/node':
specifier: ^26.6.2
version: 26.6.3
- '@types/pngjs':
- specifier: ^6.0.5
- version: 6.0.5
effect:
specifier: 4.0.2
version: 4.0.2
jpeg-js:
- specifier: ^0.4.4
+ specifier: 0.4.4
version: 0.4.4
pngjs:
- specifier: ^7.0.0
+ specifier: 7.0.0
version: 7.0.0
tsx:
specifier: ^4.23.15
@@ -672,7 +669,7 @@ importers:
version: 7.0.2
vite-plus:
specifier: 'catalog:'
packages/email:
dependencies:
@@ -742,7 +739,7 @@ importers:
vite-plus:
specifier: 'catalog:'
packages/mcp:
dependencies:
@@ -795,7 +792,7 @@ importers:
vite-plus:
specifier: 'catalog:'
packages/planka-import:
dependencies:
@@ -4943,9 +4940,6 @@ packages:
resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==}
- '@types/[email protected]':
- resolution: {integrity: sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ==}
-
resolution: {integrity: sha512-qTxFi6Buiu8+50/+3DGIWLHM6QuWsEKugJnnP6iv2Mc4ncxE4A/OJkjuVOA+5X0X1S/nq5VJRa8Lu+nwcvbrKA==}
@@ -13347,7 +13341,7 @@ snapshots:
picocolors: 1.1.1
redent: 3.0.0
optionalDependencies:
dependencies:
@@ -13795,10 +13789,6 @@ snapshots:
pg-protocol: 1.15.0
pg-types: 2.2.0
- '@types/[email protected]':
- dependencies:
- '@types/node': 26.6.3
-
dependencies:
'@types/node': 26.6.3
@@ -13922,7 +13912,7 @@ snapshots:
'@testing-library/dom': 10.4.1
'@testing-library/user-event': 14.6.7(@testing-library/[email protected])
transitivePeerDependencies:
- bufferutil
- msw
@@ -13939,7 +13929,7 @@ snapshots:
pngjs: 7.0.0
sirv: 3.0.2
tinyrainbow: 3.1.1
ws: 8.21.3
transitivePeerDependencies:
- bufferutil
@@ -13957,7 +13947,7 @@ snapshots:
obug: 2.2.1
std-env: 4.2.0
tinyrainbow: 3.1.1
'@vitest/[email protected]': {}
@@ -14018,7 +14008,7 @@ snapshots:
pathe: 2.0.3
sirv: 3.0.2
tinyrainbow: 3.1.1
'@vitest/[email protected]':
dependencies:
@@ -14337,7 +14327,7 @@ snapshots:
react: 19.3.0
react-dom: 19.3.0([email protected])
solid-js: 1.9.15
transitivePeerDependencies:
- '@cloudflare/workers-types'
- '@opentelemetry/api'
@@ -14373,7 +14363,7 @@ snapshots:
react: 19.3.0
react-dom: 19.3.0([email protected])
solid-js: 1.9.15
transitivePeerDependencies:
- '@cloudflare/workers-types'
- '@opentelemetry/api'
@@ -18475,7 +18465,7 @@ snapshots:
oxlint-tsgolint: 7.0.2003
optionalDependencies:
'@voidzero-dev/vite-plus-darwin-arm64': 1.0.0
'@voidzero-dev/vite-plus-darwin-x64': 1.0.0
@@ -18530,7 +18520,7 @@ snapshots:
oxlint-tsgolint: 7.0.2003
optionalDependencies:
'@voidzero-dev/vite-plus-darwin-arm64': 1.0.0
'@voidzero-dev/vite-plus-darwin-x64': 1.0.0
@@ -18585,7 +18575,7 @@ snapshots:
tsx: 4.23.15
yaml: 2.9.0
dependencies:
'@types/chai': 5.2.3
@@ -18610,7 +18600,7 @@ snapshots:
transitivePeerDependencies:
- msw
dependencies:
'@types/chai': 5.2.3
@@ -18629,6 +18619,7 @@ snapshots:
optionalDependencies:
'@opentelemetry/api': 1.9.1
'@types/node': 26.6.3
'@vitest/coverage-v8': 5.0.3([email protected])
jsdom: 30.1.1(@noble/[email protected])
transitivePeerDependencies: