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(api): edit custom fields and search repos

Andrej793a50ca66e8
diff --git a/apps/api/src/config/response.ts b/apps/api/src/config/response.ts
index 860649d68..80cf070ed 100644
--- a/apps/api/src/config/response.ts
+++ b/apps/api/src/config/response.ts
@@ -9,6 +9,10 @@ export const configSchema = z
disableWorkspaceCreation: z.boolean(),
isDemoMode: z.boolean(),
hasSmtp: z.boolean(),
+ hasImageUploads: z.boolean().openapi({
+ description:
+ "Whether S3-compatible storage is configured, so task images and board backgrounds can be uploaded.",
+ }),
hasGithubSignIn: z.boolean(),
hasGoogleSignIn: z.boolean(),
hasDiscordSignIn: z.boolean(),
diff --git a/apps/api/src/custom-field/assert-valid-definition.ts b/apps/api/src/custom-field/assert-valid-definition.ts
new file mode 100644
index 000000000..b5ce324f8
--- /dev/null
+++ b/apps/api/src/custom-field/assert-valid-definition.ts
@@ -0,0 +1,100 @@
+import { HTTPException } from "hono/http-exception";
+import {
+ isCustomFieldValueEmpty,
+ validateCustomFieldValue,
+} from "../task/validate-task-fields";
+
+const NUMBER_PATTERN = /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
+
+type CustomFieldDefinitionInput = {
+ name: string;
+ type: string;
+ required: boolean;
+ defaultValue?: string | null;
+ options?: string[] | null;
+};
+
+function badRequest(message: string): never {
+ throw new HTTPException(400, { message });
+}
+
+function assertValidDefaultForType(
+ trimmedValue: string,
+ { name, type, options }: CustomFieldDefinitionInput,
+) {
+ if (type === "number") {
+ const parsed = Number(trimmedValue);
+ if (
+ !NUMBER_PATTERN.test(trimmedValue) ||
+ Number.isNaN(parsed) ||
+ !Number.isFinite(parsed)
+ ) {
+ badRequest("Default value must be a valid number for number type fields");
+ }
+ return;
+ }
+
+ if (type === "boolean") {
+ if (trimmedValue !== "true" && trimmedValue !== "false") {
+ badRequest(
+ "Default value must be 'true' or 'false' for boolean type fields",
+ );
+ }
+ return;
+ }
+
+ if (type === "date") {
+ const error = validateCustomFieldValue(trimmedValue, "date", name);
+ if (error) badRequest(error);
+ return;
+ }
+
+ if (type === "dropdown" && options && options.length > 0) {
+ const normalizedOptions = options.map((option) => option.trim());
+ if (!normalizedOptions.includes(trimmedValue)) {
+ badRequest("Default value must be one of the dropdown options");
+ }
+ }
+}
+
+export function assertValidDefinition(input: CustomFieldDefinitionInput) {
+ const { name, type, required, defaultValue, options } = input;
+
+ if (required && (defaultValue == null || defaultValue.trim() === "")) {
+ badRequest("Required fields must have a default value");
+ }
+
+ const trimmedValue = defaultValue?.trim();
+ if (trimmedValue) {
+ assertValidDefaultForType(trimmedValue, input);
+ }
+
+ if (type === "dropdown" && (!options || options.length < 1)) {
+ badRequest("Dropdown fields must have at least one option");
+ }
+
+ if (type === "multiselect") {
+ const normalizedOptions = new Set(
+ (options ?? []).map((option) => option.trim()).filter(Boolean),
+ );
+ if (normalizedOptions.size < 2) {
+ badRequest("Multiselect fields must have at least 2 options");
+ }
+ }
+
+ if (type === "multiselect" && defaultValue != null) {
+ const empty = isCustomFieldValueEmpty(defaultValue, "multiselect");
+ if (required && empty) {
+ badRequest("Required fields must have a default value");
+ }
+ if (!empty) {
+ const error = validateCustomFieldValue(
+ defaultValue,
+ "multiselect",
+ name,
+ options,
+ );
+ if (error) badRequest(error);
+ }
+ }
+}
diff --git a/apps/api/src/custom-field/choice-options.ts b/apps/api/src/custom-field/choice-options.ts
new file mode 100644
index 000000000..e050a0760
--- /dev/null
+++ b/apps/api/src/custom-field/choice-options.ts
@@ -0,0 +1,63 @@
+export type ChoiceType = "dropdown" | "multiselect";
+
+export function isChoiceType(type: string): type is ChoiceType {
+ return type === "dropdown" || type === "multiselect";
+}
+
+export function readOptions(options: unknown): string[] {
+ if (!Array.isArray(options)) return [];
+ return options.filter(
+ (option): option is string => typeof option === "string",
+ );
+}
+
+export function normalizeOptions(options: string[]): string[] {
+ return Array.from(
+ new Set(options.map((option) => option.trim()).filter(Boolean)),
+ );
+}
+
+export function parseChoiceValue(
+ value: string | null,
+ type: ChoiceType,
+): string[] {
+ const trimmed = value?.trim() ?? "";
+ if (!trimmed) return [];
+ if (type === "dropdown") return [trimmed];
+
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ return Array.isArray(parsed)
+ ? parsed.filter((item): item is string => typeof item === "string")
+ : [];
+ } catch {
+ return [];
+ }
+}
+
+export function convertChoiceValue(
+ value: string,
+ from: ChoiceType,
+ to: ChoiceType,
+): string | undefined {
+ if (from === to) return value;
+
+ const picked = parseChoiceValue(value, from);
+ if (to === "multiselect") {
+ return picked.length > 0 ? JSON.stringify(picked) : "";
+ }
+
+ if (picked.length > 1) return undefined;
+ return picked[0] ?? "";
+}
+
+export function findUsedOptions(
+ values: Array<string | null>,
+ type: ChoiceType,
+ candidates: string[],
+): string[] {
+ const used = new Set(
+ values.flatMap((value) => parseChoiceValue(value, type)),
+ );
+ return candidates.filter((option) => used.has(option));
+}
diff --git a/apps/api/src/custom-field/controllers/create-custom-field.ts b/apps/api/src/custom-field/controllers/create-custom-field.ts
index c0ea79d4c..fc83fbdbb 100644
--- a/apps/api/src/custom-field/controllers/create-custom-field.ts
+++ b/apps/api/src/custom-field/controllers/create-custom-field.ts
@@ -3,15 +3,10 @@ import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
customFieldDefinitionTable,
- customFieldValueTable,
projectTable,
- taskTable,
} from "../../database/schema";
-
-import {
- isCustomFieldValueEmpty,
- validateCustomFieldValue,
-} from "../../task/validate-task-fields";
+import { assertValidDefinition } from "../assert-valid-definition";
+import { insertMissingValues } from "../fill-default-values";
async function createCustomField(
projectId: string,
@@ -34,102 +29,7 @@ async function createCustomField(
throw new HTTPException(404, { message: "Project not found" });
}
- if (
- required &&
- (defaultValue === undefined ||
- defaultValue === null ||
- defaultValue.trim() === "")
- ) {
- throw new HTTPException(400, {
- message: "Required fields must have a default value",
- });
- }
-
- if (defaultValue !== undefined && defaultValue !== null) {
- const trimmedValue = defaultValue.trim();
-
- if (trimmedValue) {
- if (type === "number") {
- const numberRegex = /^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
- if (!numberRegex.test(trimmedValue)) {
- throw new HTTPException(400, {
- message:
- "Default value must be a valid number for number type fields",
- });
- }
- const parsed = Number(trimmedValue);
- if (Number.isNaN(parsed) || !Number.isFinite(parsed)) {
- throw new HTTPException(400, {
- message:
- "Default value must be a valid number for number type fields",
- });
- }
- } else if (type === "boolean") {
- if (trimmedValue !== "true" && trimmedValue !== "false") {
- throw new HTTPException(400, {
- message:
- "Default value must be 'true' or 'false' for boolean type fields",
- });
- }
- } else if (type === "date") {
- const error = validateCustomFieldValue(trimmedValue, "date", name);
- if (error) {
- throw new HTTPException(400, { message: error });
- }
- } else if (type === "dropdown") {
- if (options && options.length > 0) {
- const normalizedOptions = options.map((opt) => opt.trim());
- if (!normalizedOptions.includes(trimmedValue)) {
- throw new HTTPException(400, {
- message: "Default value must be one of the dropdown options",
- });
- }
- }
- }
- }
- }
-
- if (type === "dropdown" && (!options || options.length < 1)) {
- throw new HTTPException(400, {
- message: "Dropdown fields must have at least one option",
- });
- }
-
- if (type === "multiselect") {
- const normalizedOptions = Array.from(
- new Set(
- (options ?? [])
- .map((opt) => opt.trim())
- .filter((opt) => opt.length > 0),
- ),
- );
-
- if (normalizedOptions.length < 2) {
- throw new HTTPException(400, {
- message: "Multiselect fields must have at least 2 options",
- });
- }
- }
-
- if (type === "multiselect" && defaultValue != null) {
- const empty = isCustomFieldValueEmpty(defaultValue, "multiselect");
- if (required && empty) {
- throw new HTTPException(400, {
- message: "Required fields must have a default value",
- });
- }
- if (!empty) {
- const error = validateCustomFieldValue(
- defaultValue,
- "multiselect",
- name,
- options,
- );
- if (error) {
- throw new HTTPException(400, { message: error });
- }
- }
- }
+ assertValidDefinition({ name, type, required, defaultValue, options });
const storedDefaultValue =
type === "date" ? defaultValue?.trim() : defaultValue;
@@ -160,24 +60,11 @@ async function createCustomField(
}
if (storedDefaultValue != null && storedDefaultValue.trim() !== "") {
- const tasks = await tx
- .select({ id: taskTable.id })
- .from(taskTable)
- .where(eq(taskTable.projectId, projectId));
-
- const CHUNK_SIZE = 500;
- for (let i = 0; i < tasks.length; i += CHUNK_SIZE) {
- await tx
- .insert(customFieldValueTable)
- .values(
- tasks.slice(i, i + CHUNK_SIZE).map((task) => ({
- taskId: task.id,
- fieldId: created.id,
- value: storedDefaultValue,
- })),
- )
- .onConflictDoNothing();
- }
+ await insertMissingValues(tx, {
+ projectId,
+ fieldId: created.id,
+ value: storedDefaultValue,
+ });
}
return created;
diff --git a/apps/api/src/custom-field/controllers/update-custom-field.ts b/apps/api/src/custom-field/controllers/update-custom-field.ts
new file mode 100644
index 000000000..e71afa59a
--- /dev/null
+++ b/apps/api/src/custom-field/controllers/update-custom-field.ts
@@ -0,0 +1,96 @@
+import { and, eq, inArray, sql } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import {
+ customFieldDefinitionTable,
+ customFieldValueTable,
+} from "../../database/schema";
+import { isChoiceType } from "../choice-options";
+import { fillEmptyValues } from "../fill-default-values";
+import { planChoiceValueChanges } from "../plan-choice-value-changes";
+import {
+ type CustomFieldUpdateInput,
+ resolveFieldUpdate,
+} from "../resolve-field-update";
+
+async function updateCustomField(id: string, input: CustomFieldUpdateInput) {
+ return db.transaction(async (tx) => {
+ const [field] = await tx
+ .select()
+ .from(customFieldDefinitionTable)
+ .where(eq(customFieldDefinitionTable.id, id))
+ .limit(1)
+ .for("update");
+
+ if (!field) {
+ throw new HTTPException(404, { message: "Custom field not found" });
+ }
+
+ const next = resolveFieldUpdate(field, input);
+
+ if (
+ isChoiceType(field.type) &&
+ isChoiceType(next.type) &&
+ (next.removedOptions.length > 0 || next.type !== field.type)
+ ) {
+ const rows = await tx
+ .selectDistinct({ value: customFieldValueTable.value })
+ .from(customFieldValueTable)
+ .where(eq(customFieldValueTable.fieldId, id));
+
+ const changes = planChoiceValueChanges({
+ values: rows.map((row) => row.value),
+ from: field.type,
+ to: next.type,
+ removedOptions: next.removedOptions,
+ });
+
+ if (changes.length > 0) {
+ const cases = sql.join(
+ changes.map((change) => sql`when ${change.from} then ${change.to}`),
+ sql` `,
+ );
+ await tx
+ .update(customFieldValueTable)
+ .set({ value: sql`case ${customFieldValueTable.value} ${cases} end` })
+ .where(
+ and(
+ eq(customFieldValueTable.fieldId, id),
+ inArray(
+ customFieldValueTable.value,
+ changes.map((change) => change.from),
+ ),
+ ),
+ );
+ }
+ }
+
+ const [updated] = await tx
+ .update(customFieldDefinitionTable)
+ .set({
+ name: next.name,
+ type: next.type,
+ required: next.required,
+ defaultValue: next.defaultValue,
+ options: next.options,
+ })
+ .where(eq(customFieldDefinitionTable.id, id))
+ .returning();
+
+ if (!updated) {
+ throw new HTTPException(404, { message: "Custom field not found" });
+ }
+
+ if (next.required && !field.required && next.defaultValue !== null) {
+ await fillEmptyValues(tx, {
+ projectId: field.projectId,
+ fieldId: id,
+ value: next.defaultValue,
+ });
+ }
+
+ return updated;
+ });
+}
+
+export default updateCustomField;
diff --git a/apps/api/src/custom-field/fill-default-values.ts b/apps/api/src/custom-field/fill-default-values.ts
new file mode 100644
index 000000000..749dac423
--- /dev/null
+++ b/apps/api/src/custom-field/fill-default-values.ts
@@ -0,0 +1,52 @@
+import { and, eq, isNull, or, sql } from "drizzle-orm";
+import type db from "../database";
+import { customFieldValueTable, taskTable } from "../database/schema";
+
+type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+type FillInput = {
+ projectId: string;
+ fieldId: string;
+ value: string;
+};
+
+const CHUNK_SIZE = 500;
+
+export async function insertMissingValues(
+ tx: Transaction,
+ { projectId, fieldId, value }: FillInput,
+) {
+ const tasks = await tx
+ .select({ id: taskTable.id })
+ .from(taskTable)
+ .where(eq(taskTable.projectId, projectId));
+
+ for (let i = 0; i < tasks.length; i += CHUNK_SIZE) {
+ await tx
+ .insert(customFieldValueTable)
+ .values(
+ tasks.slice(i, i + CHUNK_SIZE).map((task) => ({
+ taskId: task.id,
+ fieldId,
+ value,
+ })),
+ )
+ .onConflictDoNothing();
+ }
+}
+
+export async function fillEmptyValues(tx: Transaction, input: FillInput) {
+ await insertMissingValues(tx, input);
+ await tx
+ .update(customFieldValueTable)
+ .set({ value: input.value })
+ .where(
+ and(
+ eq(customFieldValueTable.fieldId, input.fieldId),
+ or(
+ isNull(customFieldValueTable.value),
+ sql`trim(${customFieldValueTable.value}) in ('', '[]')`,
+ ),
+ ),
+ );
+}
diff --git a/apps/api/src/custom-field/index.ts b/apps/api/src/custom-field/index.ts
index c1563da01..cd233a2cd 100644
--- a/apps/api/src/custom-field/index.ts
+++ b/apps/api/src/custom-field/index.ts
@@ -14,6 +14,7 @@ import getCustomFieldValuesByTask from "./controllers/get-custom-field-values-by
import getCustomFieldsByProject from "./controllers/get-custom-fields-by-project";
import reorderCustomFields from "./controllers/reorder-custom-field";
import setCustomFieldValue from "./controllers/set-custom-field-value";
+import updateCustomField from "./controllers/update-custom-field";
import {
customFieldDefinitionListSchema,
customFieldDefinitionSchema,
@@ -29,6 +30,7 @@ import {
reorderCustomFieldsBody,
setCustomFieldValueBody,
taskIdParam,
+ updateCustomFieldBody,
} from "./schema";
const getCustomFieldsRoute = createRoute({
@@ -231,6 +233,37 @@ const deleteCustomFieldRoute = createRoute({
},
});
+const updateCustomFieldRoute = createRoute({
+ method: "put",
+ operationId: "updateCustomField",
+ path: "/{id}",
+ tags: ["Custom Fields"],
+ summary: "Update custom field",
+ description:
+ "Update a custom field's name, required flag, default, or options. The type can't change, except between dropdown and multiselect. Options that tasks still use can't be removed or renamed; the request is rejected instead of changing task values.",
+ middleware: [
+ workspaceAccess.fromCustomField("id"),
+ requireWorkspacePermission({ project: ["update"] }),
+ ] as const,
+ request: {
+ params: customFieldIdParam,
+ body: {
+ required: true,
+ content: { "application/json": { schema: updateCustomFieldBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("The updated custom field", customFieldDefinitionSchema),
+ 400: errorResponse(
+ "Invalid body, a type change, or removing an option that tasks still use",
+ ),
+ 403: errorResponse(
+ "No access to the project, or missing project:update permission",
+ ),
+ 404: errorResponse("Custom field not found"),
+ },
+});
+
const customField = apiRouter()
.openapi(getCustomFieldsRoute, async (c) =>
c.json(await getCustomFieldsByProject(c.req.valid("param").projectId), 200),
@@ -279,6 +312,12 @@ const customField = apiRouter()
})
.openapi(deleteCustomFieldRoute, async (c) =>
c.json(await deleteCustomField(c.req.valid("param").id), 200),
+ )
+ .openapi(updateCustomFieldRoute, async (c) =>
+ c.json(
+ await updateCustomField(c.req.valid("param").id, c.req.valid("json")),
+ 200,
+ ),
);
export default customField;
diff --git a/apps/api/src/custom-field/plan-choice-value-changes.ts b/apps/api/src/custom-field/plan-choice-value-changes.ts
new file mode 100644
index 000000000..d7930d453
--- /dev/null
+++ b/apps/api/src/custom-field/plan-choice-value-changes.ts
@@ -0,0 +1,54 @@
+import { HTTPException } from "hono/http-exception";
+import {
+ type ChoiceType,
+ convertChoiceValue,
+ findUsedOptions,
+} from "./choice-options";
+
+export type ChoiceValueChange = {
+ from: string;
+ to: string;
+};
+
+type PlanInput = {
+ values: Array<string | null>;
+ from: ChoiceType;
+ to: ChoiceType;
+ removedOptions: string[];
+};
+
+function quote(options: string[]) {
+ return options.map((option) => `"${option}"`).join(", ");
+}
+
+export function planChoiceValueChanges({
+ values,
+ from,
+ to,
+ removedOptions,
+}: PlanInput): ChoiceValueChange[] {
+ const used = findUsedOptions(values, from, removedOptions);
+ if (used.length > 0) {
+ throw new HTTPException(400, {
+ message: `Can't remove ${quote(used)} because tasks still use ${used.length === 1 ? "it" : "them"}. Pick a different option on those tasks first.`,
+ });
+ }
+
+ if (from === to) return [];
+
+ const changes: ChoiceValueChange[] = [];
+ for (const value of new Set(values)) {
+ if (value === null) continue;
+
+ const converted = convertChoiceValue(value, from, to);
+ if (converted === undefined) {
+ throw new HTTPException(400, {
+ message:
+ "Some tasks have more than one option picked. Leave one option on those tasks first.",
+ });
+ }
+ if (converted !== value) changes.push({ from: value, to: converted });
+ }
+
+ return changes;
+}
diff --git a/apps/api/src/custom-field/resolve-field-update.ts b/apps/api/src/custom-field/resolve-field-update.ts
new file mode 100644
index 000000000..6ec25879b
--- /dev/null
+++ b/apps/api/src/custom-field/resolve-field-update.ts
@@ -0,0 +1,112 @@
+import { HTTPException } from "hono/http-exception";
+import { assertValidDefinition } from "./assert-valid-definition";
+import {
+ convertChoiceValue,
+ isChoiceType,
+ normalizeOptions,
+ readOptions,
+} from "./choice-options";
+
+export type CurrentCustomField = {
+ name: string;
+ type: string;
+ required: boolean;
+ defaultValue: string | null;
+ options: unknown;
+};
+
+export type CustomFieldUpdateInput = {
+ name?: string;
+ type?: string;
+ required?: boolean;
+ defaultValue?: string | null;
+ options?: string[];
+};
+
+export type ResolvedFieldUpdate = {
+ name: string;
+ type: string;
+ required: boolean;
+ defaultValue: string | null;
+ options: unknown;
+ removedOptions: string[];
+};
+
+function badRequest(message: string): never {
+ throw new HTTPException(400, { message });
+}
+
+function resolveType(field: CurrentCustomField, requested?: string) {
+ const type = requested ?? field.type;
+ if (type === field.type) return type;
+ if (isChoiceType(type) && isChoiceType(field.type)) return type;
+
+ badRequest(
+ "The type of a custom field can't change. Only dropdown and multiselect fields can switch between each other.",
+ );
+}
+
+function resolveDefault(
+ field: CurrentCustomField,
+ type: string,
+ requested: string | null | undefined,
+) {
+ if (requested !== undefined) {
+ if (requested === null || requested.trim() === "") return null;
+ return type === "date" ? requested.trim() : requested;
+ }
+
+ if (
+ field.defaultValue === null ||
+ type === field.type ||
+ !isChoiceType(type) ||
+ !isChoiceType(field.type)
+ ) {
+ return field.defaultValue;
+ }
+
+ const converted = convertChoiceValue(field.defaultValue, field.type, type);
+ if (converted === undefined) {
+ badRequest(
+ "The default has more than one option picked. Send a default with one option.",
+ );
+ }
+ return converted || null;
+}
+
+export function resolveFieldUpdate(
+ field: CurrentCustomField,
+ input: CustomFieldUpdateInput,
+): ResolvedFieldUpdate {
+ const type = resolveType(field, input.type);
+
+ const name = input.name === undefined ? field.name : input.name.trim();
+ if (!name) badRequest("Name cannot be empty");
+
+ if (input.options !== undefined && !isChoiceType(type)) {
+ badRequest("Only dropdown and multiselect fields have options");
+ }
+
+ const previousOptions = readOptions(field.options);
+ const options = isChoiceType(type)
+ ? input.options === undefined
+ ? previousOptions
+ : normalizeOptions(input.options)
+ : null;
+
+ const required = input.required ?? field.required;
+ const defaultValue = resolveDefault(field, type, input.defaultValue);
+
+ assertValidDefinition({ name, type, required, defaultValue, options });
+
+ return {
+ name,
+ type,
+ required,
+ defaultValue,
+ options: options ?? field.options,
+ removedOptions: options
+ ? previousOptions.filter((option) => !options.includes(option))
+ : [],
+ };
+}
diff --git a/apps/api/src/custom-field/schema.ts b/apps/api/src/custom-field/schema.ts
index d3ce0ca12..43d54cd44 100644
--- a/apps/api/src/custom-field/schema.ts
+++ b/apps/api/src/custom-field/schema.ts
@@ -12,22 +12,46 @@ export const customFieldIdParam = z.object({
id: z.string(),
});
+const customFieldType = z.enum([
+ "text",
+ "number",
+ "date",
+ "dropdown",
+ "boolean",
+ "multiselect",
+]);
+
export const createCustomFieldBody = z.object({
projectId: z.string(),
name: z.string(),
- type: z.enum([
- "text",
- "number",
- "date",
- "dropdown",
- "boolean",
- "multiselect",
- ]),
+ type: customFieldType,
required: z.boolean().optional().default(false),
defaultValue: z.string().optional(),
options: z.array(z.string()).optional(),
});
+export const updateCustomFieldBody = z.object({
+ name: z.string().optional().openapi({
+ description: "New name for the field. Cannot be blank.",
+ }),
+ type: customFieldType.optional().openapi({
+ description:
+ "Only `dropdown` and `multiselect` can switch between each other. Task values are converted, and switching to `dropdown` is rejected while a task has more than one option picked. Any other type change is rejected.",
+ }),
+ required: z.boolean().optional().openapi({
+ description:
+ "Whether every task must have a value. Turning it on needs a default, which fills tasks that have no value yet.",
+ }),
+ defaultValue: z.string().nullable().optional().openapi({
+ description:
+ "Value new tasks start with. Send `null` or an empty string to clear it. Multiselect defaults are a JSON array of options.",
+ }),
+ options: z.array(z.string()).optional().openapi({
+ description:
+ "The full option list for dropdown and multiselect fields, in display order. Adding and reordering options is always allowed. Removing or renaming an option that a task still uses is rejected with 400, so task values are never changed silently.",
+ }),
+});
+
export const reorderCustomFieldsBody = z.object({
fields: z.array(
z.object({
diff --git a/apps/api/src/github-integration/controllers/list-user-repositories.ts b/apps/api/src/github-integration/controllers/list-user-repositories.ts
index 35ddfca17..219694403 100644
--- a/apps/api/src/github-integration/controllers/list-user-repositories.ts
+++ b/apps/api/src/github-integration/controllers/list-user-repositories.ts
@@ -1,105 +1,214 @@
import { HTTPException } from "hono/http-exception";
import { getGithubApp } from "../../plugins/github/utils/github-app";
+import {
+ nextRepositoryPage,
+ type RepositoryPage,
+ searchRepositoryPages,
+} from "../repository-search";
import { getGithubAccount } from "./verify-repository-owner";
-export type RepositoryPage = {
- installationPage: number;
- repositoryPage: number;
-};
+export type { RepositoryPage } from "../repository-search";
+
const PAGE_SIZE = 20;
+const SEARCH_PAGE_SIZE = 100;
+const SEARCH_MAX_LIST_CALLS = 10;
+const SEARCH_MATCH_TARGET = 20;
+const PERMISSION_CHECK_CONCURRENCY = 4;
-/** One bounded page. Never return other users' repository or installation metadata. */
-async function listUserRepositories(userId: string, page: RepositoryPage) {
- const account = await getGithubAccount(userId);
- const app = getGithubApp(true);
- if (!app)
- throw new HTTPException(503, {
- message: "GitHub integration is unavailable",
+type GithubApp = NonNullable<ReturnType<typeof getGithubApp>>;
+type ListedInstallation = Awaited<
+ ReturnType<GithubApp["octokit"]["rest"]["apps"]["listInstallations"]>
+>["data"][number];
+type CandidateRepository = {
+ id: number;
+ name: string;
+ full_name: string;
+ private: boolean;
+ owner: { login: string; avatar_url: string; type: string };
+ description: string | null;
+ html_url: string;
+ updated_at?: string | null;
+};
+type PermissionLookup = (owner: string, repo: string) => Promise<string>;
+
+const request = { timeout: 10_000 };
+
+async function authorizeRepository(
+ lookup: PermissionLookup,
+ installationId: number,
+ repo: CandidateRepository,
+) {
+ try {
+ if ((await lookup(repo.owner.login, repo.name)) !== "admin") return null;
+ } catch (error) {
+ if ((error as { status?: number }).status === 404) return null;
+ throw new HTTPException(502, {
+ message: "GitHub access verification is temporarily unavailable",
});
- const request = { timeout: 10_000 };
+ }
+ return {
+ id: repo.id,
+ name: repo.name,
+ full_name: repo.full_name,
+ private: repo.private,
+ owner: {
+ login: repo.owner.login,
+ avatar_url: repo.owner.avatar_url,
+ type: repo.owner.type,
+ },
+ description: repo.description,
+ html_url: repo.html_url,
+ updated_at: repo.updated_at ?? "",
+ installation_id: installationId,
+ };
+}
+
+async function authorizeRepositories(
+ lookup: PermissionLookup,
+ installationId: number,
+ candidates: CandidateRepository[],
+) {
+ const repositories = [];
+ for (
+ let offset = 0;
+ offset < candidates.length;
+ offset += PERMISSION_CHECK_CONCURRENCY
+ ) {
+ const batch = candidates.slice(
+ offset,
+ offset + PERMISSION_CHECK_CONCURRENCY,
+ );
+ const authorized = await Promise.all(
+ batch.map((repo) => authorizeRepository(lookup, installationId, repo)),
+ );
+ repositories.push(...authorized.filter((repo) => repo !== null));
+ }
+ return repositories;
+}
+
+async function openInstallation(
+ app: GithubApp,
+ accountId: string,
+ installationPage: number,
+) {
const { data: installations } = await app.octokit.rest.apps.listInstallations(
{
per_page: 1,
- page: page.installationPage,
+ page: installationPage,
request,
},
);
- const installation = installations[0];
- if (!installation)
- return { repositories: [], installations: [], total: 0, nextPage: null };
+ const installation: ListedInstallation | undefined = installations[0];
+ if (!installation) return null;
const octokit = await app.getInstallationOctokit(installation.id);
const { data: identity } = await octokit.rest.users.getById({
- account_id: Number(account.accountId),
+ account_id: Number(accountId),
request,
});
- if (String(identity.id) !== account.accountId)
+ if (String(identity.id) !== accountId)
throw new HTTPException(403, {
message: "GitHub identity could not be verified",
});
- const { data } = await octokit.rest.apps.listReposAccessibleToInstallation({
- per_page: PAGE_SIZE,
- page: page.repositoryPage,
- request,
- });
- const repositories = [];
- // Bound concurrent requests as well as the total per page.
- for (let offset = 0; offset < data.repositories.length; offset += 4) {
- const candidates = data.repositories.slice(offset, offset + 4);
- const authorized = await Promise.all(
- candidates.map(async (repo) => {
- try {
- const { data: permission } =
- await octokit.rest.repos.getCollaboratorPermissionLevel({
- owner: repo.owner.login,
- repo: repo.name,
- username: identity.login,
- request,
- });
- if (permission.permission !== "admin") return null;
- return {
- id: repo.id,
- name: repo.name,
- full_name: repo.full_name,
- private: repo.private,
- owner: {
- login: repo.owner.login,
- avatar_url: repo.owner.avatar_url,
- type: repo.owner.type,
- },
- description: repo.description,
- html_url: repo.html_url,
- updated_at: repo.updated_at ?? "",
- installation_id: installation.id,
- };
- } catch (error) {
- if ((error as { status?: number }).status === 404) return null;
- throw new HTTPException(502, {
- message: "GitHub access verification is temporarily unavailable",
- });
- }
- }),
- );
- repositories.push(...authorized.filter((repo) => repo !== null));
+ const lookup: PermissionLookup = async (owner, repo) => {
+ const { data } = await octokit.rest.repos.getCollaboratorPermissionLevel({
+ owner,
+ repo,
+ username: identity.login,
+ request,
+ });
+ return data.permission;
+ };
+ return {
+ installation,
+ listRepositories: async (
+ repositoryPage: number,
+ perPage: number,
+ ): Promise<CandidateRepository[]> => {
+ const { data } =
+ await octokit.rest.apps.listReposAccessibleToInstallation({
+ per_page: perPage,
+ page: repositoryPage,
+ request,
+ });
+ return data.repositories;
+ },
+ authorize: (candidates: CandidateRepository[]) =>
+ authorizeRepositories(lookup, installation.id, candidates),
+ };
+}
+
+function describeInstallation(
+ installation: ListedInstallation,
+ repositories: { full_name: string }[],
+) {
+ return {
+ id: installation.id,
+ account: installation.account,
+ repositories: repositories.map((repo) => repo.full_name),
+ };
+}
+
+async function listUserRepositories(
+ userId: string,
+ page: RepositoryPage,
+ search?: string,
+) {
+ const account = await getGithubAccount(userId);
+ const app = getGithubApp(true);
+ if (!app)
+ throw new HTTPException(503, {
+ message: "GitHub integration is unavailable",
+ });
+
+ if (search) {
+ const { groups, nextPage } = await searchRepositoryPages({
+ start: page,
+ search,
+ perPage: SEARCH_PAGE_SIZE,
+ maxListCalls: SEARCH_MAX_LIST_CALLS,
+ matchTarget: SEARCH_MATCH_TARGET,
+ openInstallation: async (installationPage) => {
+ const source = await openInstallation(
+ app,
+ account.accountId,
+ installationPage,
+ );
+ if (!source) return null;
+ return {
+ installation: source.installation,
+ listRepositories: (repositoryPage) =>
+ source.listRepositories(repositoryPage, SEARCH_PAGE_SIZE),
+ authorize: source.authorize,
+ };
+ },
+ });
+ const repositories = groups.flatMap((group) => group.repositories);
+ return {
+ repositories,
+ installations: groups.map((group) =>
+ describeInstallation(group.installation, group.repositories),
+ ),
+ total: repositories.length,
+ nextPage,
+ };
}
+
+ const source = await openInstallation(
+ app,
+ account.accountId,
+ page.installationPage,
+ );
+ if (!source)
+ return { repositories: [], installations: [], total: 0, nextPage: null };
+ const fetched = await source.listRepositories(page.repositoryPage, PAGE_SIZE);
+ const repositories = await source.authorize(fetched);
return {
repositories,
installations: repositories.length
- ? [
- {
- id: installation.id,
- account: installation.account,
- repositories: repositories.map((repo) => repo.full_name),
- },
- ]
+ ? [describeInstallation(source.installation, repositories)]
: [],
total: repositories.length,
- nextPage:
- data.repositories.length === PAGE_SIZE
- ? {
- installationPage: page.installationPage,
- repositoryPage: page.repositoryPage + 1,
- }
- : { installationPage: page.installationPage + 1, repositoryPage: 1 },
+ nextPage: nextRepositoryPage(page, fetched.length, PAGE_SIZE),
};
}
export default listUserRepositories;
diff --git a/apps/api/src/github-integration/index.ts b/apps/api/src/github-integration/index.ts
index 353a36304..7068879f5 100644
--- a/apps/api/src/github-integration/index.ts
+++ b/apps/api/src/github-integration/index.ts
@@ -71,7 +71,7 @@ const listRepositoriesRoute = createRoute({
tags: ["GitHub"],
summary: "List GitHub repositories",
description:
- "List the repositories reachable through the installed GitHub App, for picking one to link.",
+ "List the repositories reachable through the installed GitHub App that the caller administers, for picking one to link. Without `search`, each request reads one page of one installation. With `search`, the server filters by name and description before checking access and keeps scanning later pages and installations within a fixed budget. Follow `nextPage` until it is null to see every repository.",
middleware: [requireUserSession, ...manageAccess],
request: { params: projectIdParam, query: repositoryPageQuery },
responses: {
@@ -272,9 +272,11 @@ const githubIntegration = apiRouter<BaseVariables & { workspaceId: string }>()
);
})
.openapi(listRepositoriesRoute, async (c) => {
+ const { search, ...page } = c.req.valid("query");
const repositories = await listUserRepositories(
c.get("userId"),
- c.req.valid("query"),
+ page,
+ search || undefined,
);
return c.json(repositories, 200);
})
diff --git a/apps/api/src/github-integration/repository-search.test.ts b/apps/api/src/github-integration/repository-search.test.ts
new file mode 100644
index 000000000..f45b357c8
--- /dev/null
+++ b/apps/api/src/github-integration/repository-search.test.ts
@@ -0,0 +1,203 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+import {
+ matchesRepositorySearch,
+ nextRepositoryPage,
+ type RepositorySource,
+ searchRepositoryPages,
+} from "./repository-search";
+
+type Repo = { id: number; full_name: string; description: string | null };
+
+function repo(id: number, name: string, description: string | null = null) {
+ return { id, full_name: `acme/${name}`, description };
+}
+
+function filler(start: number, count: number) {
+ return Array.from({ length: count }, (_, index) =>
+ repo(start + index, `filler-${start + index}`),
+ );
+}
+
+function installations(pages: Repo[][][]) {
+ const authorize = vi.fn(async (candidates: Repo[]) => candidates);
+ const listRepositories = vi.fn();
+ const openInstallation = vi.fn(
+ async (
+ installationPage: number,
+ ): Promise<RepositorySource<Repo, Repo, number> | null> => {
+ const installation = pages[installationPage - 1];
+ if (!installation) return null;
+ return {
+ installation: installationPage,
+ listRepositories: async (repositoryPage) => {
+ listRepositories(installationPage, repositoryPage);
+ return installation[repositoryPage - 1] ?? [];
+ },
+ authorize,
+ };
+ },
+ );
+ return { authorize, listRepositories, openInstallation };
+}
+
+describe("matchesRepositorySearch", () => {
+ it("matches the full name or description without regard to case", () => {
+ expect(matchesRepositorySearch(repo(1, "Website"), "WEB")).toBe(true);
+ expect(
+ matchesRepositorySearch(repo(2, "api", "Marketing site"), "market"),
+ ).toBe(true);
+ expect(matchesRepositorySearch(repo(3, "api", null), "web")).toBe(false);
+ });
+});
+
+describe("nextRepositoryPage", () => {
+ it("stays on the installation while pages are full", () => {
+ expect(
+ nextRepositoryPage({ installationPage: 2, repositoryPage: 3 }, 100, 100),
+ ).toEqual({ installationPage: 2, repositoryPage: 4 });
+ expect(
+ nextRepositoryPage({ installationPage: 2, repositoryPage: 3 }, 40, 100),
+ ).toEqual({ installationPage: 3, repositoryPage: 1 });
+ });
+});
+
+describe("searchRepositoryPages", () => {
+ it("filters before authorizing and scans later pages and installations", async () => {
+ const source = installations([
+ [
+ [...filler(1, 98), repo(200, "web-app"), repo(201, "docs", "Website")],
+ [repo(202, "api")],
+ ],
+ [[repo(300, "web-experiments"), repo(301, "infra")]],
+ ]);
+
+ const result = await searchRepositoryPages({
+ start: { installationPage: 1, repositoryPage: 1 },
+ search: "web",
+ perPage: 100,
+ maxListCalls: 10,
+ matchTarget: 20,
+ openInstallation: source.openInstallation,
+ });
+
+ expect(source.authorize.mock.calls).toEqual([
+ [[repo(200, "web-app"), repo(201, "docs", "Website")]],
+ [[repo(300, "web-experiments")]],
+ ]);
+ expect(result.groups).toEqual([
+ {
+ installation: 1,
+ repositories: [repo(200, "web-app"), repo(201, "docs", "Website")],
+ },
+ { installation: 2, repositories: [repo(300, "web-experiments")] },
+ ]);
+ expect(result.nextPage).toBeNull();
+ });
+
+ it("drops candidates the caller cannot administer", async () => {
+ const source = installations([[[repo(1, "web"), repo(2, "web-private")]]]);
+ source.authorize.mockImplementation(async (candidates) =>
+ candidates.filter((candidate) => candidate.id === 1),
+ );
+
+ const result = await searchRepositoryPages({
+ start: { installationPage: 1, repositoryPage: 1 },
+ search: "web",
+ perPage: 100,
+ maxListCalls: 10,
+ matchTarget: 20,
+ openInstallation: source.openInstallation,
+ });
+
+ expect(result.groups).toEqual([
+ { installation: 1, repositories: [repo(1, "web")] },
+ ]);
+ });
+
+ it("skips authorization when a page has no matches", async () => {
+ const source = installations([[[repo(1, "api")]]]);
+
+ const result = await searchRepositoryPages({
+ start: { installationPage: 1, repositoryPage: 1 },
+ search: "web",
+ perPage: 100,
+ maxListCalls: 10,
+ matchTarget: 20,
+ openInstallation: source.openInstallation,
+ });
+
+ expect(source.authorize).not.toHaveBeenCalled();
+ expect(result).toEqual({ groups: [], nextPage: null });
+ });
+
+ it("stops at the list budget and returns a cursor to resume from", async () => {
+ const pages = Array.from({ length: 5 }, (_, index) =>
+ filler(index * 100 + 1, 100),
+ );
+ const source = installations([pages]);
+
+ const result = await searchRepositoryPages({
+ start: { installationPage: 1, repositoryPage: 2 },
+ search: "web",
+ perPage: 100,
+ maxListCalls: 3,
+ matchTarget: 20,
+ openInstallation: source.openInstallation,
+ });
+
+ expect(source.listRepositories.mock.calls).toEqual([
+ [1, 2],
+ [1, 3],
+ [1, 4],
+ ]);
+ expect(result).toEqual({
+ groups: [],
+ nextPage: { installationPage: 1, repositoryPage: 5 },
+ });
+ });
+
+ it("returns early once enough matches are found", async () => {
+ const source = installations([
+ [
+ [
+ ...filler(1, 90),
+ ...Array.from({ length: 10 }, (_, i) => repo(500 + i, `web-${i}`)),
+ ],
+ filler(101, 100),
+ ],
+ ]);
+
+ const result = await searchRepositoryPages({
+ start: { installationPage: 1, repositoryPage: 1 },
+ search: "web",
+ perPage: 100,
+ maxListCalls: 10,
+ matchTarget: 10,
+ openInstallation: source.openInstallation,
+ });
+
+ expect(source.listRepositories).toHaveBeenCalledTimes(1);
+ expect(result.groups[0]?.repositories).toHaveLength(10);
+ expect(result.nextPage).toEqual({ installationPage: 1, repositoryPage: 2 });
+ });
+
+ it("never returns the same repository twice", async () => {
+ const source = installations([
+ [[repo(1, "web")]],
+ [[repo(1, "web"), repo(2, "web-two")]],
+ ]);
+
+ const result = await searchRepositoryPages({
+ start: { installationPage: 1, repositoryPage: 1 },
+ search: "web",
+ perPage: 100,
+ maxListCalls: 10,
+ matchTarget: 20,
+ openInstallation: source.openInstallation,
+ });
+
+ expect(
+ result.groups.flatMap((group) => group.repositories.map((r) => r.id)),
+ ).toEqual([1, 2]);
+ });
+});
diff --git a/apps/api/src/github-integration/repository-search.ts b/apps/api/src/github-integration/repository-search.ts
new file mode 100644
index 000000000..20f2e3f10
--- /dev/null
+++ b/apps/api/src/github-integration/repository-search.ts
@@ -0,0 +1,114 @@
+export type RepositoryPage = {
+ installationPage: number;
+ repositoryPage: number;
+};
+
+type SearchableRepository = {
+ id: number;
+ full_name: string;
+ description: string | null;
+};
+
+export type RepositorySource<
+ Candidate extends SearchableRepository,
+ Authorized extends { id: number },
+ Installation,
+> = {
+ installation: Installation;
+ listRepositories: (repositoryPage: number) => Promise<Candidate[]>;
+ authorize: (candidates: Candidate[]) => Promise<Authorized[]>;
+};
+
+export type RepositorySearchGroup<Authorized, Installation> = {
+ installation: Installation;
+ repositories: Authorized[];
+};
+
+export function matchesRepositorySearch(
+ repository: Pick<SearchableRepository, "full_name" | "description">,
+ search: string,
+) {
+ const needle = search.toLowerCase();
+ return (
+ repository.full_name.toLowerCase().includes(needle) ||
+ (repository.description?.toLowerCase().includes(needle) ?? false)
+ );
+}
+
+export function nextRepositoryPage(
+ page: RepositoryPage,
+ fetched: number,
+ perPage: number,
+): RepositoryPage {
+ return fetched === perPage
+ ? {
+ installationPage: page.installationPage,
+ repositoryPage: page.repositoryPage + 1,
+ }
+ : { installationPage: page.installationPage + 1, repositoryPage: 1 };
+}
+
+export async function searchRepositoryPages<
+ Candidate extends SearchableRepository,
+ Authorized extends { id: number },
+ Installation,
+>({
+ start,
+ search,
+ perPage,
+ maxListCalls,
+ matchTarget,
+ openInstallation,
+}: {
+ start: RepositoryPage;
+ search: string;
+ perPage: number;
+ maxListCalls: number;
+ matchTarget: number;
+ openInstallation: (
+ installationPage: number,
+ ) => Promise<RepositorySource<Candidate, Authorized, Installation> | null>;
+}): Promise<{
+ groups: RepositorySearchGroup<Authorized, Installation>[];
+ nextPage: RepositoryPage | null;
+}> {
+ const groups: RepositorySearchGroup<Authorized, Installation>[] = [];
+ const seen = new Set<number>();
+ let page = start;
+ let listCalls = 0;
+ let matched = 0;
+
+ for (;;) {
+ const source = await openInstallation(page.installationPage);
+ if (!source) return { groups, nextPage: null };
+
+ const repositories: Authorized[] = [];
+ let installationDone = false;
+ let budgetSpent = false;
+
+ while (!installationDone && !budgetSpent) {
+ const fetched = await source.listRepositories(page.repositoryPage);
+ listCalls += 1;
+ const candidates = fetched.filter(
+ (repository) =>
+ !seen.has(repository.id) &&
+ matchesRepositorySearch(repository, search),
+ );
+ const authorized = candidates.length
+ ? await source.authorize(candidates)
+ : [];
+ for (const repository of authorized) {
+ seen.add(repository.id);
+ repositories.push(repository);
+ }
+ matched += authorized.length;
+ installationDone = fetched.length < perPage;
+ page = nextRepositoryPage(page, fetched.length, perPage);
+ budgetSpent = listCalls >= maxListCalls || matched >= matchTarget;
+ }
+
+ if (repositories.length)
+ groups.push({ installation: source.installation, repositories });
+ if (budgetSpent) return { groups, nextPage: page };
+ }
+}
diff --git a/apps/api/src/github-integration/response.ts b/apps/api/src/github-integration/response.ts
index 88aa57af6..9df95a217 100644
--- a/apps/api/src/github-integration/response.ts
+++ b/apps/api/src/github-integration/response.ts
@@ -97,13 +97,17 @@ export const githubRepositoryListSchema = z
.object({
repositories: z.array(githubRepositorySchema).openapi({
description:
- "Deduplicated across installations, most recently updated first.",
+ "Repositories the caller administers, deduplicated within the response.",
}),
installations: z.array(githubInstallationSchema),
total: z.number(),
nextPage: z
.object({ installationPage: z.number(), repositoryPage: z.number() })
- .nullable(),
+ .nullable()
+ .openapi({
+ description:
+ "Where to continue listing, or null when every installation has been read.",
+ }),
})
.openapi("GitHubRepositoryList");
diff --git a/apps/api/src/github-integration/schema.ts b/apps/api/src/github-integration/schema.ts
index 5b494720d..0c7163b14 100644
--- a/apps/api/src/github-integration/schema.ts
+++ b/apps/api/src/github-integration/schema.ts
@@ -28,6 +28,10 @@ export const repositoryPageQuery = z.object({
.regex(/^[1-9][0-9]{0,5}$/)
.default("1")
.transform(Number),
+ search: z.string().trim().max(100).optional().openapi({
+ description:
+ "Case-insensitive match on the repository full name or description. When set, one request scans up to 10 pages of 100 repositories across installations and returns every match it finds, with `nextPage` set to resume the scan.",
+ }),
});
export const importGitHubBody = z.object({
diff --git a/apps/api/src/storage/s3.ts b/apps/api/src/storage/s3.ts
index 7cd02558c..6b89819ab 100644
--- a/apps/api/src/storage/s3.ts
+++ b/apps/api/src/storage/s3.ts
@@ -484,6 +484,15 @@ export function assertStorageConfigured() {
return getStorageConfig();
}
+export function isStorageConfigured() {
+ try {
+ getStorageConfig();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
export function assertTaskImageKeyMatchesContext(
key: string,
context: Omit<TaskImageUploadContext, "filename" | "contentType">,
diff --git a/apps/api/src/utils/get-settings.ts b/apps/api/src/utils/get-settings.ts
index a6535fc77..df4abd873 100644
--- a/apps/api/src/utils/get-settings.ts
+++ b/apps/api/src/utils/get-settings.ts
@@ -1,6 +1,7 @@
import { isSmtpConfigured } from "@kaneo/email";
import { config } from "dotenv-mono";
import { isBillingEnabled } from "../billing/config";
+import { isStorageConfigured } from "../storage/s3";
import { resolveFileSecret } from "./file-secret";
import { isGithubSsoConfigured } from "./github-sso-env";
import { isCloud } from "./is-cloud";
@@ -17,6 +18,7 @@ function getSettings() {
disableWorkspaceCreation: process.env.DISABLE_WORKSPACE_CREATION === "true",
isDemoMode: process.env.DEMO_MODE === "true",
hasSmtp: isSmtpConfigured(),
+ hasImageUploads: isStorageConfigured(),
hasGithubSignIn: isGithubSsoConfigured(),
hasGoogleSignIn:
Boolean(process.env.GOOGLE_CLIENT_ID) &&
diff --git a/apps/docs/openapi.json b/apps/docs/openapi.json
index 6b49a240e..101b9d675 100644
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@ -568,6 +568,10 @@
"hasSmtp": {
"type": "boolean"
},
+ "hasImageUploads": {
+ "type": "boolean",
+ "description": "Whether S3-compatible storage is configured, so task images and board backgrounds can be uploaded."
+ },
"hasGithubSignIn": {
"type": "boolean"
},
@@ -614,6 +618,7 @@
"disableWorkspaceCreation",
"isDemoMode",
"hasSmtp",
+ "hasImageUploads",
"hasGithubSignIn",
"hasGoogleSignIn",
"hasDiscordSignIn",
@@ -2718,7 +2723,7 @@
"items": {
"$ref": "#/components/schemas/GitHubRepository"
},
- "description": "Deduplicated across installations, most recently updated first."
+ "description": "Repositories the caller administers, deduplicated within the response."
},
"installations": {
"type": "array",
@@ -2745,7 +2750,8 @@
"required": [
"installationPage",
"repositoryPage"
- ]
+ ],
+ "description": "Where to continue listing, or null when every installation has been read."
}
},
"required": [
@@ -16912,7 +16918,7 @@
"GitHub"
],
"summary": "List GitHub repositories",
- "description": "List the repositories reachable through the installed GitHub App, for picking one to link.",
+ "description": "List the repositories reachable through the installed GitHub App that the caller administers, for picking one to link. Without `search`, each request reads one page of one installation. With `search`, the server filters by name and description before checking access and keeps scanning later pages and installations within a fixed budget. Follow `nextPage` until it is null to see every repository.",
"parameters": [
{
"schema": {
@@ -16941,6 +16947,17 @@
"required": false,
"name": "repositoryPage",
"in": "query"
+ },
+ {
+ "schema": {
+ "type": "string",
+ "maxLength": 100,
+ "description": "Case-insensitive match on the repository full name or description. When set, one request scans up to 10 pages of 100 repositories across installations and returns every match it finds, with `nextPage` set to resume the scan."
+ },
+ "required": false,
+ "description": "Case-insensitive match on the repository full name or description. When set, one request scans up to 10 pages of 100 repositories across installations and returns every match it finds, with `nextPage` set to resume the scan.",
+ "name": "search",
+ "in": "query"
}
],
"responses": {
@@ -22688,6 +22705,125 @@
"$ref": "#/components/responses/ApiKeyRateLimited"
}
}
+ },
+ "put": {
+ "operationId": "updateCustomField",
+ "tags": [
+ "Custom Fields"
+ ],
+ "summary": "Update custom field",
+ "description": "Update a custom field's name, required flag, default, or options. The type can't change, except between dropdown and multiselect. Options that tasks still use can't be removed or renamed; the request is rejected instead of changing task values.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "id",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string",
+ "description": "New name for the field. Cannot be blank."
+ },
+ "type": {
+ "type": "string",
+ "enum": [
+ "text",
+ "number",
+ "date",
+ "dropdown",
+ "boolean",
+ "multiselect"
+ ],
+ "description": "Only `dropdown` and `multiselect` can switch between each other. Task values are converted, and switching to `dropdown` is rejected while a task has more than one option picked. Any other type change is rejected."
+ },
+ "required": {
+ "type": "boolean",
+ "description": "Whether every task must have a value. Turning it on needs a default, which fills tasks that have no value yet."
+ },
+ "defaultValue": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Value new tasks start with. Send `null` or an empty string to clear it. Multiselect defaults are a JSON array of options."
+ },
+ "options": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "The full option list for dropdown and multiselect fields, in display order. Adding and reordering options is always allowed. Removing or renaming an option that a task still uses is rejected with 400, so task values are never changed silently."
+ }
+ }
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "The updated custom field",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CustomFieldDefinition"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid body, a type change, or removing an option that tasks still use",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "No access to the project, or missing project:update permission",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Custom field not found",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ApiError"
+ }
+ }
+ }
+ },
+ "429": {
+ "$ref": "#/components/responses/ApiKeyRateLimited"
+ }
+ }
}
},
"/import/projects": {
diff --git a/tests/api-integration/config.test.ts b/tests/api-integration/config.test.ts
index cbc55b8c9..3a880ba74 100644
--- a/tests/api-integration/config.test.ts
+++ b/tests/api-integration/config.test.ts
@@ -35,6 +35,7 @@ describe("API integration: config", () => {
expect(payload).toSatisfy((value: Record<string, unknown>) =>
[
"hasSmtp",
+ "hasImageUploads",
"hasGithubSignIn",
"hasGoogleSignIn",
"hasDiscordSignIn",
@@ -43,6 +44,20 @@ describe("API integration: config", () => {
);
});
+ it.each([
+ [{ S3_ENDPOINT: "https://s3.example.com", S3_BUCKET: "kaneo" }, true],
+ [{ S3_ENDPOINT: "", S3_BUCKET: "" }, false],
+ ])(
+ "reports image uploads from the storage settings %o",
+ async (storage, expected) => {
+ for (const [key, value] of Object.entries(storage)) {
+ vi.stubEnv(key, value);
+ }
+ const response = await createApp().app.request("/api/config");
+ expect(await response.json()).toHaveProperty("hasImageUploads", expected);
+ },
+ );
+
it("returns the trimmed custom OAuth name when one is set", async () => {
vi.stubEnv("CUSTOM_OAUTH_NAME", " Authentik ");
const response = await createApp().app.request("/api/config");
diff --git a/tests/api-integration/custom-field-update.test.ts b/tests/api-integration/custom-field-update.test.ts
new file mode 100644
index 000000000..0339c685e
--- /dev/null
+++ b/tests/api-integration/custom-field-update.test.ts
@@ -0,0 +1,258 @@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+
+beforeEach(resetTestDatabase);
+
+type FieldSeed = Partial<
+ typeof schema.customFieldDefinitionTable.$inferInsert
+> & { type: string };
+
+async function fixture({
+ role = "admin",
+ field: fieldSeed,
+ values = [],
+}: {
+ role?: string;
+ field: FieldSeed;
+ values?: Array<string | null>;
+}) {
+ const member = await createWorkspaceMember({ role });
+ const { project, columns } = await createProjectFixture({
+ workspaceId: member.workspace.id,
+ });
+ const [field] = await db
+ .insert(schema.customFieldDefinitionTable)
+ .values({
+ projectId: project.id,
+ name: "Size",
+ required: false,
+ position: 0,
+ ...fieldSeed,
+ })
+ .returning();
+
+ const tasks = [];
+ for (const [index, value] of values.entries()) {
+ const [task] = await db
+ .insert(schema.taskTable)
+ .values({
+ projectId: project.id,
+ title: `Task ${index + 1}`,
+ number: index + 1,
+ status: "to-do",
+ columnId: columns.todo.id,
+ })
+ .returning();
+ tasks.push(task);
+ if (value !== null) {
+ await db
+ .insert(schema.customFieldValueTable)
+ .values({ taskId: task.id, fieldId: field.id, value });
+ }
+ }
+
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const update = (body: Record<string, unknown>) =>
+ app.request(`/api/custom-field/${field.id}`, {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+ return { member, project, field, tasks, app, update };
+}
+
+async function readField(id: string) {
+ const [field] = await db
+ .select()
+ .from(schema.customFieldDefinitionTable)
+ .where(eq(schema.customFieldDefinitionTable.id, id));
+ return field;
+}
+
+async function readValues(fieldId: string) {
+ const rows = await db
+ .select({
+ taskId: schema.customFieldValueTable.taskId,
+ value: schema.customFieldValueTable.value,
+ })
+ .from(schema.customFieldValueTable)
+ .where(eq(schema.customFieldValueTable.fieldId, fieldId));
+ return new Map(rows.map((row) => [row.taskId, row.value]));
+}
+
+describe("PUT /custom-field/{id}", () => {
+ it("updates the name, options, and default", async () => {
+ const { field, update } = await fixture({
+ field: {
+ type: "dropdown",
+ options: ["Small", "Medium"],
+ defaultValue: "Small",
+ },
+ });
+
+ const response = await update({
+ name: " T-shirt size ",
+ options: ["Large", "Medium", "Small", "Large"],
+ defaultValue: "Medium",
+ });
+
+ expect(response.status, await response.clone().text()).toBe(200);
+ expect(await response.json()).toMatchObject({
+ id: field.id,
+ name: "T-shirt size",
+ type: "dropdown",
+ options: ["Large", "Medium", "Small"],
+ defaultValue: "Medium",
+ });
+ expect(await readField(field.id)).toMatchObject({
+ name: "T-shirt size",
+ options: ["Large", "Medium", "Small"],
+ defaultValue: "Medium",
+ });
+ });
+
+ it("fills tasks without a value when a field becomes required", async () => {
+ const { field, tasks, update } = await fixture({
+ field: { type: "text" },
+ values: ["Acme", null, ""],
+ });
+
+ const response = await update({ required: true, defaultValue: "Internal" });
+
+ expect(response.status, await response.clone().text()).toBe(200);
+ const values = await readValues(field.id);
+ expect(values.get(tasks[0].id)).toBe("Acme");
+ expect(values.get(tasks[1].id)).toBe("Internal");
+ expect(values.get(tasks[2].id)).toBe("Internal");
+ });
+
+ it("rejects making a field required without a default", async () => {
+ const { field, update } = await fixture({ field: { type: "text" } });
+
+ const response = await update({ required: true });
+
+ expect(response.status).toBe(400);
+ expect((await response.json()).message).toContain(
+ "Required fields must have a default value",
+ );
+ expect((await readField(field.id)).required).toBe(false);
+ });
+
+ it("denies members without project:update", async () => {
+ const { field, update } = await fixture({
+ role: "member",
+ field: { type: "text" },
+ });
+
+ const response = await update({ name: "Renamed" });
+
+ expect(response.status).toBe(403);
+ expect((await readField(field.id)).name).toBe("Size");
+ });
+
+ it("hides fields in other workspaces", async () => {
+ const { field } = await fixture({ field: { type: "text" } });
+ const outsider = await createWorkspaceMember({ role: "admin" });
+ mockAuthenticatedSession(outsider.user);
+ const { app } = createApp();
+
+ const response = await app.request(`/api/custom-field/${field.id}`, {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ name: "Renamed" }),
+ });
+
+ expect(response.status).toBe(404);
+ expect((await readField(field.id)).name).toBe("Size");
+ });
+
+ it("rejects a type change", async () => {
+ const { field, update } = await fixture({ field: { type: "text" } });
+
+ const response = await update({ type: "number" });
+
+ expect(response.status).toBe(400);
+ expect((await response.json()).message).toContain("can't change");
+ expect((await readField(field.id)).type).toBe("text");
+ });
+
+ it("rejects removing an option that a task uses and keeps its value", async () => {
+ const { field, tasks, update } = await fixture({
+ field: { type: "dropdown", options: ["Small", "Medium", "Large"] },
+ values: ["Small"],
+ });
+
+ const response = await update({ options: ["Smol", "Medium", "Large"] });
+
+ expect(response.status).toBe(400);
+ expect((await response.json()).message).toContain(
+ 'Can\'t remove "Small" because tasks still use it',
+ );
+ expect((await readField(field.id)).options).toEqual([
+ "Small",
+ "Medium",
+ "Large",
+ ]);
+ expect((await readValues(field.id)).get(tasks[0].id)).toBe("Small");
+ });
+
+ it("allows removing options no task uses", async () => {
+ const { field, update } = await fixture({
+ field: { type: "multiselect", options: ["iOS", "Android", "Web"] },
+ values: ['["iOS","Web"]'],
+ });
+
+ const response = await update({ options: ["Web", "iOS"] });
+
+ expect(response.status, await response.clone().text()).toBe(200);
+ expect((await readField(field.id)).options).toEqual(["Web", "iOS"]);
+ });
+
+ it("converts task values when a dropdown starts allowing several", async () => {
+ const { field, tasks, update } = await fixture({
+ field: {
+ type: "dropdown",
+ options: ["Small", "Large"],
+ defaultValue: "Small",
+ },
+ values: ["Small", "Large", ""],
+ });
+
+ const response = await update({ type: "multiselect" });
+
+ expect(response.status, await response.clone().text()).toBe(200);
+ expect(await readField(field.id)).toMatchObject({
+ type: "multiselect",
+ defaultValue: '["Small"]',
+ });
+ const values = await readValues(field.id);
+ expect(values.get(tasks[0].id)).toBe('["Small"]');
+ expect(values.get(tasks[1].id)).toBe('["Large"]');
+ expect(values.get(tasks[2].id)).toBe("");
+ });
+
+ it("refuses to stop allowing several while a task has two picks", async () => {
+ const { field, tasks, update } = await fixture({
+ field: { type: "multiselect", options: ["iOS", "Web"] },
+ values: ['["iOS","Web"]'],
+ });
+
+ const response = await update({ type: "dropdown" });
+
+ expect(response.status).toBe(400);
+ expect((await response.json()).message).toContain("more than one option");
+ expect((await readField(field.id)).type).toBe("multiselect");
+ expect((await readValues(field.id)).get(tasks[0].id)).toBe('["iOS","Web"]');
+ });
+});
diff --git a/tests/api/custom-field/choice-options.test.ts b/tests/api/custom-field/choice-options.test.ts
new file mode 100644
index 000000000..5685dcf54
--- /dev/null
+++ b/tests/api/custom-field/choice-options.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ convertChoiceValue,
+ findUsedOptions,
+ normalizeOptions,
+ parseChoiceValue,
+ readOptions,
+} from "../../../apps/api/src/custom-field/choice-options";
+
+describe("choice options", () => {
+ it("reads only string options", () => {
+ expect(readOptions(["a", 1, "b"])).toEqual(["a", "b"]);
+ expect(readOptions(null)).toEqual([]);
+ });
+
+ it("trims, drops blanks, and removes duplicates", () => {
+ expect(normalizeOptions([" Small", "Medium", "", "Small "])).toEqual([
+ "Small",
+ "Medium",
+ ]);
+ });
+
+ it("parses dropdown and multiselect values", () => {
+ expect(parseChoiceValue(" Small ", "dropdown")).toEqual(["Small"]);
+ expect(parseChoiceValue("", "dropdown")).toEqual([]);
+ expect(parseChoiceValue('["iOS","Web"]', "multiselect")).toEqual([
+ "iOS",
+ "Web",
+ ]);
+ expect(parseChoiceValue("not json", "multiselect")).toEqual([]);
+ expect(parseChoiceValue(null, "multiselect")).toEqual([]);
+ });
+
+ it("converts dropdown values to multiselect and back", () => {
+ expect(convertChoiceValue("Small", "dropdown", "multiselect")).toBe(
+ '["Small"]',
+ );
+ expect(convertChoiceValue("", "dropdown", "multiselect")).toBe("");
+ expect(convertChoiceValue('["Small"]', "multiselect", "dropdown")).toBe(
+ "Small",
+ );
+ expect(convertChoiceValue("[]", "multiselect", "dropdown")).toBe("");
+ });
+
+ it("refuses to squeeze several picks into a dropdown", () => {
+ expect(
+ convertChoiceValue('["iOS","Web"]', "multiselect", "dropdown"),
+ ).toBeUndefined();
+ });
+
+ it("finds which candidate options tasks still use", () => {
+ expect(
+ findUsedOptions(["Small", null, ""], "dropdown", ["Small", "Large"]),
+ ).toEqual(["Small"]);
+ expect(
+ findUsedOptions(['["iOS"]', '["Web","iOS"]'], "multiselect", [
+ "Android",
+ "Web",
+ ]),
+ ).toEqual(["Web"]);
+ });
+});
diff --git a/tests/api/custom-field/plan-choice-value-changes.test.ts b/tests/api/custom-field/plan-choice-value-changes.test.ts
new file mode 100644
index 000000000..c8e3abffe
--- /dev/null
+++ b/tests/api/custom-field/plan-choice-value-changes.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vite-plus/test";
+import { planChoiceValueChanges } from "../../../apps/api/src/custom-field/plan-choice-value-changes";
+
+describe("planChoiceValueChanges", () => {
+ it("allows removing options no task uses", () => {
+ expect(
+ planChoiceValueChanges({
+ values: ["Small", null],
+ from: "dropdown",
+ to: "dropdown",
+ removedOptions: ["Large"],
+ }),
+ ).toEqual([]);
+ });
+
+ it("rejects removing an option a task uses", () => {
+ expect(() =>
+ planChoiceValueChanges({
+ values: ["Small"],
+ from: "dropdown",
+ to: "dropdown",
+ removedOptions: ["Small"],
+ }),
+ ).toThrow('Can\'t remove "Small" because tasks still use it.');
+ });
+
+ it("converts each distinct value once when allowing several", () => {
+ expect(
+ planChoiceValueChanges({
+ values: ["Small", "Small", "", null],
+ from: "dropdown",
+ to: "multiselect",
+ removedOptions: [],
+ }),
+ ).toEqual([{ from: "Small", to: '["Small"]' }]);
+ });
+
+ it("rejects turning off several picks while a task has more than one", () => {
+ expect(() =>
+ planChoiceValueChanges({
+ values: ['["iOS"]', '["iOS","Web"]'],
+ from: "multiselect",
+ to: "dropdown",
+ removedOptions: [],
+ }),
+ ).toThrow("more than one option");
+ });
+});
diff --git a/tests/api/custom-field/resolve-field-update.test.ts b/tests/api/custom-field/resolve-field-update.test.ts
new file mode 100644
index 000000000..b463728dd
--- /dev/null
+++ b/tests/api/custom-field/resolve-field-update.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it } from "vite-plus/test";
+import {
+ type CurrentCustomField,
+ resolveFieldUpdate,
+} from "../../../apps/api/src/custom-field/resolve-field-update";
+
+const dropdown: CurrentCustomField = {
+ name: "Size",
+ type: "dropdown",
+ required: false,
+ defaultValue: "Medium",
+ options: ["Small", "Medium", "Large"],
+};
+
+describe("resolveFieldUpdate", () => {
+ it("keeps what the request leaves out", () => {
+ expect(resolveFieldUpdate(dropdown, { name: " T-shirt size " })).toEqual({
+ ...dropdown,
+ name: "T-shirt size",
+ removedOptions: [],
+ });
+ });
+
+ it("rejects type changes other than dropdown and multiselect", () => {
+ expect(() =>
+ resolveFieldUpdate(
+ { ...dropdown, type: "text", options: null, defaultValue: null },
+ { type: "number" },
+ ),
+ ).toThrow("can't change");
+ });
+
+ it("rejects a blank name", () => {
+ expect(() => resolveFieldUpdate(dropdown, { name: " " })).toThrow(
+ "Name cannot be empty",
+ );
+ });
+
+ it("reports removed options and checks the default against new options", () => {
+ expect(
+ resolveFieldUpdate(dropdown, { options: ["Medium", "XL", "Medium"] }),
+ ).toMatchObject({
+ options: ["Medium", "XL"],
+ removedOptions: ["Small", "Large"],
+ });
+ expect(() =>
+ resolveFieldUpdate(dropdown, { options: ["Small", "Large"] }),
+ ).toThrow("Default value must be one of the dropdown options");
+ });
+
+ it("converts the default when switching to multiselect", () => {
+ expect(resolveFieldUpdate(dropdown, { type: "multiselect" })).toMatchObject(
+ { type: "multiselect", defaultValue: '["Medium"]' },
+ );
+ });
+
+ it("clears the default with null and requires one for required fields", () => {
+ expect(
+ resolveFieldUpdate(dropdown, { defaultValue: null }).defaultValue,
+ ).toBeNull();
+ expect(() =>
+ resolveFieldUpdate(dropdown, { defaultValue: "", required: true }),
+ ).toThrow("Required fields must have a default value");
+ });
+
+ it("rejects options on fields without options", () => {
+ expect(() =>
+ resolveFieldUpdate(
+ { ...dropdown, type: "text", options: null, defaultValue: null },
+ { options: ["a"] },
+ ),
+ ).toThrow("Only dropdown and multiselect fields have options");
+ });
+});
diff --git a/tests/api/github-integration/repository-binding.test.ts b/tests/api/github-integration/repository-binding.test.ts
index a0a05ba77..6ca13c09b 100644
--- a/tests/api/github-integration/repository-binding.test.ts
+++ b/tests/api/github-integration/repository-binding.test.ts
@@ -259,6 +259,58 @@ describe("authorized bounded repository listing", () => {
expect(page.nextPage).toBeNull();
expect(m.listRepos).not.toHaveBeenCalled();
});
+ it("searches before checking access and keeps scanning installations", async () => {
+ m.listInstallations
+ .mockResolvedValueOnce({
+ data: [{ id: 10, account: { login: "owner" } }],
+ })
+ .mockResolvedValueOnce({ data: [{ id: 11, account: { login: "org" } }] })
+ .mockResolvedValueOnce({ data: [] });
+ m.listRepos
+ .mockResolvedValueOnce({
+ data: {
+ repositories: [
+ { ...candidate(20), full_name: "owner/website" },
+ { ...candidate(21), description: null },
+ ],
+ },
+ })
+ .mockResolvedValueOnce({
+ data: { repositories: [{ ...candidate(30), full_name: "org/web" }] },
+ });
+ const page = await listUserRepositories(
+ "user",
+ { installationPage: 1, repositoryPage: 1 },
+ "WEB",
+ );
+ expect(page.repositories.map((repo) => repo.id)).toEqual([20, 30]);
+ expect(page.installations.map((item) => item.id)).toEqual([10, 11]);
+ expect(page.nextPage).toBeNull();
+ expect(m.listRepos).toHaveBeenCalledWith(
+ expect.objectContaining({ per_page: 100, page: 1 }),
+ );
+ expect(m.user).toHaveBeenCalledTimes(2);
+ expect(m.permission).toHaveBeenCalledTimes(2);
+ expect(m.permission).not.toHaveBeenCalledWith(
+ expect.objectContaining({ repo: "repo-21" }),
+ );
+ });
+ it("does not return search matches the caller cannot administer", async () => {
+ m.listInstallations
+ .mockResolvedValueOnce({
+ data: [{ id: 10, account: { login: "owner" } }],
+ })
+ .mockResolvedValueOnce({ data: [] });
+ m.permission.mockResolvedValue({ data: { permission: "write" } });
+ const page = await listUserRepositories(
+ "user",
+ { installationPage: 1, repositoryPage: 1 },
+ "private",
+ );
+ expect(page.repositories).toEqual([]);
+ expect(page.installations).toEqual([]);
+ expect(JSON.stringify(page)).not.toContain("owner");
+ });
it("rejects unlinked callers before any provider enumeration", async () => {
m.account.mockResolvedValue(null);
await expect(