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.

feat(planka-import): authenticate with a PLANKA API key

Andrejff5e3fc6b91a
diff --git a/apps/docs/core/migrations/from-planka.mdx b/apps/docs/core/migrations/from-planka.mdx
index 2b3afc23b..d0afb42cc 100644
--- a/apps/docs/core/migrations/from-planka.mdx
+++ b/apps/docs/core/migrations/from-planka.mdx
@@ -14,7 +14,9 @@ machine: the CLI talks to both servers itself, so no third party sees them.
You need:
-- A PLANKA account that can see the boards you want to move.
+- A PLANKA account that can see the boards you want to move. If you sign in
+ through SSO and have no password, create a PLANKA API key and use
+ `--planka-api-key`.
- A Kaneo workspace, and an API key from **Settings → API keys**.
- Node.js 20 or newer.
@@ -106,9 +108,10 @@ resulting Kaneo project is named `Project - Board`.
**"This PLANKA instance requires you to accept its terms"**: sign in through
the PLANKA web UI once and accept them, then run the import again.
-**Two-factor authentication**: password login can't complete a TOTP challenge.
-Copy an access token from your browser's dev tools and pass `--planka-token`
-instead of a username and password.
+**Two-factor authentication, or an SSO-only account**: password login either
+can't complete a TOTP challenge, or there is no local password at all. Create a
+PLANKA API key for the account and pass `--planka-api-key` instead. This is the
+recommended credential: it doesn't expire the way a copied session token does.
**A board failed partway**: failures are isolated per board, so the rest still
import and the summary names the one that failed. Delete the half-created Kaneo
@@ -128,6 +131,7 @@ before retrying.
| `--planka-user <user>` | Email or username |
| `--planka-password <pass>` | Password, or set `PLANKA_PASSWORD` |
| `--planka-token <token>` | Use an existing access token instead of logging in |
+| `--planka-api-key <key>` | Use a PLANKA API key, or set `PLANKA_API_KEY`. Works for SSO-only accounts |
| `--kaneo-url <url>` | Kaneo instance URL (default `https://app.kaneo.app`) |
| `--kaneo-api-key <key>` | Kaneo API key, or set `KANEO_API_KEY` |
| `--workspace <id>` | Target workspace |
diff --git a/packages/planka-import/README.md b/packages/planka-import/README.md
index 52e677b0e..821a622ac 100644
--- a/packages/planka-import/README.md
+++ b/packages/planka-import/README.md
@@ -70,6 +70,7 @@ assignments come across on the first run.
| `--planka-user <user>` | Email or username (prompted if omitted) |
| `--planka-password <pass>` | Password (or set `PLANKA_PASSWORD`) |
| `--planka-token <token>` | Use an existing access token instead of logging in |
+| `--planka-api-key <key>` | Use a PLANKA API key (or `PLANKA_API_KEY`). Works for SSO-only accounts |
| `--kaneo-url <url>` | Kaneo instance URL (default `https://app.kaneo.app`) |
| `--kaneo-api-key <key>` | Kaneo API key (or set `KANEO_API_KEY`) |
| `--workspace <id>` | Target workspace (prompted if omitted) |
@@ -81,9 +82,9 @@ assignments come across on the first run.
| `--report <path>` | Write a JSON report |
| `-y, --yes` | Skip the confirmation prompt |
-If your PLANKA account has two-factor authentication enabled, password login
-won't work. Grab a token from your browser's dev tools and pass
-`--planka-token` instead.
+If your PLANKA account uses SSO or has two-factor authentication enabled, there
+is no password to log in with. Create a PLANKA API key for the account and pass
+`--planka-api-key` instead.
## Re-running
diff --git a/packages/planka-import/src/args.ts b/packages/planka-import/src/args.ts
index 9e5337ff2..3303e9d3f 100644
--- a/packages/planka-import/src/args.ts
+++ b/packages/planka-import/src/args.ts
@@ -3,6 +3,7 @@ export type ParsedArgs = {
plankaUser?: string;
plankaPassword?: string;
plankaToken?: string;
+ plankaApiKey?: string;
kaneoUrl?: string;
kaneoApiKey?: string;
workspace?: string;
@@ -22,6 +23,7 @@ const STRING_FLAGS: Record<string, keyof ParsedArgs> = {
"--planka-user": "plankaUser",
"--planka-password": "plankaPassword",
"--planka-token": "plankaToken",
+ "--planka-api-key": "plankaApiKey",
"--kaneo-url": "kaneoUrl",
"--kaneo-api-key": "kaneoApiKey",
"--workspace": "workspace",
@@ -110,6 +112,9 @@ PLANKA source:
--planka-user <user> Email or username (prompted if omitted)
--planka-password <pass> Password (env PLANKA_PASSWORD, or prompted)
--planka-token <token> Use an existing access token instead of logging in
+ --planka-api-key <key> Use a PLANKA user API key (env PLANKA_API_KEY).
+ Best option for SSO-only accounts, which have no
+ password to log in with
Kaneo target:
--kaneo-url <url> Kaneo instance URL (default https://app.kaneo.app)
diff --git a/packages/planka-import/src/colors.ts b/packages/planka-import/src/colors.ts
index e9a481dee..fd06ed92d 100644
--- a/packages/planka-import/src/colors.ts
+++ b/packages/planka-import/src/colors.ts
@@ -1,5 +1,4 @@
-// PLANKA stores label and list colors as names; Kaneo stores hex. Values are
-// read off PLANKA's own stylesheet so migrated labels keep their exact color.
+// Hex values taken from PLANKA's own stylesheet.
const LABEL_COLORS: Record<string, string> = {
"muddy-grey": "#69655a",
"autumn-leafs": "#c9b037",
diff --git a/packages/planka-import/src/index.ts b/packages/planka-import/src/index.ts
index dff063e26..ad14da365 100644
--- a/packages/planka-import/src/index.ts
+++ b/packages/planka-import/src/index.ts
@@ -34,12 +34,15 @@ async function main(): Promise<number> {
}));
if (!plankaUrl) throw new Error("--planka-url is required");
+ const plankaApiKey = args.plankaApiKey ?? process.env.PLANKA_API_KEY;
+
const planka = new PlankaClient({
baseUrl: plankaUrl,
...(args.plankaToken ? { token: args.plankaToken } : {}),
+ ...(plankaApiKey ? { apiKey: plankaApiKey } : {}),
});
- if (!args.plankaToken) {
+ if (!planka.isAuthenticated) {
const user =
args.plankaUser ??
(await ask(interactive, {
@@ -112,8 +115,6 @@ async function main(): Promise<number> {
workspaceId = await selectWorkspace(kaneo, interactive);
}
- // The dry run reads PLANKA only, so it can run before a Kaneo key exists and
- // is the honest way to show what an import would do.
const preview = await migrate({
planka,
kaneo,
diff --git a/packages/planka-import/src/kaneo.ts b/packages/planka-import/src/kaneo.ts
index 3c913b3ab..6de65f03d 100644
--- a/packages/planka-import/src/kaneo.ts
+++ b/packages/planka-import/src/kaneo.ts
@@ -5,7 +5,6 @@ export type KaneoTask = { id: string; title: string; number: number };
export type KaneoLabel = { id: string; name: string; color: string };
export type KaneoMember = { id: string; name: string; email: string };
-/** Kaneo API base URL without trailing slash and without `/api` suffix. */
export function normalizeBaseUrl(raw: string): string {
const trimmed = raw.trim().replace(/\/+$/, "");
try {
@@ -96,12 +95,8 @@ export class KaneoClient {
);
}
- /**
- * Idempotent in both scopes: without `taskId` it upserts the workspace-level
- * label, with `taskId` it upserts the label on that task. We never use
- * PUT /label/:id/task, which *moves* an existing label row and would detach
- * it from whichever task already had it.
- */
+ // Never use PUT /label/:id/task: it moves an existing label row off
+ // whichever task already had it. This upserts in both scopes.
createLabel(input: {
name: string;
color: string;
diff --git a/packages/planka-import/src/keys.ts b/packages/planka-import/src/keys.ts
index 4b9763aac..d75de98ac 100644
--- a/packages/planka-import/src/keys.ts
+++ b/packages/planka-import/src/keys.ts
@@ -17,9 +17,6 @@ export const RESERVED_COLUMN_SLUGS = ["planned", "archived"];
const PROJECT_KEY_MAX = 8;
-// Kaneo's project "key" is the short prefix on task references (ENG-14). PLANKA
-// has no equivalent, so we synthesise one: initials for multi-word names,
-// otherwise a prefix of the name.
export function toProjectKey(name: string): string {
const words = name
.normalize("NFKC")
@@ -39,7 +36,6 @@ export function toProjectKey(name: string): string {
return normalized.length > 0 ? normalized : "PROJ";
}
-// Appends -2, -3, … until the candidate is free, respecting the field's cap.
export function uniqueKey(
candidate: string,
taken: Set<string>,
diff --git a/packages/planka-import/src/mapping.ts b/packages/planka-import/src/mapping.ts
index 82db09da2..2e12bfd79 100644
--- a/packages/planka-import/src/mapping.ts
+++ b/packages/planka-import/src/mapping.ts
@@ -18,13 +18,8 @@ export type PlannedColumn = {
const UNTITLED_COLUMN = "Untitled";
-/**
- * Turns PLANKA lists into the columns we will create, in board order.
- *
- * Kaneo derives a column's slug from its name and rejects duplicates and the
- * reserved virtual statuses, so a name that would collide has to be adjusted
- * here rather than fixed up after the fact.
- */
+// Kaneo rejects duplicate and reserved slugs, so a colliding name has to be
+// adjusted before the column is created.
export function planColumns(lists: PlankaList[]): PlannedColumn[] {
const ordered = [...lists].sort(
(a, b) => (a.position ?? 0) - (b.position ?? 0),
@@ -60,15 +55,10 @@ export function planColumns(lists: PlankaList[]): PlannedColumn[] {
return planned;
}
-/** Cards in the order they appear on the board. */
export function sortCards(cards: PlankaCard[]): PlankaCard[] {
return [...cards].sort((a, b) => (a.position ?? 0) - (b.position ?? 0));
}
-/**
- * Kaneo has no checklist primitive, so PLANKA's task lists are appended to the
- * description as markdown checkboxes instead of being dropped.
- */
export function buildDescription(
card: PlankaCard,
taskLists: PlankaTaskList[],
@@ -101,10 +91,6 @@ export function displayName(user: PlankaUser | undefined): string {
);
}
-/**
- * Comments are re-created under the API key's owner, so the original author and
- * date are preserved in the body rather than silently lost.
- */
export function formatComment(
comment: PlankaComment,
author: PlankaUser | undefined,
@@ -128,11 +114,6 @@ export function toDueDate(card: PlankaCard): string | undefined {
return Number.isNaN(parsed.getTime()) ? undefined : parsed.toISOString();
}
-/**
- * A Kaneo project maps to a PLANKA board, not a PLANKA project, because the
- * board is what holds lists and cards. The project name is only worth
- * prefixing when it would otherwise be ambiguous.
- */
export function boardProjectName(
projectName: string,
boardName: string,
diff --git a/packages/planka-import/src/migrate.ts b/packages/planka-import/src/migrate.ts
index a1752dd59..530813c48 100644
--- a/packages/planka-import/src/migrate.ts
+++ b/packages/planka-import/src/migrate.ts
@@ -214,8 +214,6 @@ async function migrateBoard(context: {
).length;
if (dryRun) {
- // The comment count is the denormalized per-card total, so a dry run can
- // report it without fetching every card's comment thread.
report.comments = skipComments
? 0
: cards.reduce((total, card) => total + (card.commentsTotal ?? 0), 0);
@@ -236,9 +234,7 @@ async function migrateBoard(context: {
});
report.kaneoProjectId = project.id;
- // Kaneo seeds every new project with four default columns. They are empty at
- // this point, so removing them before creating ours keeps the board a 1:1
- // mirror of PLANKA instead of leaving unused columns behind.
+ // Kaneo seeds four default columns on create; drop them while still empty.
for (const existing of await kaneo.listColumns(project.id)) {
await kaneo.deleteColumn(existing.id);
}
@@ -256,8 +252,6 @@ async function migrateBoard(context: {
const name = label.name?.trim() || label.color;
const color = labelColorToHex(label.color);
- // Register the label at workspace level first so it shows up in Kaneo's
- // label picker, not only on the tasks that happen to carry it.
await kaneo.createLabel({ name, color, workspaceId });
labelIdByPlankaId.set(label.id, { name, color });
}
@@ -326,8 +320,7 @@ function resolveAssignee(
usersById: Map<string, PlankaUser>,
membersByEmail: Map<string, string>,
): string | undefined {
- // PLANKA allows several members per card; Kaneo has a single assignee, so we
- // take the first member who also exists in the target workspace.
+ // Kaneo has a single assignee; take the first member present in the workspace.
for (const membership of memberships) {
if (membership.cardId !== cardId) continue;
diff --git a/packages/planka-import/src/planka.test.ts b/packages/planka-import/src/planka.test.ts
new file mode 100644
index 000000000..54394d531
--- /dev/null
+++ b/packages/planka-import/src/planka.test.ts
@@ -0,0 +1,80 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { normalizeBaseUrl, PlankaClient } from "./planka.js";
+
+const realFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+function captureHeaders() {
+ const calls: Headers[] = [];
+ globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => {
+ calls.push(new Headers(init?.headers));
+ return new Response(JSON.stringify({ items: [], included: {} }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }) as unknown as typeof fetch;
+ return calls;
+}
+
+describe("PlankaClient auth headers", () => {
+ it("sends an API key in x-api-key, never as a bearer", async () => {
+ const calls = captureHeaders();
+ await new PlankaClient({
+ baseUrl: "https://planka.example.com",
+ apiKey: "secret-key",
+ }).listProjects();
+
+ expect(calls[0]?.get("x-api-key")).toBe("secret-key");
+ expect(calls[0]?.get("authorization")).toBeNull();
+ });
+
+ it("sends a session token as a bearer", async () => {
+ const calls = captureHeaders();
+ await new PlankaClient({
+ baseUrl: "https://planka.example.com",
+ token: "jwt-token",
+ }).listProjects();
+
+ expect(calls[0]?.get("authorization")).toBe("Bearer jwt-token");
+ expect(calls[0]?.get("x-api-key")).toBeNull();
+ });
+
+ it("prefers the token when both are supplied", async () => {
+ const calls = captureHeaders();
+ await new PlankaClient({
+ baseUrl: "https://planka.example.com",
+ token: "jwt-token",
+ apiKey: "secret-key",
+ }).listProjects();
+
+ expect(calls[0]?.get("authorization")).toBe("Bearer jwt-token");
+ expect(calls[0]?.get("x-api-key")).toBeNull();
+ });
+});
+
+describe("isAuthenticated", () => {
+ it("is true with either credential and false with neither", () => {
+ const base = "https://planka.example.com";
+ expect(new PlankaClient({ baseUrl: base }).isAuthenticated).toBe(false);
+ expect(
+ new PlankaClient({ baseUrl: base, token: "t" }).isAuthenticated,
+ ).toBe(true);
+ expect(
+ new PlankaClient({ baseUrl: base, apiKey: "k" }).isAuthenticated,
+ ).toBe(true);
+ });
+});
+
+describe("normalizeBaseUrl", () => {
+ it("strips trailing slashes and assumes https", () => {
+ expect(normalizeBaseUrl("planka.example.com/")).toBe(
+ "https://planka.example.com",
+ );
+ expect(normalizeBaseUrl("http://localhost:3000//")).toBe(
+ "http://localhost:3000",
+ );
+ });
+});
diff --git a/packages/planka-import/src/planka.ts b/packages/planka-import/src/planka.ts
index 01964c34d..15c24a3ba 100644
--- a/packages/planka-import/src/planka.ts
+++ b/packages/planka-import/src/planka.ts
@@ -17,9 +17,7 @@ export type PlankaBoard = {
position: number | null;
};
-// active/closed are the kanban lists whose cards arrive in full from
-// GET /boards/:id. archive and trash are "endless" lists that paginate
-// separately, and we deliberately do not migrate them.
+// archive and trash paginate separately and never arrive with GET /boards/:id.
export const MIGRATABLE_LIST_TYPES = ["active", "closed"];
export type PlankaList = {
@@ -102,10 +100,16 @@ export function normalizeBaseUrl(url: string): string {
export class PlankaClient {
readonly baseUrl: string;
private token: string | null;
+ private readonly apiKey: string | null;
- constructor(options: { baseUrl: string; token?: string }) {
+ constructor(options: { baseUrl: string; token?: string; apiKey?: string }) {
this.baseUrl = normalizeBaseUrl(options.baseUrl);
this.token = options.token ?? null;
+ this.apiKey = options.apiKey ?? null;
+ }
+
+ get isAuthenticated(): boolean {
+ return this.token !== null || this.apiKey !== null;
}
async login(emailOrUsername: string, password: string): Promise<void> {
@@ -155,8 +159,6 @@ export class PlankaClient {
const users = new Map<string, PlankaUser>();
let beforeId: string | undefined;
- // The endpoint is cursor-paginated and has no "total" to check against, so
- // we walk until a page comes back empty or repeats the cursor.
while (true) {
const query = beforeId ? `?beforeId=${encodeURIComponent(beforeId)}` : "";
const page = await this.request<{
@@ -177,15 +179,18 @@ export class PlankaClient {
beforeId = oldest.id;
}
- // PLANKA returns newest first; replay them in the order they were written.
+ // PLANKA returns newest first.
comments.reverse();
return { comments, users: [...users.values()] };
}
private async request<T>(path: string, init?: RequestInit): Promise<T> {
const headers = new Headers(init?.headers);
+ // An API key is rejected as a bearer; it only works in x-api-key.
if (this.token) {
headers.set("Authorization", `Bearer ${this.token}`);
+ } else if (this.apiKey) {
+ headers.set("x-api-key", this.apiKey);
}
headers.set("Accept", "application/json");
@@ -234,11 +239,6 @@ export class PlankaHttpError extends Error {
}
}
-/**
- * PLANKA answers a password login with 403 and a `step` when the account still
- * has something to clear (instance terms, or two-factor). Neither can be
- * completed non-interactively, so say which one it is and how to get past it.
- */
function describeLoginFailure(error: PlankaHttpError): string {
const step =
typeof error.body === "object" && error.body !== null
@@ -250,7 +250,7 @@ function describeLoginFailure(error: PlankaHttpError): string {
}
if (step === "verify-totp") {
- return "This PLANKA account has two-factor authentication enabled, which password login cannot complete. Copy an access token from your browser's dev tools and pass --planka-token instead.";
+ return "This PLANKA account has two-factor authentication enabled, which password login cannot complete. Create a PLANKA API key for the account and pass --planka-api-key instead.";
}
return error.message;