TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.
TypeScript graphviewkanban-boardnodejsproductivityproject-managementself-hostedtasktask-managementtask-managertodoapp
wip: themes, rbac, kanban columns
Nikolai Giman3e30a70d662c
diff --git a/api/.env.example b/api/.env.exampleindex 4c991e2..5aed58d 100644--- a/api/.env.example+++ b/api/.env.example@@ -20,6 +20,12 @@ JWT_SIGN=your_jwt_secret_hereACCESS_LIFE_TIME=1dREFRESH_LIFE_TIME=2dJWT_ALG=HS256+# Max sign-in codes one account can request by email per hour (default 5)+# LOGIN_CODE_HOURLY_LIMIT=5+# Days a sign-in session lasts, however often its tokens are refreshed (default 90)+# SESSION_MAX_AGE_DAYS=90+# Let users delete their own account (default false: on a company install an admin removes accounts)+# ALLOW_ACCOUNT_DELETION=false# SSO: comma-separated email domains that skip DNS/HTTP ownership proof (air-gapped installs)#SSO_TRUSTED_DOMAINS=company.com,corp.localdiff --git a/api/src/App.ts b/api/src/App.tsindex 7337d49..1bb6a07 100644--- a/api/src/App.ts+++ b/api/src/App.ts@@ -6,6 +6,8 @@ import errorHandler from './middlewares/error-handler';import routes from './routes';import passport, { initPassportLogin } from './tv-modules/auth/strategies/passport-login';import { LoginMethods } from './tv-modules/auth/LoginMethods';+import SessionStorage from './tv-modules/auth/SessionStorage';+import { AccountDeletion } from './tv-modules/auth/AccountDeletion';import { InviteEmailDispatcher } from './tv-modules/collaboration/InviteEmailDispatcher';import { PublicApiUrl } from './modules/public-url';import { validateWebhooksEnvOnStartup } from './tv-modules/webhooks/webhooks.utils';@@ -21,6 +23,8 @@ export default class App {constructor(port: number) {LoginMethods.validateOnStartup();+ SessionStorage.validateOnStartup();+ AccountDeletion.validateOnStartup();PublicApiUrl.validateOnStartup();InviteEmailDispatcher.validateOnStartup();validateWebhooksEnvOnStartup();diff --git a/api/src/core/GoalAccess.ts b/api/src/core/GoalAccess.tsnew file mode 100644index 0000000..b7482a4--- /dev/null+++ b/api/src/core/GoalAccess.ts@@ -0,0 +1,21 @@+import type { GoalPermissionType } from '../types/auth.types';+import { GoalPermissionsChecker } from './GoalPermissionsChecker';++/** Effective, token-aware permissions of the current user over a set of goals. */+export class GoalAccess {+ private readonly checkers: Map<number, GoalPermissionsChecker>;++ constructor(checkers: Map<number, GoalPermissionsChecker>) {+ this.checkers = checkers;+ }++ checkerFor(goalId: number): GoalPermissionsChecker {+ return this.checkers.get(goalId) ?? new GoalPermissionsChecker([]);+ }++ goalIdsWith(permission: GoalPermissionType): number[] {+ return [...this.checkers]+ .filter(([, checker]) => checker.hasPermissions(permission))+ .map(([goalId]) => goalId);+ }+}diff --git a/api/src/core/GoalPermissionsFetcher.ts b/api/src/core/GoalPermissionsFetcher.tsindex b7fe5fc..a81bc4a 100644--- a/api/src/core/GoalPermissionsFetcher.ts+++ b/api/src/core/GoalPermissionsFetcher.ts@@ -1,5 +1,6 @@-import type { PermissionsEntityType } from '../types/auth.types';+import type { GoalPermissionItemsFromDb, GoalPermissionType, PermissionsEntityType } from '../types/auth.types';import type { AppUser } from './AppUser';+import { GoalAccess } from './GoalAccess';import { GoalPermissionsChecker } from './GoalPermissionsChecker';import { GoalPermissionsRepository } from './GoalPermissionsRepository';@@ -39,29 +40,61 @@ export class GoalPermissionsFetcher {if (!goalId) { return new GoalPermissionsChecker([]); }- //Token authentication check+ return (await this.getAccessForGoals([goalId])).checkerFor(goalId);+ }++ /**+ * The single place where a user's goal permissions are resolved: owner or role+ * permissions, dropped for goals outside the token's allowedGoalIds and+ * intersected with the token's permissions.+ */+ async getAccessForGoals(goalIds: number[]): Promise<GoalAccess> {+ const checkers = new Map<number, GoalPermissionsChecker>();+ const userData = this.user.getUserData();+ if (!userData) return new GoalAccess(checkers);+const allowedGoalIds = this.user.getAllowedGoalIds();- if (allowedGoalIds && allowedGoalIds.length > 0 && !allowedGoalIds.includes(goalId)) {- return new GoalPermissionsChecker([]);+ const scopedGoalIds = [...new Set(goalIds)].filter(+ (id) => !allowedGoalIds || allowedGoalIds.length === 0 || allowedGoalIds.includes(id)+ );+ const uncachedGoalIds = scopedGoalIds.filter((id) => !this.isCacheValid(id));++ if (uncachedGoalIds.length > 0) {+ const rows = await this.goalPermissionsRepository.fetchPermissionsForGoals({+ goalIds: uncachedGoalIds,+ userId: userData.id,+ email: userData.email,+ });+ const tokenPerms = this.user.getTokenPermissions();+ const permissionsByGoal = new Map<number, GoalPermissionItemsFromDb>(uncachedGoalIds.map((id) => [id, []]));++ rows.forEach((row) => {+ if (tokenPerms && tokenPerms.length > 0 && !tokenPerms.includes(row.permissionName)) return;+ permissionsByGoal.get(row.goalId)?.push({ permissionName: row.permissionName, permissionId: row.permissionId });+ });++ permissionsByGoal.forEach((permissions, goalId) => {+ this.checkerCache[goalId] = {+ checker: new GoalPermissionsChecker(permissions),+ timestamp: performance.now(),+ };+ });}- if (this.isCacheValid(goalId)) {- return this.checkerCache[goalId].checker;- }+ scopedGoalIds.forEach((id) => checkers.set(id, this.checkerCache[id].checker));+ return new GoalAccess(checkers);+ }- let permissions = await this.goalPermissionsRepository.fetchPermissionsForGoal(goalId, this.user);+ /**+ * Whether the caller may see data that belongs to no goal (e.g. legacy tags):+ * a token restricted to goals may not, and a token's permissions still apply.+ */+ canSeeDataOutsideGoals(permission: GoalPermissionType): boolean {+ const allowedGoalIds = this.user.getAllowedGoalIds();+ if (allowedGoalIds && allowedGoalIds.length > 0) return false;const tokenPerms = this.user.getTokenPermissions();- if (tokenPerms && tokenPerms.length > 0) {- permissions = permissions.filter(p => tokenPerms.includes(p.permissionName));- }-- this.checkerCache[goalId] = {- checker: new GoalPermissionsChecker(permissions),- timestamp: performance.now(),- };-- return this.checkerCache[goalId].checker;+ return !tokenPerms || tokenPerms.length === 0 || tokenPerms.includes(permission);}async getCheckerForGoal(goalId: number): Promise<GoalPermissionsChecker> {diff --git a/api/src/core/GoalPermissionsRepository.ts b/api/src/core/GoalPermissionsRepository.tsindex 678de4d..273b1ff 100644--- a/api/src/core/GoalPermissionsRepository.ts+++ b/api/src/core/GoalPermissionsRepository.ts@@ -9,11 +9,17 @@ import {PermissionsSchema,} from 'taskview-db-schemas';import { Database } from '../modules/db';-import type { FetchGoalIdsWithAnyPermissionParams, FetchPermissionsForGoalByUserParams, GoalPermissionItemsFromDb } from '../types/auth.types';+import type {+ FetchGoalIdsWithAnyPermissionParams,+ FetchPermissionsForGoalByUserParams,+ FetchPermissionsForGoalsParams,+ GoalPermissionItemsFromDb,+ GoalPermissionItemsWithGoalFromDb,+ GoalPermissionType,+} from '../types/auth.types';import type { GoalItemInDb } from '../types/goal.type';import type { ListItemInDb } from '../types/lists.types';import type { TaskItemInDb } from '../types/tasks.types';-import type { AppUser } from './AppUser';export class GoalPermissionsRepository {private db: Database;@@ -32,12 +38,6 @@ export class GoalPermissionsRepository {return null;}- async fetchPermissionsForGoal(goalId: number, user: AppUser): Promise<GoalPermissionItemsFromDb> {- const userData = user.getUserData();- if (!userData) return [];- return this.fetchPermissionsForGoalByUser({ goalId, userId: userData.id, email: userData.email });- }-/*** Permission set of an arbitrary user for a goal, without an AppUser/request* context — used by background workers (e.g. deadline notifications) that@@ -73,6 +73,74 @@ export class GoalPermissionsRepository {return result.rows;}+ async fetchPermissionsForGoals(params: FetchPermissionsForGoalsParams): Promise<GoalPermissionItemsWithGoalFromDb> {+ if (params.goalIds.length === 0) return [];++ const goals = await this.db.dbDrizzle+ .select({ id: GoalsSchema.id, owner: GoalsSchema.owner })+ .from(GoalsSchema)+ .where(inArray(GoalsSchema.id, params.goalIds));++ const ownedGoalIds = goals.filter((g) => g.owner === params.userId).map((g) => g.id);+ const sharedGoalIds = goals.filter((g) => g.owner !== params.userId).map((g) => g.id);+ const rows: GoalPermissionItemsWithGoalFromDb = [];++ if (ownedGoalIds.length > 0) {+ const allPermissions = await this.db.dbDrizzle+ .select({ permissionName: PermissionsSchema.name, permissionId: PermissionsSchema.id })+ .from(PermissionsSchema);+ ownedGoalIds.forEach((goalId) => {+ allPermissions.forEach((p) => {+ rows.push({ goalId, permissionName: p.permissionName as GoalPermissionType, permissionId: p.permissionId });+ });+ });+ }++ if (sharedGoalIds.length > 0) {+ const shared = await this.db.dbDrizzle+ .select({+ goalId: CollaborationUsersToGoalsSchema.goalId,+ permissionName: PermissionsSchema.name,+ permissionId: PermissionsSchema.id,+ })+ .from(CollaborationUsersSchema)+ .innerJoin(+ CollaborationUsersToGoalsSchema,+ eq(CollaborationUsersToGoalsSchema.userId, CollaborationUsersSchema.id),+ )+ .innerJoin(+ CollaborationUsersToRolesSchema,+ eq(CollaborationUsersToRolesSchema.userId, CollaborationUsersSchema.id),+ )+ .innerJoin(+ CollaborationRolesSchema,+ and(+ eq(CollaborationRolesSchema.id, CollaborationUsersToRolesSchema.roleId),+ eq(CollaborationRolesSchema.goalId, CollaborationUsersToGoalsSchema.goalId),+ ),+ )+ .innerJoin(+ CollaborationPermissionsToRoleSchema,+ eq(CollaborationPermissionsToRoleSchema.roleId, CollaborationRolesSchema.id),+ )+ .innerJoin(+ PermissionsSchema,+ eq(PermissionsSchema.id, CollaborationPermissionsToRoleSchema.permissionId),+ )+ .where(+ and(+ eq(CollaborationUsersSchema.email, params.email),+ inArray(CollaborationUsersToGoalsSchema.goalId, sharedGoalIds),+ ),+ );+ shared.forEach((r) => {+ rows.push({ goalId: r.goalId, permissionName: r.permissionName as GoalPermissionType, permissionId: r.permissionId });+ });+ }++ return rows;+ }+async getGoalIdForTask(taskId: number): Promise<TaskItemInDb['goal_id'] | null> {const result = await this.db.query<TaskItemInDb>('select goal_id from tasks.tasks where id = $1', [taskId]);if (result.rows.length > 0) {diff --git a/api/src/middlewares/app-user-middleware.ts b/api/src/middlewares/app-user-middleware.tsindex 8622d91..44fe158 100644--- a/api/src/middlewares/app-user-middleware.ts+++ b/api/src/middlewares/app-user-middleware.ts@@ -37,7 +37,7 @@ export const appUserMiddleware = async (req: Request, res: Response, next: NextF}if (token) {- const userPayload = await AuthController.validateTokens(token);+ const userPayload = await AuthController.validateTokens({ token, type: 'access' });if (userPayload) {req.appUser = new AppUser(userPayload);try {diff --git a/api/src/middlewares/require-token-permission.ts b/api/src/middlewares/require-token-permission.tsindex 68ec920..de00287 100644--- a/api/src/middlewares/require-token-permission.ts+++ b/api/src/middlewares/require-token-permission.ts@@ -4,7 +4,7 @@ import type { GoalPermissionType } from '../types/auth.types';/*** Narrows what a restricted API / OAuth token may do on surfaces that are guarded* by an organization role or by project ownership rather than by the project RBAC- * — organizations, SSO configuration, webhooks. Those checks never consult+ * — organizations, SSO configuration, billing. Those checks never consult* GoalPermissionsFetcher, so without this the scope chosen when the token was* issued would simply not apply to them.*diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.jsonindex ed34688..7ebd952 100644--- a/api/src/migrations/taskview/migrate.json+++ b/api/src/migrations/taskview/migrate.json@@ -861,5 +861,43 @@"New tables tv_auth.scim_groups and tv_auth.scim_group_members: groups pushed by an identity provider over SCIM and their members, per SSO configuration. Groups are stored only and do not grant access yet.","New table tv_auth.scim_group_projects: an organization admin links a SCIM group to a project with a default role. People who join the group, or are in it when the link is made, or are reactivated while in it, are added to the project with that role unless they are already in it. Leaving the group changes nothing: the project is managed in TaskView."]+ },+ "66": {+ "version": "1.71.0",+ "name": "Login code limits",+ "releaseDate": "20261024",+ "scripts": [+ "/1.71.0/0.add-login-code-attempts.sql",+ "/1.71.0/1.create-login-code-requests.sql"+ ],+ "description": [+ "New column tv_auth.users.login_code_attempts: counts wrong guesses of the current email login code. After 5 wrong guesses the code stops working and a new one has to be requested; requesting a new code resets the counter.",+ "New table tv_auth.login_code_requests: a log of emailed login codes. One account can request at most LOGIN_CODE_HOURLY_LIMIT codes (default 5) in any hour; rows older than an hour are pruned."+ ]+ },+ "67": {+ "version": "1.72.0",+ "name": "Account deletion code expiry",+ "releaseDate": "20261024",+ "scripts": [+ "/1.72.0/0.add-account-deletion-created-at.sql"+ ],+ "description": [+ "New column tv_auth.account_deletion.created_at: when the account deletion code was emailed. A code works for 15 minutes; codes issued before this version start their 15 minutes at the upgrade."+ ]+ },+ "68": {+ "version": "1.73.0",+ "name": "Webhook permissions",+ "releaseDate": "20261024",+ "scripts": [+ "/1.73.0/0.webhooks-permissions.sql",+ "/1.73.0/all-triggers.sql"+ ],+ "description": [+ "New permission group 9 'webhooks'. webhooks_can_manage moves there from the organization group, and the new webhooks_can_view lets a project member see the webhooks and their delivery history. Any member whose role grants them can view or manage webhooks, not only the project owner. Neither permission is granted to existing or default roles: owners add them to roles in the role editor.",+ "A *_can_manage permission no longer includes the matching view permission, and timetracking_can_manage_all no longer includes viewing entries or logging own time: each permission grants only what it names.",+ "all-triggers.sql: re-applies all triggers idempotently and updates tasks.add_roles_and_permissions() so the editor role of NEW projects also gets timetracking_can_log. Existing projects are not changed: owners grant it to their roles in the role editor."+ ]}-}+}\ No newline at end of filediff --git a/api/src/migrations/taskview/sql/1.71.0/0.add-login-code-attempts.sql b/api/src/migrations/taskview/sql/1.71.0/0.add-login-code-attempts.sqlnew file mode 100644index 0000000..d63d463--- /dev/null+++ b/api/src/migrations/taskview/sql/1.71.0/0.add-login-code-attempts.sql@@ -0,0 +1,2 @@+ALTER TABLE tv_auth.users+ ADD COLUMN IF NOT EXISTS login_code_attempts INTEGER NOT NULL DEFAULT 0;diff --git a/api/src/migrations/taskview/sql/1.71.0/1.create-login-code-requests.sql b/api/src/migrations/taskview/sql/1.71.0/1.create-login-code-requests.sqlnew file mode 100644index 0000000..6f93670--- /dev/null+++ b/api/src/migrations/taskview/sql/1.71.0/1.create-login-code-requests.sql@@ -0,0 +1,9 @@+-- Log of emailed login codes, used to cap how many codes one account can request per hour.+-- Rows older than an hour are pruned before each new code is issued.+CREATE TABLE IF NOT EXISTS tv_auth.login_code_requests (+ id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,+ user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,+ requested_at TIMESTAMP NOT NULL DEFAULT NOW()+);++CREATE INDEX IF NOT EXISTS idx_login_code_requests_user_requested ON tv_auth.login_code_requests(user_id, requested_at);diff --git a/api/src/migrations/taskview/sql/1.72.0/0.add-account-deletion-created-at.sql b/api/src/migrations/taskview/sql/1.72.0/0.add-account-deletion-created-at.sqlnew file mode 100644index 0000000..705b320--- /dev/null+++ b/api/src/migrations/taskview/sql/1.72.0/0.add-account-deletion-created-at.sql@@ -0,0 +1 @@+ALTER TABLE tv_auth.account_deletion ADD COLUMN created_at TIMESTAMP NOT NULL DEFAULT now();diff --git a/api/src/migrations/taskview/sql/1.73.0/0.webhooks-permissions.sql b/api/src/migrations/taskview/sql/1.73.0/0.webhooks-permissions.sqlnew file mode 100644index 0000000..3f7dda6--- /dev/null+++ b/api/src/migrations/taskview/sql/1.73.0/0.webhooks-permissions.sql@@ -0,0 +1,25 @@+-- Permission group 9 = webhooks (shown in the role editor and the API token picker)+INSERT INTO tv_auth.permissions_group (id, name)+VALUES (9, 'webhooks')+ON CONFLICT (id) DO NOTHING;++UPDATE tv_auth.permissions+SET permission_group = 9+WHERE name = 'webhooks_can_manage';++INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)+VALUES (+ 'webhooks_can_view',+ 'View project webhooks and their delivery history',+ 9,+ '{+ "en": "View webhooks. See the project webhooks, their URLs and the delivery history with payloads.",+ "ru": "Просмотр вебхуков. Видеть вебхуки проекта, их адреса и историю доставок с содержимым.",+ "de": "Webhooks ansehen. Die Webhooks des Projekts, ihre URLs und den Zustellverlauf mit Inhalten sehen.",+ "es": "Ver webhooks. Ver los webhooks del proyecto, sus URL y el historial de entregas con su contenido.",+ "pt-BR": "Ver webhooks. Ver os webhooks do projeto, suas URLs e o histórico de entregas com o conteúdo."+ }'::jsonb+)+ON CONFLICT (name) DO NOTHING;++-- Not granted to any role: owners add the webhook permissions to their roles in the role editor.diff --git a/api/src/migrations/taskview/sql/1.73.0/all-triggers.sql b/api/src/migrations/taskview/sql/1.73.0/all-triggers.sqlnew file mode 100644index 0000000..7a99ff1--- /dev/null+++ b/api/src/migrations/taskview/sql/1.73.0/all-triggers.sql@@ -0,0 +1,648 @@+--1.+--Trigger set previous version+create or replace function app.trigger_set_previous_version()+ returns trigger as+$date_complete$+begin+ new.prev_version = old.version;+ return new;+end;+$date_complete$+ language plpgsql;++drop trigger if exists trigger_set_previous_version on app.version;+create trigger trigger_set_previous_version+ before insert+ on app.version+ for each row+execute procedure app.trigger_set_previous_version();++--2.+--Trigger for adding owner for taskList from goal+create or replace function tasks.trigger_set_owner_for_component()+ returns trigger as+$date_complete$+begin+ new.owner = (select owner from tasks.goals where id = new.goal_id);+ return new;+end;+$date_complete$+ language plpgsql;++drop trigger if exists trigger_set_owner_for_component on tasks.goal_lists;+create trigger trigger_set_owner_for_component+ before insert+ on tasks.goal_lists+ for each row+execute procedure tasks.trigger_set_owner_for_component();++--3.+--Trigger for updating date_complete for task+create or replace function tasks.update_date_complete()+ returns trigger as+$date_complete$+begin+ if new.complete != old.complete+ then+ if new.complete = true+ then+ update tasks.tasks set date_complete = now() where id = old.id;+ else+ update tasks.tasks set date_complete = null where id = old.id;+ end if;+ end if;+ return new;+end;+$date_complete$+ language plpgsql;++drop trigger if exists tr_update_date_complete on tasks.tasks;+create trigger tr_update_date_complete+ after update+ on tasks.tasks+ for each row+execute procedure tasks.update_date_complete();++--4.+-- Delete user from collaboration if not assigned to any goal+create or replace function collaboration.delete_user_if_not_assigned_to_goal()+returns trigger as $$+declare+ count int;+begin+ if not exists (+ select 1+ from collaboration.users_to_goals+ where user_id = old.user_id+ limit 1+ ) then+ delete from collaboration.users where id = old.user_id;+ end if;++ return old;+end;+$$ language plpgsql;++drop trigger if exists trigger_delete_user_if_not_assigned_to_goal on collaboration.users_to_goals;+create trigger trigger_delete_user_if_not_assigned_to_goal+ after delete+ on collaboration.users_to_goals+ for each row+execute function collaboration.delete_user_if_not_assigned_to_goal();++--5.+--Trigger for checking task graph relation goal to avoid connection between tasks from different goals+create or replace function tasks.check_task_graph_relation_goal()+returns trigger as $$+declare+ from_goal int;+ to_goal int;+begin+ select goal_id into from_goal from tasks.tasks where id = new.from_task_id;+ select goal_id into to_goal from tasks.tasks where id = new.to_task_id;++ if from_goal is null or to_goal is null then+ raise exception 'Invalid task reference in relation';+ end if;++ if from_goal <> to_goal then+ raise exception 'Relation goal_id must match both tasks'' goal_id';+ end if;++ new.goal_id := from_goal;++ return new;+end;+$$ language plpgsql;++drop trigger if exists trigger_task_relation_goal on tasks.task_relations;+create trigger trigger_task_relation_goal+before insert or update on tasks.task_relations+for each row execute function tasks.check_task_graph_relation_goal();++--6.+--Trigger for logging changes in taskList to history table+create or replace function tasks.log_changes_tasks_goal_lists()+ returns trigger as+$body$+begin+ if tg_op = 'DELETE' then+ insert into history.tasks_goal_lists (goal_list_id, edit_date, task, deleted) values (old.id, now(), to_jsonb(old), 1);+ return old;+ elseif tg_op = 'UPDATE' then+ insert into history.tasks_goal_lists (goal_list_id, edit_date, task, deleted)+ VALUES (old.id, new.date_creation, to_jsonb(old), 0);+ new.edit_date = now();+ return new;+ end if;+end+$body$+ language plpgsql;++drop trigger if exists trigger_log_changes_tasks_goal_lists on tasks.goal_lists;+create trigger trigger_log_changes_tasks_goal_lists+ before update or delete+ on tasks.goal_lists+ for each row+execute procedure tasks.log_changes_tasks_goal_lists();++--7.+--Trigger for logging changes in goal to history table+create or replace function tasks.log_changes_tasks_goals()+ returns trigger as+$body$+begin+ if tg_op = 'DELETE' then+ insert into history.tasks_goals (goal_id, edit_date, task, deleted) values (old.id, now(), to_jsonb(old), 1);+ return old;+ elseif tg_op = 'UPDATE' then+ insert into history.tasks_goals (goal_id, edit_date, task, deleted)+ VALUES (old.id, new.date_creation, to_jsonb(old), 0);+ new.edit_date = now();+ return new;+ end if;+end+$body$+ language plpgsql;++drop trigger if exists trigger_log_changes_tasks_goals on tasks.goals;+create trigger trigger_log_changes_tasks_goals+ before update or delete+ on tasks.goals+ for each row+execute procedure tasks.log_changes_tasks_goals();++--8.+--Trigger for logging changes in task to history table+create or replace function tasks.log_changes_tasks_tasks()+ returns trigger as+$body$+begin+ if tg_op = 'DELETE' then+ insert into history.tasks_tasks (task_id, edit_date, task, deleted) values (old.id, now(), to_jsonb(old), 1);+ return old;+ elseif tg_op = 'UPDATE' then+ insert into history.tasks_tasks (task_id, edit_date, task, deleted)+ VALUES (old.id, new.date_creation, to_jsonb(old), 0);+ new.edit_date = now();+ return new;+ end if;+end+$body$+ language plpgsql;++drop trigger if exists trigger_log_changes_tasks_tasks on tasks.tasks;+create trigger trigger_log_changes_tasks_tasks+ before update or delete+ on tasks.tasks+ for each row+execute procedure tasks.log_changes_tasks_tasks();++--9.+--Trigger for setting goal_id default for task+CREATE OR REPLACE FUNCTION tasks.set_goal_id_default_for_task()+ RETURNS TRIGGER AS+$$+DECLARE+ goal_id INT;+BEGIN++ SELECT gl.goal_id+ INTO goal_id+ FROM tasks.goal_lists gl+ WHERE gl.id = NEW.goal_list_id;++ IF goal_id IS NOT NULL THEN+ NEW.goal_id := goal_id;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists before_insert_set_goal_id_for_task on tasks.tasks;++CREATE TRIGGER before_insert_set_goal_id_for_task+ BEFORE INSERT OR UPDATE+ ON tasks.tasks+ FOR EACH ROW+EXECUTE FUNCTION tasks.set_goal_id_default_for_task();+++--10.+--Trigger for adding default roles and permissions for goal+CREATE OR REPLACE FUNCTION tasks.add_roles_and_permissions()+ RETURNS TRIGGER AS+$$+DECLARE+ editor_role_id INTEGER;+ executor_role_id INTEGER;+BEGIN+ -- 1. Create role "editor"+ INSERT INTO collaboration.roles (name, goal_id)+ VALUES ('editor', NEW.id)+ RETURNING id INTO editor_role_id;++ -- 2. Create role "executor"+ INSERT INTO collaboration.roles (name, goal_id)+ VALUES ('executor', NEW.id)+ RETURNING id INTO executor_role_id;++ -- 3. Add permissions for role "editor"+ INSERT INTO collaboration.permissions_to_role (role_id, permission_id)+ SELECT editor_role_id, id+ FROM tv_auth.permissions+ WHERE name IN (+ 'goal_can_watch_content',+ 'goal_can_edit',+ 'goal_can_add_task_list',+ 'goal_can_manage_users',+ 'component_can_watch_content',+ 'component_can_edit',+ 'component_can_delete',+ 'component_can_add_tasks',+ 'task_can_edit_deadline',+ 'task_can_watch_subtasks',+ 'task_can_watch_note',+ 'task_can_recovery_history',+ 'task_can_watch_assigned_users',+ 'task_can_edit_priority',+ 'task_can_delete',+ 'task_can_watch_details',+ 'task_can_assign_users',+ 'task_can_add_subtasks',+ 'task_can_watch_tags',+ 'task_can_watch_priority',+ 'task_can_access_history',+ 'task_can_edit_tags',+ 'task_can_edit_description',+ 'task_can_edit_status',+ 'task_can_edit_note',+ 'kanban_can_manage',+ 'kanban_can_view',+ 'graph_can_manage',+ 'graph_can_view',+ 'timetracking_can_view',+ 'timetracking_can_log',+ 'timetracking_can_manage_all',+ 'sprint_can_view',+ 'sprint_can_manage',+ 'sprint_can_assign_tasks',+ 'sprint_can_view_analytics',+ 'file_can_view',+ 'file_can_manage',+ 'automation_can_view',+ 'automation_can_manage'+ );++ -- 4. Add permissions for role "viewver"+ INSERT INTO collaboration.permissions_to_role (role_id, permission_id)+ SELECT executor_role_id, id+ FROM tv_auth.permissions+ WHERE name IN (+ 'goal_can_watch_content',+ 'component_can_watch_content',+ 'component_can_add_tasks',+ 'task_can_watch_subtasks',+ 'task_can_watch_note',+ 'task_can_watch_assigned_users',+ 'task_can_watch_details',+ 'task_can_add_subtasks',+ 'task_can_watch_tags',+ 'task_can_watch_priority',+ 'timetracking_can_view',+ 'timetracking_can_log',+ 'sprint_can_view',+ 'sprint_can_assign_tasks',+ 'file_can_view',+ 'automation_can_view'+ );++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;+++drop trigger if exists add_roles_after_insert on tasks.goals;++CREATE TRIGGER add_roles_after_insert+ AFTER INSERT+ ON tasks.goals+ FOR EACH ROW+EXECUTE FUNCTION tasks.add_roles_and_permissions();+++--11.+--Trigger for adjusting start and end dates for task+CREATE OR REPLACE FUNCTION tasks.adjust_start_and_end_dates()+ RETURNS TRIGGER AS+$$+DECLARE+ start_timestamp TIMESTAMPTZ;+ end_timestamp TIMESTAMPTZ;+BEGIN+ -- If start_date is NULL, then start_time should be NULL+ IF NEW.start_date IS NULL THEN+ NEW.start_time := NULL;+ END IF;++ -- If end_date is NULL, then end_time should be NULL+ IF NEW.end_date IS NULL THEN+ NEW.end_time := NULL;+ END IF;++ -- If both dates are set+ IF NEW.start_date IS NOT NULL AND NEW.end_date IS NOT NULL THEN+ -- Adjust dates+ IF NEW.start_date > NEW.end_date THEN+ -- If start_date is greater than end_date, set end_date to start_date+ NEW.end_date := NEW.start_date;+ -- end_time remains unchanged+ ELSIF NEW.end_date < NEW.start_date THEN+ -- If end_date is less than start_date, set start_date to end_date+ NEW.start_date := NEW.end_date;+ -- start_time remains unchanged+ END IF;++ -- Prepare timestamps for comparison+ start_timestamp := (NEW.start_date::text || ' ' || COALESCE(NEW.start_time::text, '00:00:00+00'))::timestamptz;+ end_timestamp := (NEW.end_date::text || ' ' || COALESCE(NEW.end_time::text, '00:00:00+00'))::timestamptz;++ -- If start_timestamp is greater than end_timestamp, adjust end_date and end_time+ IF start_timestamp > end_timestamp THEN+ NEW.end_date := NEW.start_date;+ -- Assign end_time only if start_time is not NULL+ IF NEW.start_time IS NOT NULL AND NEW.end_time IS NOT NULL THEN+ NEW.end_time := NEW.start_time;+ END IF;+ END IF;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;+++drop trigger if exists adjust_dates_and_times_trigger on tasks.tasks;+CREATE TRIGGER adjust_dates_and_times_trigger+ BEFORE INSERT OR UPDATE+ ON tasks.tasks+ FOR EACH ROW+EXECUTE FUNCTION tasks.adjust_start_and_end_dates();++--12.+--Trigger for adding self/owner to collaboration table to be able to assign tasks to self+create or replace function tasks.add_self_to_collaboration()+returns trigger as $$+DECLARE+ owner_email TEXT;+BEGIN++ select email into owner_email+ from tv_auth.users+ where id = NEW.owner;++ if owner_email is not null then+ insert into collaboration.users (email) values (owner_email) ON CONFLICT (email) DO NOTHING;+ insert into collaboration.users_to_goals (goal_id, user_id) values (NEW.id, (select id from collaboration.users where email = owner_email));+ end if;++ return NEW;+END;+$$ language plpgsql;++drop trigger if exists add_selt_to_collaboration_trg on tasks.goals;++create trigger add_selt_to_collaboration_trg+ after insert on tasks.goals+ for each row+ execute function tasks.add_self_to_collaboration();++--13.+--Trigger for adding default kanban columns for new goal+CREATE OR REPLACE FUNCTION tasks.kanban_add_default_columns()+RETURNS TRIGGER AS $$+BEGIN+ -- Add default columns for new goal+ INSERT INTO tasks.statuses (name, goal_id, view_order)+ VALUES+ ('TODO', NEW.id, 1),+ ('In Progress', NEW.id, 2),+ ('Done', NEW.id, 3);+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS kanban_add_default_columns_trg ON tasks.goals;++CREATE TRIGGER kanban_add_default_columns_trg+AFTER INSERT ON tasks.goals+FOR EACH ROW+EXECUTE FUNCTION tasks.kanban_add_default_columns();++--14.+--Trigger for validating the correct statusId for the inserted value. To avoid assigning a status that does not belong to the goal.+CREATE OR REPLACE FUNCTION tasks.check_task_status_goal()+RETURNS TRIGGER AS $$+BEGIN+ -- Check if there is a record in tasks.statuses with the same goal_id+ IF NOT EXISTS (+ SELECT 1 FROM tasks.statuses s+ WHERE s.id = NEW.status_id AND s.goal_id = NEW.goal_id+ ) THEN+ RAISE EXCEPTION 'Status ID % is not valid for goal ID %', NEW.status_id, NEW.goal_id;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists enforce_task_status_goal on tasks.tasks;++CREATE TRIGGER enforce_task_status_goal+BEFORE INSERT OR UPDATE ON tasks.tasks+FOR EACH ROW+WHEN (NEW.status_id IS NOT NULL)+EXECUTE FUNCTION tasks.check_task_status_goal();++--15.+--Trigger for setting default orders value for task+CREATE OR REPLACE FUNCTION tasks.set_order_value()+RETURNS TRIGGER AS $$+BEGIN+ IF NEW.task_order IS NULL THEN+ NEW.task_order := NEW.id;+ END IF;+ IF NEW.kanban_order IS NULL THEN+ NEW.kanban_order := NEW.id;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists set_order_trigger on tasks.tasks;+CREATE TRIGGER set_order_trigger+BEFORE INSERT ON tasks.tasks+FOR EACH ROW+EXECUTE FUNCTION tasks.set_order_value();++--16.+--Trigger for setting default view order for new status+CREATE OR REPLACE FUNCTION tasks.status_set_default_view_order()+RETURNS TRIGGER AS $$+DECLARE+ new_view_order INT;+BEGIN+ -- Determine the next view_order for the given goal_id+ SELECT COALESCE(MAX(view_order), 0) + 1 INTO new_view_order+ FROM tasks.statuses+ WHERE goal_id = NEW.goal_id;++ -- Assign the calculated value to the view_order field+ NEW.view_order := new_view_order;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists set_default_status_view_order on tasks.statuses;++CREATE TRIGGER set_default_status_view_order+BEFORE INSERT ON tasks.statuses+FOR EACH ROW+EXECUTE FUNCTION tasks.status_set_default_view_order();++--17.+--Trigger for validating the correct user_id for the inserted value. To avoid assigning a user that does not belong to the goal.+CREATE OR REPLACE FUNCTION tasks_auth.control_user_id_is_from_same_goal_as_task()+RETURNS TRIGGER AS $$+DECLARE+ user_exists BOOLEAN;+BEGIN+ SELECT EXISTS (+ SELECT 1+ FROM tasks.tasks tt+ LEFT JOIN collaboration.users_to_goals utg ON utg.goal_id = tt.goal_id+ WHERE tt.id = NEW.task_id AND utg.user_id = NEW.collab_user_id+ ) INTO user_exists;++ IF NOT user_exists THEN+ RAISE EXCEPTION 'User % is not associated with the goal of task %', NEW.collab_user_id, NEW.task_id;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists trigger_control_user_id_is_from_same_goal_as_task on tasks_auth.task_assignee;++CREATE TRIGGER trigger_control_user_id_is_from_same_goal_as_task+BEFORE INSERT ON tasks_auth.task_assignee+FOR EACH ROW+EXECUTE FUNCTION tasks_auth.control_user_id_is_from_same_goal_as_task();++--18.+--Trigger for adding owner for task, extend owner from goal or taskList++--delete old function with wrong name+drop trigger if exists trigger_set_owner_for_task on tasks.tasks;+drop function if exists tasks.trigger_set_owner_for_task();++CREATE OR REPLACE FUNCTION tasks.fn_set_owner_for_task()+RETURNS TRIGGER AS+$body$+BEGIN+ NEW.owner := COALESCE(+ (SELECT owner FROM tasks.goal_lists WHERE id = NEW.goal_list_id),+ (SELECT owner FROM tasks.goals WHERE id = NEW.goal_id)+ );++ IF NEW.owner IS NULL THEN+ RAISE EXCEPTION 'Can not insert task without owner';+ END IF;++ RETURN NEW;+END;+$body$+LANGUAGE plpgsql;++drop trigger if exists trigger_set_owner_for_task on tasks.tasks;+create trigger trigger_set_owner_for_task+ before insert+ on tasks.tasks+ for each row+execute procedure tasks.fn_set_owner_for_task();++--19.+--Trigger for validating that tag and task belong to the same project (goal_id)+drop trigger if exists trigger_check_tag_task_same_goal on tasks.tasks_to_tags;+drop function if exists tasks.check_tag_task_same_goal();++create or replace function tasks.check_tag_task_same_goal()+returns trigger as $$+declare+ v_tag_goal_id integer;+ v_task_goal_id integer;+begin+ select goal_id into v_tag_goal_id from tasks.tags where id = new.tag_id;+ select goal_id into v_task_goal_id from tasks.tasks where id = new.task_id;++ if v_tag_goal_id is null or v_tag_goal_id != v_task_goal_id then+ raise exception 'Tag (id=%) and task (id=%) belong to different projects', new.tag_id, new.task_id;+ end if;++ return new;+end;+$$ language plpgsql;++drop trigger if exists trigger_check_tag_task_same_goal on tasks.tasks_to_tags;+create trigger trigger_check_tag_task_same_goal+ before insert on tasks.tasks_to_tags+ for each row+execute function tasks.check_tag_task_same_goal();++--20.+-- Remove user from task assignees when removed from project collaboration++drop trigger if exists trigger_remove_user_from_task_assignees on collaboration.users_to_goals;+drop function if exists collaboration.remove_user_from_task_assignees();+++CREATE OR REPLACE FUNCTION collaboration.remove_user_from_task_assignees()+RETURNS TRIGGER AS $$+BEGIN+ DELETE FROM tasks_auth.task_assignee+ WHERE collab_user_id = OLD.user_id+ AND task_id IN (SELECT id FROM tasks.tasks WHERE goal_id = OLD.goal_id);++ RETURN OLD;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS trigger_remove_user_from_task_assignees ON collaboration.users_to_goals;++CREATE TRIGGER trigger_remove_user_from_task_assignees+ BEFORE DELETE+ ON collaboration.users_to_goals+ FOR EACH ROW+EXECUTE FUNCTION collaboration.remove_user_from_task_assignees();++--21.+--Trigger for logging changes in time_entries to history table+create or replace function tasks.log_changes_time_entries()+ returns trigger as+$body$+begin+ insert into history.time_entries (entry_id, edit_date, entry)+ values (old.id, now(), to_jsonb(old));+ new.edited_at = now();+ return new;+end+$body$+ language plpgsql;++drop trigger if exists trigger_log_changes_time_entries on tasks.time_entries;+create trigger trigger_log_changes_time_entries+ before update+ on tasks.time_entries+ for each row+execute procedure tasks.log_changes_time_entries();diff --git a/api/src/tv-modules/auth/AccountDeletion.ts b/api/src/tv-modules/auth/AccountDeletion.tsnew file mode 100644index 0000000..407713c--- /dev/null+++ b/api/src/tv-modules/auth/AccountDeletion.ts@@ -0,0 +1,22 @@+/**+ * Whether people may delete their own account. Off unless ALLOW_ACCOUNT_DELETION=true:+ * on a company install accounts are removed by an admin, not by their owners.+ */+export class AccountDeletion {+ /** How long an emailed account deletion code works. */+ static readonly CODE_TTL_S = 15 * 60;++ static allowed(): boolean {+ return process.env.ALLOW_ACCOUNT_DELETION?.trim().toLowerCase() === 'true';+ }++ static validateOnStartup(): void {+ const raw = process.env.ALLOW_ACCOUNT_DELETION;+ if (raw === undefined || raw.trim() === '') return;++ const normalized = raw.trim().toLowerCase();+ if (normalized !== 'true' && normalized !== 'false') {+ throw new Error(`ALLOW_ACCOUNT_DELETION has unrecognized value "${raw}". Allowed: true, false`);+ }+ }+}diff --git a/api/src/tv-modules/auth/AuthController.ts b/api/src/tv-modules/auth/AuthController.tsindex ab57a75..5c7ffb3 100644--- a/api/src/tv-modules/auth/AuthController.ts+++ b/api/src/tv-modules/auth/AuthController.ts@@ -10,6 +10,7 @@ import {ChangeOwnPasswordByPasswordSchema,ChangeOwnPasswordSchema,ChangePasswordDataScheme,+ DeleteAccountSchema,type PasswordChangeConfirmationMode,ConfirmEmailReqDataSchema,RefreshTokenSchema,@@ -17,8 +18,12 @@ import {type UserDbRecord,type UserJwtPayload,UserJwtPayloadSchema,+ AuthTokenPayloadSchema,+ type ValidateTokenArgs,} from '../../types/auth.types';+import { safeEqual } from '../../utils/crypto';import { generateString, isEmail, time } from '../../utils/helpers';+import { AccountDeletion } from './AccountDeletion';import { LoginMethods } from './LoginMethods';import EnEmailTemplate from './mail/confirm-email-en';import RuEmailTemplate from './mail/confirm-email-ru';@@ -28,6 +33,7 @@ import { OrganizationRepository } from '../organizations/OrganizationRepository'import { GoalsRepository } from '../goals/GoalsRepository';const LOGIN_CODE_TTL_MS = 5 * 60 * 1000;+const LOGIN_CODE_MAX_ATTEMPTS = 5;const PASSWORD_CHANGE_CODE_TTL_S = 15 * 60;const PASSWORD_CHANGE_CODE_RESEND_COOLDOWN_S = 60;// Seeded by migration 0.0.0 (app_permissions.sql) on self-hosted installs.@@ -66,14 +72,15 @@ export default class AuthController {$logger.error('Can not parse JWT payload');}+ // typ keeps the two apart: an access token cannot be exchanged for new tokens, a refresh token cannot authorize requests//@ts-expect-error- const access = jwt.sign(cleanPayload.data!, process.env.JWT_SIGN as string, {+ const access = jwt.sign({ ...cleanPayload.data!, typ: 'access' }, process.env.JWT_SIGN as string, {algorithm: this.jwtAlg,expiresIn: this.jwtExp,});//@ts-expect-error- const refresh = jwt.sign(cleanPayload.data!, process.env.JWT_SIGN as string, {+ const refresh = jwt.sign({ ...cleanPayload.data!, typ: 'refresh' }, process.env.JWT_SIGN as string, {algorithm: this.jwtAlg,expiresIn: this.jwtRefreshExp,});@@ -86,19 +93,28 @@ export default class AuthController {};}- static validateTokens(token: string): Promise<UserJwtPayload | undefined> {+ static validateTokens(args: ValidateTokenArgs): Promise<UserJwtPayload | undefined> {return new Promise((resolve) => {jwt.verify(- token,+ args.token,process.env.JWT_SIGN as string,{ algorithms: [process.env.JWT_ALG as Algorithm] },(err, payload) => {if (err) {- // console.log('Can not verify token', err)resolve(undefined);- } else {- resolve(payload as UserJwtPayload);+ return;}+ // Other JWTs signed with JWT_SIGN (e.g. OAuth state) do not carry a session payload+ const parsed = AuthTokenPayloadSchema.safeParse(payload);+ if (!parsed.success) {+ resolve(undefined);+ return;+ }+ if (parsed.data.typ !== args.type) {+ resolve(undefined);+ return;+ }+ resolve({ id: parsed.data.id, userData: parsed.data.userData });});});@@ -195,6 +211,18 @@ export default class AuthController {});}+ const reservation = await req.appUser.authManager.repository.reserveLoginCodeSend({+ userId: userData.id,+ hourlyLimit: LoginMethods.loginCodeHourlyLimit(),+ });+ if (!reservation.allowed) {+ $logger.warn({ userId: userData.id }, '[AuthController:sendLoginCode] hourly login code limit reached');+ return res.status(429).send({+ message: 'Too many codes requested, try again later.',+ retryAfter: reservation.retryAfterSeconds,+ });+ }+$logger.info(`[AuthController:sendLoginCode] updating login code for user`);await req.appUser.authManager.repository.updateLoginCode(code, email);$logger.info(`[AuthController:sendLoginCode] sending code by email to`);@@ -348,17 +376,24 @@ export default class AuthController {isEmail(data.data.email));- if (!userData || !userData.remember_token?.trim()) {- return res.status(400).end();+ // Unknown email, no pending code and a wrong code all answer the same way+ if (!userData) {+ return res.status(400).send({ message: 'Invalid code' });}- const tokenFromDb = userData.remember_token?.split(':');+ const attempt = await req.appUser.authManager.repository.registerLoginCodeAttempt(userData.id);+ if (!attempt) {+ return res.status(400).send({ message: 'Invalid code' });+ }- if (tokenFromDb?.length !== 2) {- return res.status(400).end();+ // The code stays in place after the limit, so the resend cooldown of sendLoginCode still applies+ if (attempt.attempts > LOGIN_CODE_MAX_ATTEMPTS) {+ return res.status(429).send({ message: 'Too many attempts, get new code' });}- if (tokenFromDb[0] !== data.data.code) {+ const tokenFromDb = attempt.rememberToken.split(':');++ if (tokenFromDb.length !== 2 || !safeEqual(tokenFromDb[0], data.data.code)) {return res.status(400).send({ message: 'Invalid code' });}@@ -368,7 +403,13 @@ export default class AuthController {}// Invalidate code immediately to prevent replay attacks- await req.appUser.authManager.repository.updateLoginCode(null, userData.email);+ const consumed = await req.appUser.authManager.repository.consumeLoginCode({+ userId: userData.id,+ rememberToken: attempt.rememberToken,+ });+ if (!consumed) {+ return res.status(400).send({ message: 'Invalid code' });+ }if (userData.block) {if (!userData.confirm_email_code) {@@ -583,6 +624,7 @@ export default class AuthController {const remindPasswordBody = `<html><body><p><a href="${remindPasswordUrl}"> Reset password link! </a></p>+ <p>The link expires in 15 minutes.</p></body></html>`;@@ -607,20 +649,33 @@ export default class AuthController {return res.status(400).send();}+ // Unknown login, wrong, used and expired codes answer alike, so the reason never hints at a valid code+ const invalidCode = () => res.status(400).send({ reason: 'invalid_or_expired_code' });+const userData = await req.appUser.authManager.repository.getUserByLogin(parsedData.data.login);if (!userData) {- return res.status(400).send();+ return invalidCode();}- if (userData.remind_password_code !== parsedData.data.code) {- return res.status(400).send();+ if (!userData.remind_password_code || !safeEqual(userData.remind_password_code, parsedData.data.code)) {+ return invalidCode();}if (parsedData.data.password !== parsedData.data.passwordRepeat) {return res.status(400).send();}+ // Same lifetime as the password-change code: the column is shared by both flows+ const consumed = await req.appUser.authManager.repository.consumeReminderCode({+ userId: userData.id,+ code: parsedData.data.code,+ issuedAfter: Math.floor(Date.now() / 1000) - PASSWORD_CHANGE_CODE_TTL_S,+ });+ if (!consumed) {+ return invalidCode();+ }+const passwordHash = hashSync(parsedData.data.password, 10);const result = await req.appUser.authManager.repository.updateUserPassword(passwordHash, userData.id);@@ -630,7 +685,9 @@ export default class AuthController {return res.status(500).send();}- await req.appUser.authManager.repository.setReminderCodeAndTime(userData.email, null, null);+ // A reset is account recovery: every session ends, including any held by whoever had access before+ await req.appUser.authManager.sessionStorage.deleteAllSessions(userData.id);+ this.clearRefreshToken(res);return res.status(200).send({ reset: true });};@@ -663,8 +720,8 @@ export default class AuthController {return res.status(400).send({ message: 'Invalid refresh token' });}- const cookiePayload = cookieToken ? await AuthController.validateTokens(cookieToken) : undefined;- const bodyPayload = bodyToken ? await AuthController.validateTokens(bodyToken) : undefined;+ const cookiePayload = cookieToken ? await AuthController.validateTokens({ token: cookieToken, type: 'refresh' }) : undefined;+ const bodyPayload = bodyToken ? await AuthController.validateTokens({ token: bodyToken, type: 'refresh' }) : undefined;const payload = cookiePayload ?? bodyPayload;$logger.info(`Refresh token source: ${cookiePayload ? 'cookie' : bodyPayload ? 'body' : 'none valid'}` +@@ -889,39 +946,51 @@ export default class AuthController {const code = generateString(12);+ // Saved before sending, so the emailed code is never one the server does not know+ const insertCode = await req.appUser.authManager.repository.addDeleteAccountCode({ code, userId });+ if (!insertCode) {+ $logger.error(`Can not insert account deletion code for user`);+ return res.status(500).end();+ }+const sendResult = await Email.send({- text: code,- to: userEmail, //'[email protected]',- subject: 'Account deletion code!',+ text: `Your TaskView account deletion code is ${code}\n\nThe code expires in 15 minutes.\n\nIf you didn't request this, ignore this email and consider changing your password.`,+ to: userEmail,+ subject: 'Account deletion code',from: process.env.SMTP_FROM_EMAIL as string,});if (!sendResult) {$logger.error(`Can not send account deletion code for user`);}- const insertCode = await req.appUser.authManager.repository.addDeleteAccountCode(code, userId);-- if (!insertCode) {- $logger.error(`Can not insert account deletion code for user`);- return res.status(500).end();- }return res.status(200).end();};+ getAccountDeletionOptions = async (_req: Request, res: Response) => {+ return res.status(200).send({ allowed: AccountDeletion.allowed() });+ };+deleteUserAccaunt = async (req: Request, res: Response) => {- const { code } = req.body;+ const invalidCode = () => res.status(400).send({ reason: 'invalid_or_expired_code' });++ const parsed = DeleteAccountSchema.safeParse(req.body);+ if (!parsed.success) {+ return invalidCode();+ }const userId = req.appUser.getUserData()?.id;if (!userId) {$logger.fatal(`Request for account deletion without userId in request`);return res.status(400).end();}- const deleteResult = await req.appUser.authManager.repository.deleteUserAccount(code, userId);-- if (!deleteResult) {- $logger.error(`Can not delete user account for code ${code}`);- return res.status(500).end();+ const deleted = await req.appUser.authManager.repository.deleteAccountByCode({+ userId,+ code: parsed.data.code,+ ttlSeconds: AccountDeletion.CODE_TTL_S,+ });+ if (!deleted) {+ return invalidCode();}- return res.status(200).end();+ return res.tvJson({ del: true });};}diff --git a/api/src/tv-modules/auth/AuthModel.ts b/api/src/tv-modules/auth/AuthModel.tsindex 7e2f778..66a5a15 100644--- a/api/src/tv-modules/auth/AuthModel.ts+++ b/api/src/tv-modules/auth/AuthModel.ts@@ -1,8 +1,8 @@-import { eq, sql } from 'drizzle-orm';-import { CollaborationUsersSchema, OrganizationMembersSchema, ScimUsersSchema, SsoIdentitiesSchema, UsersSchema } from 'taskview-db-schemas';+import { and, count, eq, exists, gt, gte, isNotNull, lt, sql } from 'drizzle-orm';+import { AccountDeletionSchema, CollaborationUsersSchema, LoginCodeRequestsSchema, OrganizationMembersSchema, ScimUsersSchema, SsoIdentitiesSchema, UsersSchema } from 'taskview-db-schemas';import { Database } from '../../modules/db';import { $logger } from '../../modules/logget';-import type { RegisterUserInDb, UpdateUserCredentialsArgs, UpdateUserEmailArgs, UpdateUserCredentialsResult, UserDbRecord } from '../../types/auth.types';+import type { AddDeleteAccountCodeArgs, ConsumeLoginCodeArgs, DeleteAccountByCodeArgs, ConsumeReminderCodeArgs, LoginCodeAttempt, LoginCodeSendReservation, RegisterUserInDb, ReserveLoginCodeSendArgs, UpdateUserCredentialsArgs, UpdateUserEmailArgs, UpdateUserCredentialsResult, UserDbRecord } from '../../types/auth.types';export default class AuthModel {private readonly db: Database;@@ -13,13 +13,13 @@ export default class AuthModel {async getUserByLogin(login: string, isEmail: boolean = false): Promise<UserDbRecord | false> {const field = isEmail ? 'email' : 'login';- // Emails are case-insensitive; legacy rows may still hold mixed case, oldest account wins+ // Login and email are stored lowercase; legacy rows may still hold mixed case, oldest account winsconst query = isEmail- ? 'select * from tv_auth.users where lower(email) = lower($1) order by id limit 1'- : 'select * from tv_auth.users where login = $1';+ ? 'select * from tv_auth.users where lower(email) = $1 order by id limit 1'+ : 'select * from tv_auth.users where lower(login) = $1 order by id limit 1';$logger.info({ field }, `[AuthModel:getUserByLogin] field`);try {- const data = await this.db.query<UserDbRecord>(query, [login]);+ const data = await this.db.query<UserDbRecord>(query, [login.toLowerCase()]);$logger.info({ login }, `[AuthModel:getUserByLogin] ${query}`);$logger.info(data, `[AuthModel:getUserByLogin] data`);@@ -39,19 +39,88 @@ export default class AuthModel {async updateLoginCode(code: string | null, email: string): Promise<boolean> {if (!email) return false;- //remember_token is used as login code+ //remember_token is used as login code; a new code starts with a fresh attempt budgettry {- const data = await this.db.query(`update tv_auth.users set remember_token = $1 where email = $2`, [- code,- email,- ]);- return !!(data.rowCount && data.rowCount > 0);+ const rows = await this.db.dbDrizzle+ .update(UsersSchema)+ .set({ rememberToken: code, loginCodeAttempts: 0 })+ .where(sql`lower(${UsersSchema.email}) = ${email.toLowerCase()}`)+ .returning({ id: UsersSchema.id });+ return rows.length > 0;} catch (error: unknown) {$logger.error(error, 'Can not update login code');return false;}+ }++ /**+ * Counts one guess against the user's current login code before it is compared.+ * The increment is a single UPDATE, so concurrent guesses each get their own attempt number.+ */+ async registerLoginCodeAttempt(userId: number): Promise<LoginCodeAttempt | null> {+ try {+ const [row] = await this.db.dbDrizzle+ .update(UsersSchema)+ .set({ loginCodeAttempts: sql`${UsersSchema.loginCodeAttempts} + 1` })+ .where(and(eq(UsersSchema.id, userId), isNotNull(UsersSchema.rememberToken)))+ .returning({ rememberToken: UsersSchema.rememberToken, attempts: UsersSchema.loginCodeAttempts });+ if (!row?.rememberToken) return null;+ return { rememberToken: row.rememberToken, attempts: row.attempts };+ } catch (error: unknown) {+ $logger.error(error, 'Can not register login code attempt');+ return null;+ }+ }- return true;+ /**+ * Records an emailed login code against the hourly cap, or reports when the next one is allowed.+ * The user row is locked for the check-and-insert, so concurrent requests cannot both take the last slot.+ */+ async reserveLoginCodeSend(args: ReserveLoginCodeSendArgs): Promise<LoginCodeSendReservation> {+ return this.db.dbDrizzle.transaction(async (tx) => {+ await tx+ .select({ id: UsersSchema.id })+ .from(UsersSchema)+ .where(eq(UsersSchema.id, args.userId))+ .for('update');++ await tx+ .delete(LoginCodeRequestsSchema)+ .where(lt(LoginCodeRequestsSchema.requestedAt, sql`now() - interval '1 hour'`));++ const [window] = await tx+ .select({+ sent: count(),+ retryAfterSeconds: sql<string | null>`ceil(extract(epoch from (min(${LoginCodeRequestsSchema.requestedAt}) + interval '1 hour' - now())))`,+ })+ .from(LoginCodeRequestsSchema)+ .where(eq(LoginCodeRequestsSchema.userId, args.userId));++ if ((window?.sent ?? 0) >= args.hourlyLimit) {+ return { allowed: false, retryAfterSeconds: Math.max(1, Number(window?.retryAfterSeconds ?? 0)) };+ }++ await tx.insert(LoginCodeRequestsSchema).values({ userId: args.userId });+ return { allowed: true };+ });+ }++ /**+ * Clears the login code only if it is still the one that was checked,+ * so two concurrent requests with the right code cannot both log in.+ */+ async consumeLoginCode(args: ConsumeLoginCodeArgs): Promise<boolean> {+ try {+ const rows = await this.db.dbDrizzle+ .update(UsersSchema)+ .set({ rememberToken: null })+ .where(and(eq(UsersSchema.id, args.userId), eq(UsersSchema.rememberToken, args.rememberToken)))+ .returning({ id: UsersSchema.id });+ return rows.length > 0;+ } catch (error: unknown) {+ $logger.error(error, 'Can not consume login code');+ return false;+ }}async registerUserInDb(data: RegisterUserInDb): Promise<number | false> {@@ -59,7 +128,13 @@ export default class AuthModel {try {const query = `INSERT INTO tv_auth.users (login, email, password, confirm_email_code, block)VALUES ($1, $2, $3, $4, $5) RETURNING id;`;- const data = await this.db.query<{ id: number }>(query, [login, email, password, confirmEmailCode, block]);+ const data = await this.db.query<{ id: number }>(query, [+ login.toLowerCase(),+ email.toLowerCase(),+ password,+ confirmEmailCode,+ block,+ ]);if (data?.rows && data.rows.length > 0) {$logger.debug('User registration success');@@ -110,9 +185,9 @@ export default class AuthModel {}async fetchUserByEmail(email: string): Promise<UserDbRecord | false> {- const query = 'SELECT * FROM tv_auth.users WHERE email = $1;';+ const query = 'SELECT * FROM tv_auth.users WHERE lower(email) = $1 ORDER BY id LIMIT 1;';try {- const result = await this.db.query(query, [email]);+ const result = await this.db.query(query, [email.toLowerCase()]);if (result.rows.length > 0) {return result.rows[0];}@@ -130,7 +205,7 @@ export default class AuthModel {const result = await this.db.dbDrizzle.update(UsersSchema).set({ confirmEmailCode: null, block: 0 })- .where(eq(UsersSchema.email, email));+ .where(sql`lower(${UsersSchema.email}) = ${email.toLowerCase()}`);return (result.rowCount ?? 0) > 0;} catch (error) {$logger.error(error, `Error marking email confirmed for ${email}`);@@ -141,10 +216,10 @@ export default class AuthModel {async confirmEmail(login: string, code: string, block: number): Promise<boolean> {const query = `UPDATE tv_auth.usersSET confirm_email_code = NULL, block = $1- WHERE login = $2 AND confirm_email_code = $3`;+ WHERE lower(login) = $2 AND confirm_email_code = $3`;try {- const result = await this.db.query(query, [block, login, code]);+ const result = await this.db.query(query, [block, login.toLowerCase(), code]);return !!(result.rowCount && result.rowCount > 0);} catch (_error) {$logger.error('Error confirming email', { login, code });@@ -152,6 +227,30 @@ export default class AuthModel {}}+ /**+ * Clears the password reminder code only if it is still the given, unexpired one.+ * One UPDATE decides, so two concurrent requests with the same code cannot both pass.+ */+ async consumeReminderCode(args: ConsumeReminderCodeArgs): Promise<boolean> {+ try {+ const rows = await this.db.dbDrizzle+ .update(UsersSchema)+ .set({ remindPasswordCode: null, remindPasswordTime: null })+ .where(+ and(+ eq(UsersSchema.id, args.userId),+ eq(UsersSchema.remindPasswordCode, args.code),+ gte(UsersSchema.remindPasswordTime, args.issuedAfter)+ )+ )+ .returning({ id: UsersSchema.id });+ return rows.length > 0;+ } catch (error: unknown) {+ $logger.error(error, 'Can not consume password reminder code');+ return false;+ }+ }+async setReminderCodeAndTime(email: string, code: string | null, time: number | null): Promise<boolean> {if (!email) return false;@@ -160,11 +259,11 @@ export default class AuthModel {if (code === null && time === null) {query =- 'UPDATE tv_auth.users SET remind_password_code = NULL, remind_password_time = NULL WHERE email = $1';- args = [email];+ 'UPDATE tv_auth.users SET remind_password_code = NULL, remind_password_time = NULL WHERE lower(email) = $1';+ args = [email.toLowerCase()];} else {- query = 'UPDATE tv_auth.users SET remind_password_code = $1, remind_password_time = $2 WHERE email = $3';- args = [code, time, email];+ query = 'UPDATE tv_auth.users SET remind_password_code = $1, remind_password_time = $2 WHERE lower(email) = $3';+ args = [code, time, email.toLowerCase()];}try {@@ -177,23 +276,25 @@ export default class AuthModel {}async updateUserCredentials(args: UpdateUserCredentialsArgs): Promise<UpdateUserCredentialsResult> {+ const login = args.login.toLowerCase();+ const email = args.email.toLowerCase();try {await this.db.dbDrizzle.transaction(async (tx) => {await tx.update(UsersSchema)- .set({ login: args.login, email: args.email, password: args.passwordHash })+ .set({ login, email, password: args.passwordHash }).where(eq(UsersSchema.id, args.userId));await tx.update(OrganizationMembersSchema)- .set({ email: args.email })+ .set({ email }).where(sql`lower(${OrganizationMembersSchema.email}) = ${args.oldEmail.toLowerCase()}`);await tx.update(CollaborationUsersSchema)- .set({ email: args.email })+ .set({ email }).where(sql`lower(${CollaborationUsersSchema.email}) = ${args.oldEmail.toLowerCase()}`);await tx.update(SsoIdentitiesSchema)- .set({ email: args.email })+ .set({ email }).where(eq(SsoIdentitiesSchema.userId, args.userId));});return 'ok';@@ -209,27 +310,28 @@ export default class AuthModel {}async updateUserEmail(args: UpdateUserEmailArgs): Promise<UpdateUserCredentialsResult> {+ const email = args.email.toLowerCase();try {await this.db.dbDrizzle.transaction(async (tx) => {await tx.update(UsersSchema)- .set({ email: args.email })+ .set({ email }).where(eq(UsersSchema.id, args.userId));await tx.update(OrganizationMembersSchema)- .set({ email: args.email })+ .set({ email }).where(sql`lower(${OrganizationMembersSchema.email}) = ${args.oldEmail.toLowerCase()}`);await tx.update(CollaborationUsersSchema)- .set({ email: args.email })+ .set({ email }).where(sql`lower(${CollaborationUsersSchema.email}) = ${args.oldEmail.toLowerCase()}`);await tx.update(ScimUsersSchema)- .set({ memberEmail: args.email })+ .set({ memberEmail: email }).where(sql`lower(${ScimUsersSchema.memberEmail}) = ${args.oldEmail.toLowerCase()}`);await tx.update(SsoIdentitiesSchema)- .set({ email: args.email })+ .set({ email }).where(eq(SsoIdentitiesSchema.userId, args.userId));});return 'ok';@@ -265,38 +367,42 @@ export default class AuthModel {}}- async addDeleteAccountCode(code: string, userId: number): Promise<boolean> {+ async addDeleteAccountCode(args: AddDeleteAccountCodeArgs): Promise<boolean> {try {- const queryDeleteOldData = 'delete from tv_auth.account_deletion where user_id = $1';- await this.db.query(queryDeleteOldData, [userId]);- const insertQuery = 'insert into tv_auth.account_deletion (code, user_id) values ($1,$2)';- const insertResult = await this.db.query(insertQuery, [code, userId]);- return !!(insertResult.rowCount && insertResult.rowCount > 0);- } catch (error: any) {- $logger.error(`Can can not complete delete code for account ${userId}`, {- errorMessage: error.message,- errorStack: error.stack,+ return await this.db.dbDrizzle.transaction(async (tx) => {+ await tx.delete(AccountDeletionSchema).where(eq(AccountDeletionSchema.userId, args.userId));+ const rows = await tx+ .insert(AccountDeletionSchema)+ .values({ userId: args.userId, code: args.code })+ .returning({ id: AccountDeletionSchema.id });+ return rows.length > 0;});+ } catch (error: unknown) {+ $logger.error(error, 'Can not save account deletion code');return false;}}- async deleteUserAccount(code: string, userId: number): Promise<boolean> {+ async deleteAccountByCode(args: DeleteAccountByCodeArgs): Promise<boolean> {try {- const query = 'select user_id from tv_auth.account_deletion where code = $1';- const codeData = await this.db.query(query, [code]);- if (codeData.rows.length > 0 && userId === codeData.rows[0]['user_id']) {- const deleteUser = await this.db.query('delete from tv_auth.users where id = $1', [- codeData.rows[0]['user_id'],- ]);- return !!(deleteUser.rowCount && deleteUser.rowCount > 0);- } else {- $logger.error(`Can not fetch user account for code ${code}`);- }- } catch (_err: any) {- $logger.error(`Can not delete user account for code ${code}`);+ const validCode = this.db.dbDrizzle+ .select({ id: AccountDeletionSchema.id })+ .from(AccountDeletionSchema)+ .where(+ and(+ eq(AccountDeletionSchema.userId, args.userId),+ eq(AccountDeletionSchema.code, args.code),+ gt(AccountDeletionSchema.createdAt, sql`now() - make_interval(secs => ${args.ttlSeconds})`)+ )+ );+ const rows = await this.db.dbDrizzle+ .delete(UsersSchema)+ .where(and(eq(UsersSchema.id, args.userId), exists(validCode)))+ .returning({ id: UsersSchema.id });+ return rows.length > 0;+ } catch (error: unknown) {+ $logger.error(error, 'Can not delete user account');return false;}- return false;}}diff --git a/api/src/tv-modules/auth/AuthRoutes.ts b/api/src/tv-modules/auth/AuthRoutes.tsindex 21a2cf1..e2a237a 100644--- a/api/src/tv-modules/auth/AuthRoutes.ts+++ b/api/src/tv-modules/auth/AuthRoutes.ts@@ -4,6 +4,7 @@ import AuthController from './AuthController';import { IsLoggedIn } from './middlewares/is-logged-in';import { RejectApiTokenAuth } from '../api-tokens/middlewares/RejectApiTokenAuth';import { RequireAnyLoginMethod, RequireLoginMethod, RequireSocialProvider } from './middlewares/require-login-method';+import { RequireAccountDeletion } from './middlewares/require-account-deletion';import passport from './strategies/passport-login';import { ExternalProviderScope } from './strategies/external-auth.types';export default class AuthRoutes implements Routable {@@ -37,8 +38,9 @@ export default class AuthRoutes implements Routable {this.router.post('/credentials/change', [IsLoggedIn, RejectApiTokenAuth], this.authController.changeDefaultUserCredentials);this.router.post('/logout', [IsLoggedIn], this.authController.logout);this.router.post('/refresh/token', this.authController.refreshTokens);- this.router.post('/delete/account/code', [IsLoggedIn], this.authController.sendDeleteAccountCode);- this.router.post('/delete/account', [IsLoggedIn], this.authController.deleteUserAccaunt);+ this.router.get('/delete/account/options', [IsLoggedIn], this.authController.getAccountDeletionOptions);+ this.router.post('/delete/account/code', [IsLoggedIn, RejectApiTokenAuth, RequireAccountDeletion], this.authController.sendDeleteAccountCode);+ this.router.post('/delete/account', [IsLoggedIn, RejectApiTokenAuth, RequireAccountDeletion], this.authController.deleteUserAccaunt);this.router.get('/provider/:providerName',diff --git a/api/src/tv-modules/auth/LoginMethods.ts b/api/src/tv-modules/auth/LoginMethods.tsindex 17c0a13..1bc6dc9 100644--- a/api/src/tv-modules/auth/LoginMethods.ts+++ b/api/src/tv-modules/auth/LoginMethods.ts@@ -1,4 +1,7 @@import type { LoginMethod } from '../../types/auth.types';+import { parsePositiveInt } from '../../utils/helpers';++const DEFAULT_LOGIN_CODE_HOURLY_LIMIT = 5;export class LoginMethods {static readonly ALL: LoginMethod[] = ['magic-link', 'password', 'sso', 'social'];@@ -19,7 +22,17 @@ export class LoginMethods {return process.env.ALLOW_PUBLIC_REGISTRATION?.trim().toLowerCase() !== 'false';}+ /** Max login codes one account may request by email per hour. */+ static loginCodeHourlyLimit(): number {+ return parsePositiveInt(process.env.LOGIN_CODE_HOURLY_LIMIT) ?? DEFAULT_LOGIN_CODE_HOURLY_LIMIT;+ }+static validateOnStartup(): void {+ const limitRaw = process.env.LOGIN_CODE_HOURLY_LIMIT;+ if (limitRaw !== undefined && limitRaw.trim() !== '' && parsePositiveInt(limitRaw) === null) {+ throw new Error(`LOGIN_CODE_HOURLY_LIMIT has unrecognized value "${limitRaw}". Expected a positive integer`);+ }+const registrationRaw = process.env.ALLOW_PUBLIC_REGISTRATION;if (registrationRaw !== undefined && registrationRaw.trim() !== '') {const normalized = registrationRaw.trim().toLowerCase();diff --git a/api/src/tv-modules/auth/SessionStorage.ts b/api/src/tv-modules/auth/SessionStorage.tsindex dc3a7b8..f2d2bbe 100644--- a/api/src/tv-modules/auth/SessionStorage.ts+++ b/api/src/tv-modules/auth/SessionStorage.ts@@ -1,11 +1,29 @@-import { and, eq, ne } from 'drizzle-orm'+import { and, eq, gt, ne, sql } from 'drizzle-orm'import { UserTokensSchema } from 'taskview-db-schemas'import { Database } from '../../modules/db'-import { callWithCatch, parseDeviceName } from '../../utils/helpers'+import { callWithCatch, parseDeviceName, parsePositiveInt } from '../../utils/helpers'++const DEFAULT_SESSION_MAX_AGE_DAYS = 90export default class SessionStorage {private readonly db: Database+ /** A session ends this many days after sign-in, however often its tokens are refreshed. */+ static maxAgeDays(): number {+ return parsePositiveInt(process.env.SESSION_MAX_AGE_DAYS) ?? DEFAULT_SESSION_MAX_AGE_DAYS+ }++ static validateOnStartup(): void {+ const raw = process.env.SESSION_MAX_AGE_DAYS+ if (raw !== undefined && raw.trim() !== '' && parsePositiveInt(raw) === null) {+ throw new Error(`SESSION_MAX_AGE_DAYS has unrecognized value "${raw}". Expected a positive integer`)+ }+ }++ private notExpired() {+ return gt(UserTokensSchema.timeCreation, sql`now() - make_interval(days => ${SessionStorage.maxAgeDays()})`)+ }+constructor() {this.db = Database.getInstance()}@@ -28,7 +46,7 @@ export default class SessionStorage {const result = await callWithCatch(() =>this.db.dbDrizzle.select({ id: UserTokensSchema.id }).from(UserTokensSchema)- .where(eq(UserTokensSchema.id, sessionId))+ .where(and(eq(UserTokensSchema.id, sessionId), this.notExpired())))return !!(result && result.length > 0)}@@ -72,7 +90,7 @@ export default class SessionStorage {const result = await callWithCatch(() =>this.db.dbDrizzle.select().from(UserTokensSchema)- .where(eq(UserTokensSchema.userId, userId))+ .where(and(eq(UserTokensSchema.userId, userId), this.notExpired())).orderBy(UserTokensSchema.lastUsedAt))return result ?? []diff --git a/api/src/tv-modules/auth/__tests__/AccountDeletion.test.ts b/api/src/tv-modules/auth/__tests__/AccountDeletion.test.tsnew file mode 100644index 0000000..71ea318--- /dev/null+++ b/api/src/tv-modules/auth/__tests__/AccountDeletion.test.ts@@ -0,0 +1,56 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { Request, Response } from 'express';+import { AccountDeletion } from '../AccountDeletion';+import { RequireAccountDeletion } from '../middlewares/require-account-deletion';++const runWith = (value: string | undefined) => {+ vi.stubEnv('ALLOW_ACCOUNT_DELETION', value);+ const next = vi.fn();+ const send = vi.fn();+ const res = { status: vi.fn(() => ({ send })) } as unknown as Response;++ RequireAccountDeletion({} as Request, res, next);+ return { next, res };+};++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('RequireAccountDeletion', () => {+ it('refuses when ALLOW_ACCOUNT_DELETION is not set: deletion is off by default', () => {+ const { next, res } = runWith(undefined);+ expect(next).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(403);+ });++ it('refuses when ALLOW_ACCOUNT_DELETION=false', () => {+ const { next, res } = runWith('false');+ expect(next).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(403);+ });++ it('lets the request through when ALLOW_ACCOUNT_DELETION=true, in any case and with spaces', () => {+ for (const value of ['true', ' TRUE ']) {+ const { next, res } = runWith(value);+ expect(next).toHaveBeenCalled();+ expect(res.status).not.toHaveBeenCalled();+ }+ });+});++describe('AccountDeletion.validateOnStartup', () => {+ it('accepts true, false and an unset value', () => {+ for (const value of [undefined, '', 'true', 'false', ' False ']) {+ vi.stubEnv('ALLOW_ACCOUNT_DELETION', value);+ expect(() => AccountDeletion.validateOnStartup()).not.toThrow();+ }+ });++ it('stops the server on a value that is neither true nor false', () => {+ for (const value of ['yes', '1', 'on']) {+ vi.stubEnv('ALLOW_ACCOUNT_DELETION', value);+ expect(() => AccountDeletion.validateOnStartup()).toThrow(/ALLOW_ACCOUNT_DELETION/);+ }+ });+});diff --git a/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts b/api/src/tv-modules/auth/__tests__/AuthModel.spec.tsindex 9af9c8f..7c3342a 100644--- a/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts+++ b/api/src/tv-modules/auth/__tests__/AuthModel.spec.ts@@ -295,7 +295,7 @@ describe('AuthModel Integration Tests', () => {expect(userId).toBeTruthy();if (userId) {- const result = await authModel.addDeleteAccountCode(`${emailNum}some-code`, userId);+ const result = await authModel.addDeleteAccountCode({ code: `${emailNum}some-code`, userId });expect(result).toBe(true);const db = Database.getInstance();const codeResult = await db.query('select * from tv_auth.account_deletion where code = $1', [@@ -326,14 +326,14 @@ describe('AuthModel Integration Tests', () => {expect(userId).toBeTruthy();if (userId) {- const result = await authModel.addDeleteAccountCode(code, userId);+ const result = await authModel.addDeleteAccountCode({ code, userId });expect(result).toBe(true);const codeResult = await db.query('select * from tv_auth.account_deletion where code = $1', [code]);expect(codeResult.rows[0].user_id).toBe(userId);expect(codeResult.rows[0].code).toBe(code);}- const deleteResult = await authModel.deleteUserAccount(code, userId);+ const deleteResult = await authModel.deleteAccountByCode({ code, userId, ttlSeconds: 15 * 60 });expect(deleteResult).toBe(true);const codeResult = await db.query('select * from tv_auth.account_deletion where code = $1', [code]);diff --git a/api/src/tv-modules/auth/middlewares/is-logged-in.ts b/api/src/tv-modules/auth/middlewares/is-logged-in.tsindex 6436ada..bdfeffe 100644--- a/api/src/tv-modules/auth/middlewares/is-logged-in.ts+++ b/api/src/tv-modules/auth/middlewares/is-logged-in.ts@@ -8,7 +8,7 @@ export const IsLoggedIn = async (req: Request, res: Response, next: NextFunctionconst token = req.headers['authorization']?.split(' ')[1];if (token) {- const userPayload = await AuthController.validateTokens(token);+ const userPayload = await AuthController.validateTokens({ token, type: 'access' });if (userPayload&& req.appUser.getTokenId() === userPayload.iddiff --git a/api/src/tv-modules/auth/middlewares/require-account-deletion.ts b/api/src/tv-modules/auth/middlewares/require-account-deletion.tsnew file mode 100644index 0000000..0c52b65--- /dev/null+++ b/api/src/tv-modules/auth/middlewares/require-account-deletion.ts@@ -0,0 +1,9 @@+import type { NextFunction, Request, Response } from 'express';+import { AccountDeletion } from '../AccountDeletion';++export const RequireAccountDeletion = (_req: Request, res: Response, next: NextFunction) => {+ if (!AccountDeletion.allowed()) {+ return res.status(403).send();+ }+ return next();+};diff --git a/api/src/tv-modules/automations/automations/KanbanAutomations.ts b/api/src/tv-modules/automations/automations/KanbanAutomations.tsindex 49bd881..bbef122 100644--- a/api/src/tv-modules/automations/automations/KanbanAutomations.ts+++ b/api/src/tv-modules/automations/automations/KanbanAutomations.ts@@ -26,7 +26,7 @@ export const kanbanAutomations: AutomationModuleDefinition = {],dataSources: {'kanban.statuses': {- viewPermissions: [GoalPermissions.KANBAN_CAN_VIEW, GoalPermissions.KANBAN_CAN_MANAGE],+ viewPermissions: [GoalPermissions.KANBAN_CAN_VIEW],load: async ({ actor, goalId }) => {const statuses = await actor.kanbanManager.getAllStatusesForGoal(goalId);return statuses.map((status) => ({ id: status.id, label: status.name }));diff --git a/api/src/tv-modules/automations/automations/TagsAutomations.ts b/api/src/tv-modules/automations/automations/TagsAutomations.tsindex 97ade50..27e8ef5 100644--- a/api/src/tv-modules/automations/automations/TagsAutomations.ts+++ b/api/src/tv-modules/automations/automations/TagsAutomations.ts@@ -33,7 +33,7 @@ export const tagsAutomations: AutomationModuleDefinition = {],dataSources: {'tags.goalTags': {- viewPermissions: [GoalPermissions.TASKS_CAN_WATCH_TAGS, GoalPermissions.TASKS_CAN_EDIT_TAGS],+ viewPermissions: [GoalPermissions.TASKS_CAN_WATCH_TAGS],load: async ({ goalId }) => {const tags = await new AutomationsRepository().fetchGoalTags(goalId);return tags.map((tag) => ({ id: tag.id, label: tag.name, color: tag.color }));diff --git a/api/src/tv-modules/automations/middlewares/require-automation-permission.ts b/api/src/tv-modules/automations/middlewares/require-automation-permission.tsindex 5508d8a..22e205d 100644--- a/api/src/tv-modules/automations/middlewares/require-automation-permission.ts+++ b/api/src/tv-modules/automations/middlewares/require-automation-permission.ts@@ -1,7 +1,6 @@import type { NextFunction, Request, Response } from 'express';import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';import { $logger } from '../../../modules/logget';-import { GoalPermissions } from '../../../types/auth.types';import { logError } from '../../../utils/api';import type { RequireAutomationPermissionArgs } from '../types';@@ -19,10 +18,7 @@ export function requireAutomationPermission({ permission, resolveGoalId }: Requireturn res.status(500).end();}- const granted =- permissions.hasPermissions(permission) ||- (permission === GoalPermissions.AUTOMATION_CAN_VIEW && permissions.hasPermissions(GoalPermissions.AUTOMATION_CAN_MANAGE));- if (granted) return next();+ if (permissions.hasPermissions(permission)) return next();return res.status(403).end();};}diff --git a/api/src/tv-modules/collaboration-roles/middlewares/CanAddCollaborationRoles.ts b/api/src/tv-modules/collaboration-roles/middlewares/CanAddCollaborationRoles.tsindex 389a1ad..012e5ae 100644--- a/api/src/tv-modules/collaboration-roles/middlewares/CanAddCollaborationRoles.ts+++ b/api/src/tv-modules/collaboration-roles/middlewares/CanAddCollaborationRoles.ts@@ -1,5 +1,6 @@import type { NextFunction, Request, Response } from 'express';import { $logger } from '../../../modules/logget';+import { GoalPermissions } from '../../../types/auth.types';export const CanAddCollaborationRoles = async (req: Request, res: Response, next: NextFunction) => {const goalId = req.body.goalId;@@ -15,7 +16,12 @@ export const CanAddCollaborationRoles = async (req: Request, res: Response, nextreturn res.status(500).end();}- if (goal.owner === req.appUser.getUserData()?.id) {+ if (goal.owner !== req.appUser.getUserData()?.id) {+ return res.status(403).end();+ }++ const permissions = await req.appUser.permissionsFetcher.getCheckerForGoal(goal.id);+ if (permissions.hasPermissions(GoalPermissions.GOAL_CAN_MANAGE_USERS)) {return next();}diff --git a/api/src/tv-modules/collaboration-roles/middlewares/CanDeleteCollaborationRoles.ts b/api/src/tv-modules/collaboration-roles/middlewares/CanDeleteCollaborationRoles.tsindex 554e1e3..3f60174 100644--- a/api/src/tv-modules/collaboration-roles/middlewares/CanDeleteCollaborationRoles.ts+++ b/api/src/tv-modules/collaboration-roles/middlewares/CanDeleteCollaborationRoles.ts@@ -1,6 +1,7 @@import { type } from 'arktype';import type { NextFunction, Request, Response } from 'express';import { $logger } from '../../../modules/logget';+import { GoalPermissions } from '../../../types/auth.types';import { CollaborationArkTypeDeleteRoleFromGoal } from '../../collaboration/collaboration.server.types';export const CanDeleteCollaborationRoles = async (req: Request, res: Response, next: NextFunction) => {@@ -20,7 +21,12 @@ export const CanDeleteCollaborationRoles = async (req: Request, res: Response, n}//Only owners can manage roles itself- if (goal.owner === req.appUser.getUserData()?.id) {+ if (goal.owner !== req.appUser.getUserData()?.id) {+ return res.status(403).end();+ }++ const permissions = await req.appUser.permissionsFetcher.getCheckerForGoal(goal.id);+ if (permissions.hasPermissions(GoalPermissions.GOAL_CAN_MANAGE_USERS)) {return next();}diff --git a/api/src/tv-modules/collaboration-roles/middlewares/CanFetchRolesPermissionsCollaborationRoles.ts b/api/src/tv-modules/collaboration-roles/middlewares/CanFetchRolesPermissionsCollaborationRoles.tsindex 46bdc99..ceae3a2 100644--- a/api/src/tv-modules/collaboration-roles/middlewares/CanFetchRolesPermissionsCollaborationRoles.ts+++ b/api/src/tv-modules/collaboration-roles/middlewares/CanFetchRolesPermissionsCollaborationRoles.ts@@ -12,17 +12,6 @@ export const CanFetchRolesPermissionsCollaborationRoles = async (req: Request, rreturn res.status(400).end();}- const goal = await req.appUser.goalsManager.goalsRepository.fetchGoalById(+goalId);-- if (!goal) {- $logger.error('Can not get goal for CanFetchRolesPermissionsCollaborationRoles middleware');- return res.status(500).end();- }-- if (goal.owner === req.appUser.getUserData()?.id) {- return next();- }-const permissions = await req.appUser.permissionsFetcher.getPermissionsForType(Number(goalId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL).catch(logError);diff --git a/api/src/tv-modules/collaboration-roles/middlewares/CanToggleRolesPermissionsCollaborationRoles.ts b/api/src/tv-modules/collaboration-roles/middlewares/CanToggleRolesPermissionsCollaborationRoles.tsindex 1d6aa02..2083114 100644--- a/api/src/tv-modules/collaboration-roles/middlewares/CanToggleRolesPermissionsCollaborationRoles.ts+++ b/api/src/tv-modules/collaboration-roles/middlewares/CanToggleRolesPermissionsCollaborationRoles.ts@@ -1,5 +1,6 @@import type { NextFunction, Request, Response } from 'express';import { $logger } from '../../../modules/logget';+import { GoalPermissions } from '../../../types/auth.types';export const CanToggleRolesPermissionsCollaborationRoles = async (req: Request, res: Response, next: NextFunction) => {const roleId = req.body.roleId;@@ -22,7 +23,12 @@ export const CanToggleRolesPermissionsCollaborationRoles = async (req: Request,return res.status(500).end();}- if (goal.owner === req.appUser.getUserData()?.id) {+ if (goal.owner !== req.appUser.getUserData()?.id) {+ return res.status(403).end();+ }++ const permissions = await req.appUser.permissionsFetcher.getCheckerForGoal(goal.id);+ if (permissions.hasPermissions(GoalPermissions.GOAL_CAN_MANAGE_USERS)) {return next();}diff --git a/api/src/tv-modules/collaboration/CollaborationManager.ts b/api/src/tv-modules/collaboration/CollaborationManager.tsindex 6197c63..60e8506 100644--- a/api/src/tv-modules/collaboration/CollaborationManager.ts+++ b/api/src/tv-modules/collaboration/CollaborationManager.ts@@ -25,17 +25,15 @@ export class CollaborationManager {this.repository = new CollaborationRepository();}+ private async fetchGoalIdsWithVisibleUsers(organizationId?: number): Promise<number[]> {+ const goalIds = await this.user.goalsManager.fetchAccessibleGoalIds({ organizationId });+ const access = await this.user.permissionsFetcher.getAccessForGoals(goalIds);+ return access.goalIdsWith(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS);+ }+/** @deprecated */async fetchAllUsers(): Promise<CollaborationUserWithRoles[] | false> {- const sharedGoals = await this.user.goalsManager.fetchSharedGoals();-- const goalIds = sharedGoals- .filter((g) => g.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS))- .map((g) => g.id);-- const ownGoals = await this.user.goalsManager.fetchAllOwnGoalsIds();-- goalIds.push(...ownGoals);+ const goalIds = await this.fetchGoalIdsWithVisibleUsers();if (goalIds.length === 0) {return [];@@ -163,16 +161,7 @@ export class CollaborationManager {}async fetchAllUsersNew(organizationId?: number): Promise<CollaborationUserWithRoles[]> {-- const sharedGoals = await this.user.goalsManager.fetchSharedGoals(organizationId);-- const goalIds = sharedGoals- .filter((g) => g.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS))- .map((g) => g.id);-- const ownGoals = await this.user.goalsManager.fetchAllOwnGoalsIds(organizationId);-- goalIds.push(...ownGoals);+ const goalIds = await this.fetchGoalIdsWithVisibleUsers(organizationId);if (goalIds.length === 0) {return [];diff --git a/api/src/tv-modules/goals/GoalsManager.ts b/api/src/tv-modules/goals/GoalsManager.tsindex eee044a..408fd7c 100644--- a/api/src/tv-modules/goals/GoalsManager.ts+++ b/api/src/tv-modules/goals/GoalsManager.ts@@ -4,7 +4,13 @@ import type { AddGoalToDbArg, GoalItemInDb, UpdateGoalDbArg } from '../../types/import { isNotNullable } from '../../utils/helpers';import { GoalItemForClient } from './GoalItemForClient';import { GoalsRepository } from './GoalsRepository';-import type { GoalsArgAdd, GoalsArgDelete, GoalsArgUpdate, GoalsItemForClientWithPermissions } from './types';+import type {+ GoalsArgAdd,+ GoalsArgDelete,+ GoalsArgFetchAccessibleIds,+ GoalsArgUpdate,+ GoalsItemForClientWithPermissions,+} from './types';export default class GoalsManager {public readonly goalsRepository: GoalsRepository;@@ -102,8 +108,20 @@ export default class GoalsManager {return await this.goalsRepository.updateArchive(goalId, archive);}- async fetchAllOwnGoalsIds(organizationId?: number) {- return await this.goalsRepository.fetchAllOwnGoalsIds(this.user, organizationId);+ async fetchAccessibleGoalIds(args: GoalsArgFetchAccessibleIds = {}): Promise<number[]> {+ const userId = this.user.getUserData()?.id;+ if (!userId) return [];++ const [ownGoalIds, sharedGoals] = await Promise.all([+ this.goalsRepository.fetchOwnGoalIds({+ userId,+ organizationId: args.organizationId,+ includeArchived: args.includeArchivedOwn,+ }),+ this.goalsRepository.fetchSharedGoals(this.user, args.organizationId),+ ]);++ return [...new Set([...ownGoalIds, ...sharedGoals.map((g) => g.id)])];}async createGoal(goalData: GoalsArgAdd): Promise<GoalsItemForClientWithPermissions | false> {diff --git a/api/src/tv-modules/goals/GoalsRepository.ts b/api/src/tv-modules/goals/GoalsRepository.tsindex 3ecbb19..b016857 100644--- a/api/src/tv-modules/goals/GoalsRepository.ts+++ b/api/src/tv-modules/goals/GoalsRepository.ts@@ -12,7 +12,7 @@ import type { AddGoalToDbArg, GoalItemInDb, GoalItemsInDb, UpdateGoalDbArg } froimport { logError } from '../../utils/api';import { updateQuery } from '../../utils/db-helper';import { callWithCatch } from '../../utils/helpers';-import type { GoalsArgAdd, GoalsArgCreateInbox, GoalsArgDelete, GoalsArgUpdate } from './types';+import type { GoalsArgAdd, GoalsArgCreateInbox, GoalsArgDelete, GoalsArgFetchOwnIds, GoalsArgUpdate } from './types';export class GoalsRepository {private readonly db: Database;@@ -194,13 +194,13 @@ export class GoalsRepository {return !!(result.rowCount && result.rowCount > 0);}- async fetchAllOwnGoalsIds(user: AppUser, organizationId?: number): Promise<number[]> {- const conditions = [- eq(GoalsSchema.owner, user.getUserData()?.id!),- eq(GoalsSchema.archive, 0),- ];- if (organizationId) {- conditions.push(eq(GoalsSchema.organizationId, organizationId));+ async fetchOwnGoalIds(args: GoalsArgFetchOwnIds): Promise<number[]> {+ const conditions = [eq(GoalsSchema.owner, args.userId)];+ if (!args.includeArchived) {+ conditions.push(eq(GoalsSchema.archive, 0));+ }+ if (args.organizationId) {+ conditions.push(eq(GoalsSchema.organizationId, args.organizationId));}const result = await callWithCatch(() =>diff --git a/api/src/tv-modules/goals/types.ts b/api/src/tv-modules/goals/types.tsindex 754f58b..ef6d44f 100644--- a/api/src/tv-modules/goals/types.ts+++ b/api/src/tv-modules/goals/types.ts@@ -40,3 +40,14 @@ export type GoalsArgCreateInbox = {ownerId: number;organizationId: number;};++export type GoalsArgFetchOwnIds = {+ userId: number;+ organizationId?: number;+ includeArchived?: boolean;+};++export type GoalsArgFetchAccessibleIds = {+ organizationId?: number;+ includeArchivedOwn?: boolean;+};diff --git a/api/src/tv-modules/integrations/IntegrationsController.ts b/api/src/tv-modules/integrations/IntegrationsController.tsindex 33324b3..274ac79 100644--- a/api/src/tv-modules/integrations/IntegrationsController.ts+++ b/api/src/tv-modules/integrations/IntegrationsController.ts@@ -80,7 +80,7 @@ export default class IntegrationsController {integrationsDebugLog({ step: 'initiate:reject', data: 'token is required' });return res.status(401).send('token is required');}- const userPayload = await AuthController.validateTokens(token);+ const userPayload = await AuthController.validateTokens({ token, type: 'access' });if (!userPayload?.userData?.id) {integrationsDebugLog({ step: 'initiate:reject', data: 'invalid token' });return res.status(401).send('Invalid token');diff --git a/api/src/tv-modules/kanban/KanbanController.ts b/api/src/tv-modules/kanban/KanbanController.tsindex aa2f111..0826474 100644--- a/api/src/tv-modules/kanban/KanbanController.ts+++ b/api/src/tv-modules/kanban/KanbanController.ts@@ -3,6 +3,7 @@ import {KanbanArkTypeFetchTasksForColumn,KanbanArkTypeFilters,KanbanArkTypeGetTasksOrderForColumnAndCursor,+ KanbanArkTypeReorderStatuses,KanbanArkTypeUpdateTasksOrder,KanbanSchemaAddStatus,KanbanSchemaFetchAllStatuses,@@ -29,6 +30,20 @@ export class KanbanController {return res.tvJson(await req.appUser.kanbanManager.updateStatus(data.data));};+ reorderStatuses = async (req: Request, res: Response) => {+ const data = KanbanArkTypeReorderStatuses(req.body);+ if (data instanceof ArkErrors) {+ return res.status(400).send(data.summary);+ }++ const result = await req.appUser.kanbanManager.reorderStatuses({ goalId: data.goalId, statusIds: data.statusIds });+ if (!result.ok) {+ return res.status(result.reason === 'invalid_order' ? 400 : 500).json({ code: result.reason });+ }++ return res.tvJson(result.statuses);+ };+addStatus = async (req: Request, res: Response) => {const data = KanbanSchemaAddStatus.safeParse(req.body);if (!data.success) {diff --git a/api/src/tv-modules/kanban/KanbanManager.ts b/api/src/tv-modules/kanban/KanbanManager.tsindex a3fda09..70c53de 100644--- a/api/src/tv-modules/kanban/KanbanManager.ts+++ b/api/src/tv-modules/kanban/KanbanManager.ts@@ -10,6 +10,8 @@ import {type KanbanArgFilters,type KanbanArgGetTasksOrderForColumnAndCursor,type KanbanArgUpdateTasksOrder,+ type KanbanReorderStatusesArgs,+ type KanbanReorderStatusesResult,type KanbanStatusForClient,KanbanStatusToClientSchema,type UpdateKanbanStatus,@@ -29,6 +31,20 @@ export class KanbanManager {return statuses.map((stat) => KanbanStatusToClientSchema.parse(stat));}+ async reorderStatuses(args: KanbanReorderStatusesArgs): Promise<KanbanReorderStatusesResult> {+ const currentIds = new Set((await this.repository.getAllStatusesForGoal(args.goalId)).map((s) => s.id));+ const requestedIds = new Set(args.statusIds);+ const isFullOrder =+ requestedIds.size === args.statusIds.length &&+ requestedIds.size === currentIds.size &&+ args.statusIds.every((id) => currentIds.has(id));+ if (!isFullOrder) return { ok: false, reason: 'invalid_order' };++ if (!(await this.repository.reorderStatuses(args))) return { ok: false, reason: 'save_failed' };++ return { ok: true, statuses: await this.getAllStatusesForGoal(args.goalId) };+ }+async updateStatus(data: UpdateKanbanStatus) {return await this.repository.updateNameFotStatus(data.id, data.name, data.viewOrder);}@@ -115,10 +131,10 @@ export class KanbanManager {// Получаем порядки предыдущей и следующей задачlet prevTask = data.prevTaskId- ? (await this.repository.getTaskById(data.prevTaskId))?.kanbanOrder ?? null+ ? (await this.repository.getGoalTask({ taskId: data.prevTaskId, goalId: data.goalId }))?.kanbanOrder ?? null: null;let nextTask = data.nextTaskId- ? (await this.repository.getTaskById(data.nextTaskId))?.kanbanOrder ?? null+ ? (await this.repository.getGoalTask({ taskId: data.nextTaskId, goalId: data.goalId }))?.kanbanOrder ?? null: null;let newOrder: number | null = null;diff --git a/api/src/tv-modules/kanban/KanbanRepository.ts b/api/src/tv-modules/kanban/KanbanRepository.tsindex 839bf33..c3850f3 100644--- a/api/src/tv-modules/kanban/KanbanRepository.ts+++ b/api/src/tv-modules/kanban/KanbanRepository.ts@@ -3,10 +3,9 @@ import { Database } from '../../modules/db';import type { GoalItemInDb } from '../../types/goal.type';import { logError } from '../../utils/api';import { updateQuery } from '../../utils/db-helper';-import type { KanbanStatusItemInDb, StatusBelongsToGoalArgs } from './types';+import type { KanbanGoalTaskArgs, KanbanReorderStatusesArgs, KanbanStatusItemInDb, StatusBelongsToGoalArgs } from './types';import { callWithCatch } from '../../utils/helpers';import { and, asc, eq, gt, gte, isNull, lt, lte, sql } from 'drizzle-orm';-import type { TaskItemInDb } from '../../types/tasks.types';import { PgDialect } from 'drizzle-orm/pg-core';export class KanbanRepository {@@ -20,13 +19,31 @@ export class KanbanRepository {return [];}- const columns = await this.db- .query<KanbanStatusItemInDb>('select * from tasks.statuses where goal_id = $1 order by id', [goalId])- .catch(logError);+ const columns = await callWithCatch(() => this.db.dbDrizzle+ .select({+ id: TasksStatusesSchema.id,+ goal_id: TasksStatusesSchema.goalId,+ name: TasksStatusesSchema.name,+ view_order: TasksStatusesSchema.viewOrder,+ })+ .from(TasksStatusesSchema)+ .where(eq(TasksStatusesSchema.goalId, goalId))+ .orderBy(asc(TasksStatusesSchema.viewOrder), asc(TasksStatusesSchema.id)));- if (!columns) return [];+ return (columns ?? []).map((column) => ({ ...column, view_order: column.view_order ?? 0 }));+ }- return columns.rows;+ async reorderStatuses(args: KanbanReorderStatusesArgs): Promise<boolean> {+ const result = await callWithCatch(() => this.db.dbDrizzle.transaction(async (tx) => {+ for (const [index, statusId] of args.statusIds.entries()) {+ await tx+ .update(TasksStatusesSchema)+ .set({ viewOrder: index + 1 })+ .where(and(eq(TasksStatusesSchema.id, statusId), eq(TasksStatusesSchema.goalId, args.goalId)));+ }+ return true;+ }));+ return result === true;}async updateNameFotStatus(@@ -134,8 +151,11 @@ export class KanbanRepository {return result?.[0] ?? null;}- async getTaskById(id: TaskItemInDb['id']): Promise<TasksSchemaTypeForSelect | null> {- const result = await callWithCatch(() => this.db.dbDrizzle.select().from(TasksSchema).where(eq(TasksSchema.id, id)));+ async getGoalTask(args: KanbanGoalTaskArgs): Promise<TasksSchemaTypeForSelect | null> {+ const result = await callWithCatch(() => this.db.dbDrizzle+ .select()+ .from(TasksSchema)+ .where(and(eq(TasksSchema.id, args.taskId), eq(TasksSchema.goalId, args.goalId))));if (!result) {return null;}diff --git a/api/src/tv-modules/kanban/KanbanRoutes.ts b/api/src/tv-modules/kanban/KanbanRoutes.tsindex 97133d1..3407842 100644--- a/api/src/tv-modules/kanban/KanbanRoutes.ts+++ b/api/src/tv-modules/kanban/KanbanRoutes.ts@@ -44,6 +44,17 @@ export default class KanbanRoutes implements Routable {this.kanbanController.addStatus);+ this.router.patch(+ '/reorder-statuses',+ [+ IsLoggedIn, requireKanbanPermission({+ anyOf: [GoalPermissions.KANBAN_CAN_MANAGE],+ resolveGoalId: goalIdFromBody+ })+ ],+ this.kanbanController.reorderStatuses+ );+this.router.post('/delete-status',[diff --git a/api/src/tv-modules/kanban/types.ts b/api/src/tv-modules/kanban/types.tsindex cc9c324..51bc070 100644--- a/api/src/tv-modules/kanban/types.ts+++ b/api/src/tv-modules/kanban/types.ts@@ -35,8 +35,27 @@ export type KanbanArgUpdateStatus = typeof KanbanArkTypeStatusUpdate.infer;export type KanbanArgFetchAllStatuses = typeof KanbanArkTypeFetchAllStatuses.infer;+export const KanbanArkTypeReorderStatuses = type({+ goalId: NumberFromString,+ statusIds: 'number.integer[]',+});++export type KanbanArgReorderStatuses = typeof KanbanArkTypeReorderStatuses.infer;++export type KanbanReorderStatusesArgs = {+ goalId: number;+ /** every column of the goal, in the new order */+ statusIds: number[];+};++export type KanbanReorderStatusesResult =+ | { ok: true; statuses: KanbanStatusForClient[] }+ | { ok: false; reason: 'invalid_order' | 'save_failed' };+export type StatusBelongsToGoalArgs = { statusId: number; goalId: number };+export type KanbanGoalTaskArgs = { taskId: number; goalId: number };+export type KanbanStatusInDb = {id: number;goal_id: number;diff --git a/api/src/tv-modules/messaging/MessagingController.ts b/api/src/tv-modules/messaging/MessagingController.tsindex 259096f..08f0f04 100644--- a/api/src/tv-modules/messaging/MessagingController.ts+++ b/api/src/tv-modules/messaging/MessagingController.ts@@ -175,7 +175,7 @@ export class MessagingController {const token = req.query.token as string;if (!token) return res.status(401).send('token is required');- const userPayload = await AuthController.validateTokens(token);+ const userPayload = await AuthController.validateTokens({ token, type: 'access' });const userId = userPayload?.userData?.id;if (!userId) return res.status(401).send('Invalid token');diff --git a/api/src/tv-modules/messaging/MessagingManager.ts b/api/src/tv-modules/messaging/MessagingManager.tsindex 37d4e5d..39363b1 100644--- a/api/src/tv-modules/messaging/MessagingManager.ts+++ b/api/src/tv-modules/messaging/MessagingManager.ts@@ -103,7 +103,7 @@ export class MessagingManager {}const created = await appUser.tasksManager.addTaskNew({ goalId: goalIds[0], description: intent.text });- const task = created?.[0];+ const task = created.ok ? created.tasks[0] : undefined;if (!task) return note('Failed to create the task.');const orgSlug = await this.repository.fetchGoalOrgSlug(goalIds[0]);@@ -172,7 +172,7 @@ export class MessagingManager {}async toggleProject(id: number, goalId: number, isActive: boolean): Promise<MessagingConnectionForClient | null> {- // goalId was verified against the caller by IsGoalOwnerByGoalId; the WHERE+ // goalId was verified against the caller by CanManageProjectMessaging; the WHERE// clause also binds the connection to that goal, so no cross-project mutation.const updated = await this.repository.setActiveOwned({ id, ownerType: 'project', ownerId: goalId, isActive });return updated ? this.toClient(updated) : null;diff --git a/api/src/tv-modules/messaging/SlackInboundManager.ts b/api/src/tv-modules/messaging/SlackInboundManager.tsindex dff1f52..26e9455 100644--- a/api/src/tv-modules/messaging/SlackInboundManager.ts+++ b/api/src/tv-modules/messaging/SlackInboundManager.ts@@ -41,7 +41,7 @@ export class SlackInboundManager {}const created = await appUser.tasksManager.addTaskNew({ goalId: goalIds[0], description });- if (!created?.[0]) return this.ephemeral('Failed to create the task.');+ if (!created.ok || !created.tasks[0]) return this.ephemeral('Failed to create the task.');return this.ephemeral(`✅ Task created: ${description}`);}diff --git a/api/src/tv-modules/organizations/__tests__/TokenScope.integration.spec.ts b/api/src/tv-modules/organizations/__tests__/TokenScope.integration.spec.tsindex de97c93..464ff5b 100644--- a/api/src/tv-modules/organizations/__tests__/TokenScope.integration.spec.ts+++ b/api/src/tv-modules/organizations/__tests__/TokenScope.integration.spec.ts@@ -61,8 +61,8 @@ describe('API token scope on organization-level surfaces', () => {expect(login.status).toBe(200);jwt = login.data.access;- // A goal the caller actually owns: otherwise IsGoalOwnerByGoalId answers 403- // on its own and the webhook tests below would pass without the token check.+ // A goal the caller actually owns: otherwise the webhook guard answers 403 for+ // lack of project permissions and the tests below would pass without the token check.const goal = await api.post('/module/goals', { name: `scope-goal-${Date.now()}` }, asUser());expect(goal.status).toBe(200);ownedGoalId = goal.data.response.id;@@ -87,10 +87,18 @@ describe('API token scope on organization-level surfaces', () => {'SELECT name FROM tv_auth.permissions WHERE permission_group = 6 ORDER BY name',);expect(result?.rows.map((row) => row.name)).toEqual([- 'billing_can_manage', 'org_can_manage', 'org_can_manage_members', 'org_can_view', 'sso_can_manage', 'webhooks_can_manage',+ 'billing_can_manage', 'org_can_manage', 'org_can_manage_members', 'org_can_view', 'sso_can_manage',]);});+ it('keeps the webhook permissions in a group of their own', async () => {+ const db = Database.getInstance();+ const result = await db.query<{ name: string }>(+ 'SELECT name FROM tv_auth.permissions WHERE permission_group = 9 ORDER BY name',+ );+ expect(result?.rows.map((row) => row.name)).toEqual(['webhooks_can_manage', 'webhooks_can_view']);+ });+it('offers the new permissions for selection, with localized descriptions', async () => {const response = await api.get('/module/api-tokens/permissions', asUser());@@ -177,8 +185,8 @@ describe('API token scope on organization-level surfaces', () => {expect(response.status).toBe(403);});- it('lets webhooks_can_manage through on that same goal, proving the 403 came from the token', async () => {- const token = await issueToken([GoalPermissions.WEBHOOKS_CAN_MANAGE]);+ it('lets webhooks_can_view through on that same goal, proving the 403 came from the token', async () => {+ const token = await issueToken([GoalPermissions.WEBHOOKS_CAN_VIEW]);const response = await api.get(`/module/webhooks?goalId=${ownedGoalId}`, token);diff --git a/api/src/tv-modules/start/StartManager.ts b/api/src/tv-modules/start/StartManager.tsindex e34b74b..75b9a47 100644--- a/api/src/tv-modules/start/StartManager.ts+++ b/api/src/tv-modules/start/StartManager.ts@@ -1,14 +1,13 @@import type { AppUser } from '../../core/AppUser';-import { $logger } from '../../modules/logget';+import type { GoalAccess } from '../../core/GoalAccess';import { GoalPermissions } from '../../types/auth.types';-import { logError } from '../../utils/api';-import type { GoalItemForClient } from '../goals/GoalItemForClient';+import { hideUnwatchableTaskFields } from '../tasks/task-field-visibility';import { StartRepository } from './StartRepository';+import type { StartTasksVisibilityArgs, StartVisibleTask } from './start.types';export class StartManager {public readonly user: AppUser;public readonly repository: StartRepository;- private sharedGoals: GoalItemForClient[] = [];constructor(user: AppUser) {this.user = user;@@ -16,80 +15,55 @@ export class StartManager {}async fetchAllLists(organizationId?: number) {- return await this.repository.fetchAllLists(this.user, organizationId);+ const access = await this.fetchGoalAccess(organizationId);+ return await this.repository.fetchListsForGoals(access.goalIdsWith(GoalPermissions.GOAL_CAN_WATCH_CONTENT));}async fetchAllState(tz: string, organizationId?: number) {- await this.fetchSharedGoals(organizationId);- const goalIds = await this.getAllGoalsIds(organizationId);- const usersAndProjects = await this.fetchProjectsAndUsers(organizationId);- const tasks = await this.repository.fetchAllActiveTasksForGoals(goalIds, usersAndProjects.assignees);- const tasksToday = await this.repository.fetchAllTodayTasksForGoals(goalIds, tz, usersAndProjects.assignees);- const tasksUpcoming = await this.repository.fetchUpcomingTasksForGoals(goalIds, tz, usersAndProjects.assignees);- const tasksLastCompleted = await this.repository.fetchLastCompletedTasksForGoals(- goalIds,- usersAndProjects.assignees+ const access = await this.fetchGoalAccess(organizationId);+ const goalIds = access.goalIdsWith(GoalPermissions.COMPONENT_CAN_WATCH_CONTENT);+ const assigneeGoalIds = goalIds.filter((id) =>+ access.checkerFor(id).hasPermissions(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS));- return {- tasks,- tasksToday,- tasksUpcoming,- tasksLastCompleted,- users: usersAndProjects.users,- assignees: usersAndProjects.assignees,- };- }- async fetchSharedGoals(organizationId?: number) {- this.sharedGoals = await this.user.goalsManager.fetchSharedGoals(organizationId);- }-- async getAllGoalsIds(organizationId?: number) {- const ownGoalIds = await this.user.goalsManager.fetchAllOwnGoalsIds(organizationId);-- const sharedGoalIds: number[] = [];- this.sharedGoals.forEach((g) => {- if (g.hasPermissions(GoalPermissions.GOAL_CAN_WATCH_CONTENT)) {- sharedGoalIds.push(g.id);- }- });-- const ids = new Set([...ownGoalIds, ...sharedGoalIds]);- return [...ids];- }-- async fetchProjectsAndUsers(organizationId?: number) {- const ownGoalIds = await this.user.goalsManager.fetchAllOwnGoalsIds(organizationId)-- const goalsIdsForUsers: number[] = [...ownGoalIds]- const goalsIdsForAssignee: number[] = [...ownGoalIds]-- this.sharedGoals.forEach((goal) => {- if (goal.hasPermissions(GoalPermissions.GOAL_CAN_MANAGE_USERS)) {- goalsIdsForUsers.push(goal.id)- }-- if (goal.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_ASSIGNED_USERS)) {- goalsIdsForAssignee.push(goal.id)- }- })-- const users = await this.repository.fetchUsersByProjects(goalsIdsForUsers)- const assignees = await this.repository.fetchAssigneesForTasks(goalsIdsForAssignee)+ const users = await this.repository.fetchUsersByProjects(access.goalIdsWith(GoalPermissions.GOAL_CAN_MANAGE_USERS));+ const assignees = await this.repository.fetchAssigneesForTasks(assigneeGoalIds);+ const tasks = await this.repository.fetchAllActiveTasksForGoals(goalIds, assignees);+ const tasksToday = await this.repository.fetchAllTodayTasksForGoals(goalIds, tz, assignees);+ const tasksUpcoming = await this.repository.fetchUpcomingTasksForGoals(goalIds, tz, assignees);+ const tasksLastCompleted = await this.repository.fetchLastCompletedTasksForGoals(goalIds, assignees);return {+ tasks: this.applyTaskVisibility({ tasks, access }),+ tasksToday: this.applyTaskVisibility({ tasks: tasksToday, access }),+ tasksUpcoming: this.applyTaskVisibility({ tasks: tasksUpcoming, access }),+ tasksLastCompleted: this.applyTaskVisibility({ tasks: tasksLastCompleted, access }),users,assignees,- }+ };}async searchTaskInAllProjects(description?: string, organizationId?: number) {if (!description) return [];- await this.fetchSharedGoals(organizationId);- const goalIds = await this.getAllGoalsIds(organizationId);-+ const access = await this.fetchGoalAccess(organizationId);+ const goalIds = access.goalIdsWith(GoalPermissions.COMPONENT_CAN_WATCH_CONTENT);const tasks = await this.repository.searchTask({ description, goalsIds: goalIds });- return tasks;+ return this.applyTaskVisibility({ tasks, access });+ }++ private async fetchGoalAccess(organizationId?: number): Promise<GoalAccess> {+ const goalIds = await this.user.goalsManager.fetchAccessibleGoalIds({ organizationId });+ return await this.user.permissionsFetcher.getAccessForGoals(goalIds);+ }++ private applyTaskVisibility<T extends StartVisibleTask>(args: StartTasksVisibilityArgs<T>): T[] {+ return args.tasks.map((task) => {+ const checker = args.access.checkerFor(task.goalId);+ if (!checker.hasPermissions(GoalPermissions.TASKS_CAN_WATCH_TAGS)) {+ task.tags = [];+ }+ return hideUnwatchableTaskFields({ task, checker });+ });}}diff --git a/api/src/tv-modules/start/StartRepository.ts b/api/src/tv-modules/start/StartRepository.tsindex 935cf3f..1d715d5 100644--- a/api/src/tv-modules/start/StartRepository.ts+++ b/api/src/tv-modules/start/StartRepository.ts@@ -1,14 +1,13 @@-import { and, eq, ilike, inArray, isNotNull, isNull, or } from 'drizzle-orm';-import { GoalsSchema, GoalsListSchema, TasksSchema } from 'taskview-db-schemas';+import { and, eq, ilike, inArray, isNotNull, isNull } from 'drizzle-orm';+import { GoalsSchema, GoalsListSchema, TasksSchema, TasksToTagsSchema } from 'taskview-db-schemas';import type { AppUser } from '../../core/AppUser';import { Database } from '../../modules/db';import { $logger } from '../../modules/logget';import type { TaskItemInDb } from '../../types/tasks.types';import { logError } from '../../utils/api';import { callWithCatch } from '../../utils/helpers';-import type { TagToTaskInDb } from '../tags/tags.types';import { TaskItemForClient } from '../tasks/TaskItemForClient';-import type { AssigneesForTaskFromDb, FetchAllListsResult, SearchTaskArgs, SearchTaskResult, UsersByProjectsFromDb } from './start.types';+import type { AssigneesForTaskFromDb, FetchAllListsResult, SearchTaskArgs, SearchTaskResult, StartTaskTagFromDb, UsersByProjectsFromDb } from './start.types';//TODO: refactorexport class StartRepository {@@ -20,21 +19,8 @@ export class StartRepository {this.user = user;}- async fetchAllLists(user: AppUser, organizationId?: number): Promise<FetchAllListsResult[] | false> {- const userId = user.getUserData()?.id- if (!userId) return false-- const sharedGoals = await user.goalsManager.fetchSharedGoals(organizationId)- const sharedGoalIds = sharedGoals.map((g) => g.id)-- const ownConditions = [eq(GoalsSchema.owner, userId)]- if (organizationId) {- ownConditions.push(eq(GoalsSchema.organizationId, organizationId))- }-- const goalConditions = sharedGoalIds.length > 0- ? or(and(...ownConditions), inArray(GoalsSchema.id, sharedGoalIds))- : and(...ownConditions)+ async fetchListsForGoals(goalIds: number[]): Promise<FetchAllListsResult[]> {+ if (goalIds.length === 0) return []const result = await callWithCatch(() =>this.db.dbDrizzle@@ -50,7 +36,7 @@ export class StartRepository {and(eq(GoalsListSchema.archive, 0),isNotNull(GoalsListSchema.id),- goalConditions,+ inArray(GoalsSchema.id, goalIds),)))@@ -103,6 +89,19 @@ export class StartRepository {return result.rows}+ async fetchTagIdsForTasks(taskIds: number[]): Promise<StartTaskTagFromDb[]> {+ if (taskIds.length === 0) return [];++ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ taskId: TasksToTagsSchema.taskId, tagId: TasksToTagsSchema.tagId })+ .from(TasksToTagsSchema)+ .where(inArray(TasksToTagsSchema.taskId, taskIds))+ );++ return result ?? [];+ }+async fetchAllActiveTasksForGoals(goalsIds: number[],assignees?: AssigneesForTaskFromDb[],@@ -117,7 +116,7 @@ export class StartRepository {const map: Map<number, TaskItemForClient> = new Map();const result = await this.db.query<TaskItemInDb>(- `select * from tasks.tasks where goal_id in (${placeholders.join(',')}) and complete = FALSE and parent_id is null and end_date is null ORDER BY priority_id DESC, date_creation DESC LIMIT 30`,+ `select * from tasks.tasks where goal_id in (${placeholders.join(',')}) and complete = FALSE and parent_id is null and end_date is null ORDER BY date_creation DESC, id DESC LIMIT 30`,goalsIds);@@ -131,20 +130,10 @@ export class StartRepository {}});- const tagsQuery = `select ttt.*- from tasks.tags- left join tasks.tasks_to_tags ttt on tags.id = ttt.tag_id- where goal_id in (${placeholders.join(',')}) and owner = $${goalsIds.length + 1};`;-- const tagsResult = await this.db.query<TagToTaskInDb>(tagsQuery, [...goalsIds, this.user.getUserData()?.id]);-- if (tagsResult) {- tagsResult.rows.forEach((r) => {- if (map.get(r.task_id)) {- map.get(r.task_id)?.tags.push(r.tag_id);- }- });- }+ const taskTags = await this.fetchTagIdsForTasks([...map.keys()]);+ taskTags.forEach((r) => {+ map.get(r.taskId)?.tags.push(r.tagId);+ });if (assignees) {assignees.forEach((i) => {@@ -204,20 +193,10 @@ export class StartRepository {}});- const tagsQuery = `select ttt.*- from tasks.tags- left join tasks.tasks_to_tags ttt on tags.id = ttt.tag_id- where goal_id in (${placeholders.join(',')}) and owner = $${goalsIds.length + 1};`;-- const tagsResult = await this.db.query<TagToTaskInDb>(tagsQuery, [...goalsIds, this.user.getUserData()?.id]);-- if (tagsResult) {- tagsResult.rows.forEach((r) => {- if (map.get(r.task_id)) {- map.get(r.task_id)?.tags.push(r.tag_id);- }- });- }+ const taskTags = await this.fetchTagIdsForTasks([...map.keys()]);+ taskTags.forEach((r) => {+ map.get(r.taskId)?.tags.push(r.tagId);+ });if (assignees) {assignees.forEach((i) => {@@ -282,20 +261,10 @@ export class StartRepository {}});- const tagsQuery = `select ttt.*- from tasks.tags- left join tasks.tasks_to_tags ttt on tags.id = ttt.tag_id- where goal_id in (${placeholders.join(',')}) and owner = $${goalsIds.length + 1};`;-- const tagsResult = await this.db.query<TagToTaskInDb>(tagsQuery, [...goalsIds, this.user.getUserData()?.id]);-- if (tagsResult) {- tagsResult.rows.forEach((r) => {- if (map.get(r.task_id)) {- map.get(r.task_id)?.tags.push(r.tag_id);- }- });- }+ const taskTags = await this.fetchTagIdsForTasks([...map.keys()]);+ taskTags.forEach((r) => {+ map.get(r.taskId)?.tags.push(r.tagId);+ });if (assignees) {assignees.forEach((i) => {@@ -345,20 +314,10 @@ export class StartRepository {}});- const tagsQuery = `select ttt.*- from tasks.tags- left join tasks.tasks_to_tags ttt on tags.id = ttt.tag_id- where goal_id in (${placeholders.join(',')}) and owner = $${goalsIds.length + 1};`;-- const tagsResult = await this.db.query<TagToTaskInDb>(tagsQuery, [...goalsIds, this.user.getUserData()?.id]);-- if (tagsResult) {- tagsResult.rows.forEach((r) => {- if (taskIdToTaskMap.get(r.task_id)) {- taskIdToTaskMap.get(r.task_id)?.tags.push(r.tag_id);- }- });- }+ const taskTags = await this.fetchTagIdsForTasks([...taskIdToTaskMap.keys()]);+ taskTags.forEach((r) => {+ taskIdToTaskMap.get(r.taskId)?.tags.push(r.tagId);+ });if (assignees) {assignees.forEach((i) => {diff --git a/api/src/tv-modules/start/start.types.ts b/api/src/tv-modules/start/start.types.tsindex f6295a1..1f99c38 100644--- a/api/src/tv-modules/start/start.types.ts+++ b/api/src/tv-modules/start/start.types.ts@@ -1,4 +1,15 @@import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';+import type { GoalAccess } from '../../core/GoalAccess';++export type StartVisibleTask = {+ goalId: number;+ tags: number[];+};++export type StartTasksVisibilityArgs<T extends StartVisibleTask> = {+ tasks: T[];+ access: GoalAccess;+};export type SearchTaskArgs = {description: string;@@ -30,3 +41,8 @@ export type AssigneesForTaskFromDb = {taskId: number;collabUserId: number;};++export type StartTaskTagFromDb = {+ taskId: number;+ tagId: number;+};diff --git a/api/src/tv-modules/tags/TagsController.ts b/api/src/tv-modules/tags/TagsController.tsindex c995d83..11cf34c 100644--- a/api/src/tv-modules/tags/TagsController.ts+++ b/api/src/tv-modules/tags/TagsController.ts@@ -33,11 +33,6 @@ export class TagsController {return res.tvJson((await req.appUser.tagsManager.addTagNew(data)) ?? null);};- /** @deprecated use fetchAllTagsForUser instead */- fetchAll = async (req: Request, res: Response) => {- return res.tvJson(await req.appUser.tagsManager.fetchAll());- };-fetchAllTagsForUser = async (req: Request, res: Response) => {const organizationId = req.query.organizationId ? Number(req.query.organizationId) : undefined;return res.tvJson(await req.appUser.tagsManager.fetchAllTagsForUser(organizationId));diff --git a/api/src/tv-modules/tags/TagsManager.ts b/api/src/tv-modules/tags/TagsManager.tsindex 36c0814..dcce66a 100644--- a/api/src/tv-modules/tags/TagsManager.ts+++ b/api/src/tv-modules/tags/TagsManager.ts@@ -41,20 +41,6 @@ export class TagsManager {return await this.repository.addTagNew(data);}- /** @deprecated use fetchAllTagsForUser instead */- async fetchAll() {- const userId = this.user.getUserData()?.id;- if (!userId) {- $logger.error(`Can not fetch tags for undefined user`);- return [];- }- const tags = await this.repository.fetchAll(userId);- if (!tags) {- return [];- }- return tags.map((item) => new TagItemForClient(item));- }-async fetchAllTagsForUser(organizationId?: number) {const userId = this.user.getUserData()?.id;if (!userId) {diff --git a/api/src/tv-modules/tags/TagsRepository.ts b/api/src/tv-modules/tags/TagsRepository.tsindex 1667933..5b9433a 100644--- a/api/src/tv-modules/tags/TagsRepository.ts+++ b/api/src/tv-modules/tags/TagsRepository.ts@@ -1,4 +1,4 @@-import { and, eq, inArray } from 'drizzle-orm';+import { and, eq, inArray, isNull, or, type SQL } from 'drizzle-orm';import type { TagsSchemaTypeForSelect } from 'taskview-db-schemas';import { GoalsSchema, TagsSchema, TasksSchema, TasksToTagsSchema } from 'taskview-db-schemas';import type { AppUser } from '../../core/AppUser';@@ -74,79 +74,25 @@ export class TagsRepository {return tagResult;}- /** @deprecated use fetchAllTagsForUser instead */- async fetchAll(userId: number): Promise<TagItemInDb[] | false> {- const tags = await this.db.query('SELECT * FROM tasks.tags WHERE owner = $1;', [userId]).catch(logError);+ async fetchAllTagsForUser(userId: number, organizationId?: number): Promise<TagsSchemaTypeForSelect[]> {+ const goalIds = await this.user.goalsManager.fetchAccessibleGoalIds({ organizationId, includeArchivedOwn: true });+ const access = await this.user.permissionsFetcher.getAccessForGoals(goalIds);+ const tagGoalIds = access.goalIdsWith(GoalPermissions.TASKS_CAN_WATCH_TAGS);- if (!tags) {- return false;+ const conditions: SQL[] = [];+ if (tagGoalIds.length > 0) {+ conditions.push(inArray(TagsSchema.goalId, tagGoalIds));}-- const sharedGoals = await this.user.goalsManager.fetchSharedGoals();-- if (sharedGoals.length > 0) {- const goalIds: number[] = [];- sharedGoals.forEach((goal) => {- //Не уверен что тут надо именно данное разрешение- if (goal.permissions[GoalPermissions.TASKS_CAN_WATCH_TAGS]) {- goalIds.push(goal.id);- }- });-- if (goalIds.length > 0) {- const placeholders = goalIds.map((_, i) => `$${i + 1}`).join(',');-- const sharedTags = await this.db- .query(`SELECT * FROM tasks.tags WHERE goal_id IN (${placeholders})`, goalIds)- .catch(logError);-- if (sharedTags) {- tags.rows = [...tags.rows, ...sharedTags.rows];- }- }+ if (!organizationId && this.user.permissionsFetcher.canSeeDataOutsideGoals(GoalPermissions.TASKS_CAN_WATCH_TAGS)) {+ conditions.push(and(eq(TagsSchema.owner, userId), isNull(TagsSchema.goalId))!);}+ if (conditions.length === 0) return [];- return tags.rows;- }-- async fetchAllTagsForUser(userId: number, organizationId?: number): Promise<TagsSchemaTypeForSelect[]> {- const ownTagsConditions = [eq(TagsSchema.owner, userId)];- if (organizationId) {- ownTagsConditions.push(- inArray(TagsSchema.goalId, this.db.dbDrizzle.select({ id: GoalsSchema.id }).from(GoalsSchema).where(eq(GoalsSchema.organizationId, organizationId)))- );- }- const ownTags = await callWithCatch(() =>- this.db.dbDrizzle.select().from(TagsSchema).where(and(...ownTagsConditions))+ const tags = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(TagsSchema).where(or(...conditions)));- const allTags: TagsSchemaTypeForSelect[] = [];-- if (ownTags) {- allTags.push(...ownTags);- }-- const sharedGoals = await this.user.goalsManager.fetchSharedGoals(organizationId);-- if (sharedGoals.length > 0) {- const goalIds: number[] = [];- sharedGoals.forEach((goal) => {- if (goal.permissions[GoalPermissions.TASKS_CAN_WATCH_TAGS]) {- goalIds.push(goal.id);- }- });-- if (goalIds.length > 0) {- const sharedTags = await callWithCatch(() =>- this.db.dbDrizzle.select().from(TagsSchema).where(inArray(TagsSchema.goalId, goalIds))- );- if (sharedTags) {- allTags.push(...sharedTags);- }- }- }-- return allTags;+ return tags ?? [];}async tagExists(tagId: number, taskId: number): Promise<boolean> {diff --git a/api/src/tv-modules/tasks/TasksController.ts b/api/src/tv-modules/tasks/TasksController.tsindex 170ee4f..67ad0b6 100644--- a/api/src/tv-modules/tasks/TasksController.ts+++ b/api/src/tv-modules/tasks/TasksController.ts@@ -408,13 +408,16 @@ export class TasksController {return res.status(400).send(args.summary);}- const tasks = await req.appUser.tasksManager.addTaskNew(args);+ const result = await req.appUser.tasksManager.addTaskNew(args);+ if (!result.ok) {+ return res.status(400).send('List, kanban column and parent must belong to the task project');+ }- if (tasks.length === 0) {+ if (result.tasks.length === 0) {return res.status(500).send('Can not add task');}- return res.tvJson(tasks[0] ?? null);+ return res.tvJson(result.tasks[0] ?? null);};deleteTaskNew = async (req: Request, res: Response) => {diff --git a/api/src/tv-modules/tasks/TasksManager.ts b/api/src/tv-modules/tasks/TasksManager.tsindex 94c95de..c4ecf20 100644--- a/api/src/tv-modules/tasks/TasksManager.ts+++ b/api/src/tv-modules/tasks/TasksManager.ts@@ -31,6 +31,7 @@ import { TasksRepository } from './TasksRepository';import type { TaskArgMove, TaskMoveOutcome, TaskMovePreviewDto } from './task-move.types';import { FilesRepository } from '../files/FilesRepository';import {+ type TaskAddResult,type TaskArgAdd,type TaskArgDelete,type TaskArgFetchTaskByIdNew,@@ -38,14 +39,12 @@ import {type TaskArgFetchTasksNew,type TaskArgRestoreTaskHistory,type TaskArgUpdate,- TaskFieldPermissionsForWatching,type TaskForClientNew,type TaskUpdateResult,type TasksArgToggleTaskUsers,} from './tasks.server.types';import type { KanbanArgFetchTasksForColumn, KanbanArgFilters } from '../kanban/types';--type TaskFieldPermissionKey = keyof typeof TaskFieldPermissionsForWatching & keyof TasksSchemaTypeForSelect;+import { hideUnwatchableTaskFields } from './task-field-visibility';export class TasksManager {public readonly repository: TasksRepository;@@ -321,17 +320,8 @@ export class TasksManager {/** Public: other modules returning task rows (e.g. recurrence) gate fields through the same cleaner. */async cleanTaskFieldsRegardPermissions(task: TasksSchemaTypeForSelect): Promise<TasksSchemaTypeForSelect> {- const permissions = await this.user.permissionsFetcher.getCheckerForGoal(task.goalId);- (Object.keys(TaskFieldPermissionsForWatching) as TaskFieldPermissionKey[]).forEach((key) => {- if (!permissions.hasPermissions(TaskFieldPermissionsForWatching[key])) {- // Type-safe: we know key is a valid field from TaskFieldPermissions- // and we're intentionally nullifying it for permission reasons- const taskWithNullableFields = task as TasksSchemaTypeForSelect &- Partial<Record<TaskFieldPermissionKey, null>>;- taskWithNullableFields[key] = null;- }- });- return task;+ const checker = await this.user.permissionsFetcher.getCheckerForGoal(task.goalId);+ return hideUnwatchableTaskFields({ task, checker });}/**@@ -412,14 +402,27 @@ export class TasksManager {);}- async addTaskNew(data: TaskArgAdd) {- let newData = { ...data };+ async addTaskNew(data: TaskArgAdd): Promise<TaskAddResult> {+ // The caller is authorized on data.goalId only; a DB trigger would otherwise move the task into the list's project+ const foreign = await this.repository.referencesOutsideGoal({+ taskId: null,+ goalId: data.goalId,+ goalListId: data.goalListId,+ statusId: data.statusId,+ parentId: data.parentId,+ });+ if (foreign) return { ok: false, reason: 'foreign_reference' };++ const newData = { ...data };if (data.kanbanOrder === null || data.kanbanOrder === undefined) {newData.kanbanOrder = await this.repository.getNextKanbanOrder(data.goalId, data.statusId ?? null);}- const task = await this.repository.addTaskNew(newData);+ const task = await this.repository.addTaskNew({+ data: newData,+ creatorId: this.user.getUserData()?.id as number,+ });const result = await this.extendTasksWithTagsAndAssignees(task, true);if (task[0]) {@@ -429,7 +432,7 @@ export class TasksManager {});}- return result;+ return { ok: true, tasks: result };}async deleteTaskNew(data: TaskArgDelete) {diff --git a/api/src/tv-modules/tasks/TasksRepository.ts b/api/src/tv-modules/tasks/TasksRepository.tsindex f07cc2d..2181722 100644--- a/api/src/tv-modules/tasks/TasksRepository.ts+++ b/api/src/tv-modules/tasks/TasksRepository.ts@@ -24,12 +24,13 @@ import { logError } from '../../utils/api';import { updateQuery } from '../../utils/db-helper';import { callWithCatch, isNotNullable } from '../../utils/helpers';import {- type TaskArgAdd,type TaskArgDelete,type TaskArgFetchTasksNew,type TaskArgUpdate,type TaskHistoryRestoreArgs,+ type TaskInsertArgs,type TaskReferenceCheckArgs,+ TASK_CREATABLE_COLUMNS,TASK_PROJECT_BOUND_COLUMNS,TASK_UPDATABLE_COLUMNS,type TasksArgToggleTaskUsers,@@ -672,8 +673,15 @@ export class TasksRepository {return rows;}- async addTaskNew(data: TaskArgAdd): Promise<TasksSchemaTypeForSelect[]> {- const result = await callWithCatch(() => this.db.dbDrizzle.insert(TasksSchema).values(data).returning());+ async addTaskNew(args: TaskInsertArgs): Promise<TasksSchemaTypeForSelect[]> {+ // Validated input keeps undeclared keys, so only the declared columns are written+ const values: typeof TasksSchema.$inferInsert = { goalId: args.data.goalId, creatorId: args.creatorId };+ for (const column of TASK_CREATABLE_COLUMNS) {+ if (args.data[column] !== undefined) {+ values[column] = args.data[column] as never;+ }+ }+ const result = await callWithCatch(() => this.db.dbDrizzle.insert(TasksSchema).values(values).returning());if (!result) return [];return result;}diff --git a/api/src/tv-modules/tasks/task-field-visibility.ts b/api/src/tv-modules/tasks/task-field-visibility.tsnew file mode 100644index 0000000..d9d58a8--- /dev/null+++ b/api/src/tv-modules/tasks/task-field-visibility.ts@@ -0,0 +1,13 @@+import { TaskFieldPermissionsForWatching } from './tasks.server.types';+import type { HideUnwatchableTaskFieldsArgs, TaskWatchableField } from './tasks.server.types';++/** Nulls every task field the checker does not allow to watch; mutates and returns the task. */+export function hideUnwatchableTaskFields<T extends object>(args: HideUnwatchableTaskFieldsArgs<T>): T {+ const task = args.task as Record<TaskWatchableField, unknown>;+ (Object.keys(TaskFieldPermissionsForWatching) as TaskWatchableField[]).forEach((key) => {+ if (!args.checker.hasPermissions(TaskFieldPermissionsForWatching[key])) {+ task[key] = null;+ }+ });+ return args.task;+}diff --git a/api/src/tv-modules/tasks/tasks.server.types.ts b/api/src/tv-modules/tasks/tasks.server.types.tsindex fd0b28a..138f157 100644--- a/api/src/tv-modules/tasks/tasks.server.types.ts+++ b/api/src/tv-modules/tasks/tasks.server.types.ts@@ -2,6 +2,7 @@ import { type } from 'arktype';import type { TaskItemInDb } from '../../types/tasks.types';import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';import { GoalPermissions } from '../../types/auth.types';+import type { GoalPermissionsChecker } from '../../core/GoalPermissionsChecker';export const TaskArkTypeFetchTaskByIdNew = type({taskId: type('string|number').pipe((v) => Number(v)),@@ -78,7 +79,8 @@ export type TaskArgUpdate = typeof TaskArkTypeUpdate.infer;// A list, kanban column or parent from another project would silently move the task there (a DB trigger derives// goal_id from the list), so updates must only reference the task's own project. Moving goes through /tasks/move.export type TaskReferenceCheckArgs = {- taskId: number;+ /** null when the task is being created: there is no task yet that a parent chain could loop back to */+ taskId: number | null;goalId: number;goalListId?: number | null;statusId?: number | null;@@ -135,6 +137,36 @@ export const TaskArkTypeAdd = type({export type TaskArgAdd = typeof TaskArkTypeAdd.infer;+export const TASK_CREATABLE_COLUMNS = [+ 'goalId',+ 'parentId',+ 'description',+ 'complete',+ 'goalListId',+ 'note',+ 'priorityId',+ 'startDate',+ 'endDate',+ 'startTime',+ 'endTime',+ 'statusId',+ 'taskOrder',+ 'kanbanOrder',+ 'amount',+ 'transactionType',+ 'nodeGraphPosition',+ 'estimateValue',+] as const satisfies ReadonlyArray<keyof TaskArgAdd>;++export type TaskInsertArgs = {+ data: TaskArgAdd;+ creatorId: number;+};++export type TaskAddResult =+ | { ok: true; tasks: TaskForClientNew[] }+ | { ok: false; reason: 'foreign_reference' };+export const TaskFieldPermissionsForEditOrCreation = {description: GoalPermissions.TASKS_CAN_EDIT_DESCRIPTION,note: GoalPermissions.TASKS_CAN_EDIT_NOTE,@@ -179,6 +211,13 @@ export const TaskFieldPermissionsForWatching = {nodeGraphPosition: GoalPermissions.COMPONENT_CAN_WATCH_CONTENT,};+export type TaskWatchableField = keyof typeof TaskFieldPermissionsForWatching;++export type HideUnwatchableTaskFieldsArgs<T extends object> = {+ task: T;+ checker: GoalPermissionsChecker;+};+export type TaskForClientNew = TasksSchemaTypeForSelect & {tags: number[];assignedUsers: number[];diff --git a/api/src/tv-modules/time-tracking/TimeTrackingManager.ts b/api/src/tv-modules/time-tracking/TimeTrackingManager.tsindex 7c460f6..2f52eb0 100644--- a/api/src/tv-modules/time-tracking/TimeTrackingManager.ts+++ b/api/src/tv-modules/time-tracking/TimeTrackingManager.ts@@ -233,7 +233,7 @@ export class TimeTrackingManager {if (filters.organizationId === undefined) return []const accessibleGoalIds = await this.user.permissionsFetcher.getAccessibleGoalIds(filters.organizationId,- [GoalPermissions.TIMETRACKING_CAN_VIEW, GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL],+ [GoalPermissions.TIMETRACKING_CAN_VIEW],)if (accessibleGoalIds.length === 0) return []@@ -284,10 +284,7 @@ export class TimeTrackingManager {}async getViewableGoalIds(organizationId: number): Promise<number[]> {- return this.user.permissionsFetcher.getAccessibleGoalIds(organizationId, [- GoalPermissions.TIMETRACKING_CAN_VIEW,- GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL,- ])+ return this.user.permissionsFetcher.getAccessibleGoalIds(organizationId, [GoalPermissions.TIMETRACKING_CAN_VIEW])}private async resolveReportFilters(req: TimeReportRequest): Promise<ResolvedReportFilters | null> {diff --git a/api/src/tv-modules/time-tracking/middlewares/can-access-time-entry.ts b/api/src/tv-modules/time-tracking/middlewares/can-access-time-entry.tsindex 16fe572..288bb53 100644--- a/api/src/tv-modules/time-tracking/middlewares/can-access-time-entry.ts+++ b/api/src/tv-modules/time-tracking/middlewares/can-access-time-entry.ts@@ -23,8 +23,7 @@ export const canAccessTimeEntry = (action: Action) => async (req: Request, res:if (action === 'view') {if (- checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW) ||- checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW)) {return next()}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.ts b/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.tsindex f112849..b85ba9e 100644--- a/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.ts+++ b/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.ts@@ -33,8 +33,7 @@ export const canFetchTimeEntries = async (req: Request, res: Response, next: Nex}if (- checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW) ||- checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW)) {return next()}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-log-time-on-task.ts b/api/src/tv-modules/time-tracking/middlewares/can-log-time-on-task.tsindex 07ec980..05bafa1 100644--- a/api/src/tv-modules/time-tracking/middlewares/can-log-time-on-task.ts+++ b/api/src/tv-modules/time-tracking/middlewares/can-log-time-on-task.ts@@ -18,8 +18,7 @@ export const canLogTimeOnTask = async (req: Request, res: Response, next: NextFu}if (- checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_LOG) ||- checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_LOG)) {return next()}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-view-time-stats.ts b/api/src/tv-modules/time-tracking/middlewares/can-view-time-stats.tsindex 892a2c2..f9d99be 100644--- a/api/src/tv-modules/time-tracking/middlewares/can-view-time-stats.ts+++ b/api/src/tv-modules/time-tracking/middlewares/can-view-time-stats.ts@@ -24,8 +24,7 @@ export const canViewTimeStats = (source: Source) => async (req: Request, res: Re}if (- checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW) ||- checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW)) {return next()}diff --git a/api/src/tv-modules/ui-preferences/types.ts b/api/src/tv-modules/ui-preferences/types.tsindex 30fc425..6b508fd 100644--- a/api/src/tv-modules/ui-preferences/types.ts+++ b/api/src/tv-modules/ui-preferences/types.ts@@ -1,4 +1,5 @@import { type } from 'arktype'+import { THEME_NEUTRAL_COLORS, THEME_PRIMARY_COLORS } from 'taskview-api'const MAX_SECTIONS = 20const MAX_ITEMS_PER_SECTION = 200@@ -42,6 +43,23 @@ const firstDayOfWeekArkType = type('number.integer').narrow((v, ctx) =>v >= 0 && v <= 6 ? true : ctx.mustBe('an integer 0..6 (0=Sunday)'),)+const hexColorArkType = type(/^#[0-9a-fA-F]{6}$/)++const CustomThemePaletteArkType = type({+ '+': 'reject',+ background: hexColorArkType,+ surface: hexColorArkType,+ border: hexColorArkType,+ text: hexColorArkType,+ accent: hexColorArkType,+})++const CustomThemeArkType = type({+ '+': 'reject',+ light: CustomThemePaletteArkType,+ dark: CustomThemePaletteArkType,+})+export const UiSettingsArkType = type({'firstDayOfWeek?': firstDayOfWeekArkType,'defaultProjectId?': 'number.integer >= 1',@@ -49,6 +67,11 @@ export const UiSettingsArkType = type({'taskSortBy?': "'date' | 'priority'",'taskSortFirstNew?': '0 | 1','showTaskId?': '0 | 1',+ 'keyboardShortcuts?': '0 | 1',+ 'primaryColor?': type.enumerated(...THEME_PRIMARY_COLORS),+ 'neutralColor?': type.enumerated(...THEME_NEUTRAL_COLORS),+ 'customTheme?': CustomThemeArkType,+ 'customThemeActive?': '0 | 1',})export type UiSettings = typeof UiSettingsArkType.inferdiff --git a/api/src/tv-modules/webhooks/WebhooksController.ts b/api/src/tv-modules/webhooks/WebhooksController.tsindex 964d114..cf9793b 100644--- a/api/src/tv-modules/webhooks/WebhooksController.ts+++ b/api/src/tv-modules/webhooks/WebhooksController.ts@@ -86,7 +86,7 @@ export class WebhooksController {};fetchDeliveries = async (req: Request, res: Response) => {- const data = WebhookArkTypeFetchDeliveries({ ...req.params, ...req.query });+ const data = WebhookArkTypeFetchDeliveries({ ...req.query, id: req.params.id });if (data instanceof ArkErrors) {return res.status(400).send(data.summary);}diff --git a/api/src/tv-modules/webhooks/WebhooksRoutes.ts b/api/src/tv-modules/webhooks/WebhooksRoutes.tsindex d3bdcb9..80b9651 100644--- a/api/src/tv-modules/webhooks/WebhooksRoutes.ts+++ b/api/src/tv-modules/webhooks/WebhooksRoutes.ts@@ -2,9 +2,13 @@ import { Router } from 'express'import type { Routable } from '../../types/routable.type'import { IsLoggedIn } from '../auth/middlewares/is-logged-in'import { WebhooksController } from './WebhooksController'-import { IsGoalOwnerByGoalId, IsGoalOwnerByWebhookId } from './middlewares/IsGoalOwner'-import { RequireTokenPermission } from '../../middlewares/require-token-permission';-import { GoalPermissions } from '../../types/auth.types';+import {+ CanCreateWebhook,+ CanManageWebhook,+ CanRetryWebhookDelivery,+ CanViewWebhookDeliveries,+ CanViewWebhooksOfGoal,+} from './middlewares/WebhooksPermission'export default class WebhooksRoutes implements Routable {private readonly router: ReturnType<typeof Router>@@ -21,15 +25,13 @@ export default class WebhooksRoutes implements Routable {}initRoutes() {- const canManageWebhooks = RequireTokenPermission(GoalPermissions.WEBHOOKS_CAN_MANAGE)-- this.router.get('', [IsLoggedIn, IsGoalOwnerByGoalId, canManageWebhooks], this.controller.fetch)- this.router.post('', [IsLoggedIn, IsGoalOwnerByGoalId, canManageWebhooks], this.controller.create)- this.router.patch('', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.update)- this.router.delete('', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.delete)- this.router.post('/rotate-secret', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.rotateSecret)- this.router.post('/test', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.testDelivery)- this.router.get('/deliveries/:id', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.fetchDeliveries)- this.router.post('/retry', [IsLoggedIn, IsGoalOwnerByWebhookId, canManageWebhooks], this.controller.retryDelivery)+ this.router.get('', [IsLoggedIn, CanViewWebhooksOfGoal], this.controller.fetch)+ this.router.post('', [IsLoggedIn, CanCreateWebhook], this.controller.create)+ this.router.patch('', [IsLoggedIn, CanManageWebhook], this.controller.update)+ this.router.delete('', [IsLoggedIn, CanManageWebhook], this.controller.delete)+ this.router.post('/rotate-secret', [IsLoggedIn, CanManageWebhook], this.controller.rotateSecret)+ this.router.post('/test', [IsLoggedIn, CanManageWebhook], this.controller.testDelivery)+ this.router.get('/deliveries/:id', [IsLoggedIn, CanViewWebhookDeliveries], this.controller.fetchDeliveries)+ this.router.post('/retry', [IsLoggedIn, CanRetryWebhookDelivery], this.controller.retryDelivery)}}diff --git a/api/src/tv-modules/webhooks/middlewares/IsGoalOwner.ts b/api/src/tv-modules/webhooks/middlewares/IsGoalOwner.tsdeleted file mode 100644index 752df13..0000000--- a/api/src/tv-modules/webhooks/middlewares/IsGoalOwner.ts+++ /dev/null@@ -1,39 +0,0 @@-import type { NextFunction, Request, Response } from 'express'-import { eq } from 'drizzle-orm'-import { GoalsSchema, WebhooksSchema } from 'taskview-db-schemas'-import { Database } from '../../../modules/db'--export const IsGoalOwnerByGoalId = async (req: Request, res: Response, next: NextFunction) => {- const goalId = Number(req.body.goalId || req.query.goalId)- const userId = req.appUser.getUserData()?.id-- if (!goalId || !userId) return res.status(400).end()-- const db = Database.getInstance()- const goals = await db.dbDrizzle- .select({ owner: GoalsSchema.owner })- .from(GoalsSchema)- .where(eq(GoalsSchema.id, goalId))-- if (!goals.length || goals[0].owner !== userId) return res.status(403).end()-- next()-}--export const IsGoalOwnerByWebhookId = async (req: Request, res: Response, next: NextFunction) => {- const webhookId = Number(req.body.id || req.params.id)- const userId = req.appUser.getUserData()?.id-- if (!webhookId || !userId) return res.status(400).end()-- const db = Database.getInstance()- const result = await db.dbDrizzle- .select({ owner: GoalsSchema.owner })- .from(WebhooksSchema)- .innerJoin(GoalsSchema, eq(WebhooksSchema.goalId, GoalsSchema.id))- .where(eq(WebhooksSchema.id, webhookId))-- if (!result.length || result[0].owner !== userId) return res.status(403).end()-- next()-}diff --git a/api/src/tv-modules/webhooks/middlewares/WebhooksPermission.ts b/api/src/tv-modules/webhooks/middlewares/WebhooksPermission.tsnew file mode 100644index 0000000..55c6c03--- /dev/null+++ b/api/src/tv-modules/webhooks/middlewares/WebhooksPermission.ts@@ -0,0 +1,48 @@+import type { NextFunction, Request, Response } from 'express'+import { GoalPermissions } from '../../../types/auth.types'+import type { WebhooksPermissionGuardArgs } from '../types'+import { WebhooksRepository } from '../WebhooksRepository'++const repository = new WebhooksRepository()++async function goalIdOfWebhook(webhookId: number): Promise<number | null> {+ return (await repository.fetchById(webhookId))?.goalId ?? null+}++async function goalIdOfDelivery(deliveryId: number): Promise<number | null> {+ const delivery = await repository.fetchDeliveryById(deliveryId)+ return delivery ? goalIdOfWebhook(delivery.webhookId) : null+}++function requireWebhooksPermission(args: WebhooksPermissionGuardArgs) {+ return async (req: Request, res: Response, next: NextFunction) => {+ const goalId = await args.resolveGoalId(req)+ if (!goalId) return res.status(403).end()++ const checker = await req.appUser.permissionsFetcher.getCheckerForGoal(goalId)+ if (!checker.hasPermissions(args.permission)) return res.status(403).end()++ return next()+ }+}++const goalInQuery = async (req: Request) => Number(req.query?.goalId) || null+const goalInBody = async (req: Request) => Number(req.body?.goalId) || null+const webhookInBody = async (req: Request) => {+ const webhookId = Number(req.body?.id)+ return webhookId ? goalIdOfWebhook(webhookId) : null+}+const webhookInPath = async (req: Request) => {+ const webhookId = Number(req.params?.id)+ return webhookId ? goalIdOfWebhook(webhookId) : null+}+const deliveryInBody = async (req: Request) => {+ const deliveryId = Number(req.body?.id)+ return deliveryId ? goalIdOfDelivery(deliveryId) : null+}++export const CanViewWebhooksOfGoal = requireWebhooksPermission({ permission: GoalPermissions.WEBHOOKS_CAN_VIEW, resolveGoalId: goalInQuery })+export const CanCreateWebhook = requireWebhooksPermission({ permission: GoalPermissions.WEBHOOKS_CAN_MANAGE, resolveGoalId: goalInBody })+export const CanManageWebhook = requireWebhooksPermission({ permission: GoalPermissions.WEBHOOKS_CAN_MANAGE, resolveGoalId: webhookInBody })+export const CanViewWebhookDeliveries = requireWebhooksPermission({ permission: GoalPermissions.WEBHOOKS_CAN_VIEW, resolveGoalId: webhookInPath })+export const CanRetryWebhookDelivery = requireWebhooksPermission({ permission: GoalPermissions.WEBHOOKS_CAN_MANAGE, resolveGoalId: deliveryInBody })diff --git a/api/src/tv-modules/webhooks/types.ts b/api/src/tv-modules/webhooks/types.tsindex eee796e..2b71c9f 100644--- a/api/src/tv-modules/webhooks/types.ts+++ b/api/src/tv-modules/webhooks/types.ts@@ -1,4 +1,6 @@import { type } from 'arktype';+import type { Request } from 'express';+import type { GoalPermissionType } from '../../types/auth.types';import { OUTBOUND_URL_ERROR_CODES } from '../../utils/outbound-url.types';import { FILE_EVENTS } from '../files/types';@@ -86,3 +88,8 @@ export interface WebhookDeliverJobData {payload: object;attempt: number;}++export type WebhooksPermissionGuardArgs = {+ permission: GoalPermissionType;+ resolveGoalId: (req: Request) => Promise<number | null>;+};diff --git a/api/src/types/app.types.ts b/api/src/types/app.types.tsindex b874ee2..43f8ad7 100644--- a/api/src/types/app.types.ts+++ b/api/src/types/app.types.ts@@ -28,6 +28,15 @@ export const AppEnvSchema = z.object({// Max invite emails one user may trigger per hour (default 30)INVITE_EMAIL_HOURLY_LIMIT: z.string().optional(),+ // Max login codes one account may request by email per hour (default 5)+ LOGIN_CODE_HOURLY_LIMIT: z.string().optional(),++ // Days a sign-in session lasts, however often its tokens are refreshed (default 90)+ SESSION_MAX_AGE_DAYS: z.string().optional(),++ // Let users delete their own account (default false)+ ALLOW_ACCOUNT_DELETION: z.string().optional(),+// Allow outgoing webhooks to target loopback/private/link-local addresses (default off, see SSRF)WEBHOOKS_ALLOW_PRIVATE_URLS: z.string().optional(),diff --git a/api/src/types/auth.types.ts b/api/src/types/auth.types.tsindex 5a0fa64..b34ec44 100644--- a/api/src/types/auth.types.ts+++ b/api/src/types/auth.types.ts@@ -11,6 +11,7 @@ export type UserDbRecord = {remind_password_code: string | null;remind_password_time: number | null;remember_token: string | null;+ login_code_attempts: number;};export const UserJwtPayloadSchema = z.object({@@ -22,6 +23,18 @@ export const UserJwtPayloadSchema = z.object({}),});+export type AuthTokenType = 'access' | 'refresh';++// A signed session token as it comes in: the session payload plus the token type+export const AuthTokenPayloadSchema = UserJwtPayloadSchema.extend({+ typ: z.enum(['access', 'refresh']),+});++export type ValidateTokenArgs = {+ token: string;+ type: AuthTokenType;+};+export const RegisterUserInDbSchema = z.object({login: z.string(),email: z.string().email(),@@ -51,9 +64,9 @@ export type RemindPassword = z.infer<typeof RemindPasswordSchema>;export const ChangePasswordDataScheme = z.object({login: z.string(),- code: z.string(),- password: z.string(),- passwordRepeat: z.string(),+ code: z.string().min(1).max(64),+ password: z.string().min(6).max(128),+ passwordRepeat: z.string().max(128),}).refine((data) => data.password === data.passwordRepeat, {message: "Passwords don't match",@@ -123,6 +136,46 @@ export type UpdateUserEmailArgs = {export type UpdateUserCredentialsResult = 'ok' | 'conflict' | 'error';+export type LoginCodeAttempt = {+ rememberToken: string;+ attempts: number;+};++export type ConsumeLoginCodeArgs = {+ userId: number;+ rememberToken: string;+};++export type ReserveLoginCodeSendArgs = {+ userId: number;+ hourlyLimit: number;+};++export type LoginCodeSendReservation = { allowed: true } | { allowed: false; retryAfterSeconds: number };++export type ConsumeReminderCodeArgs = {+ userId: number;+ code: string;+ /** unix seconds; a code issued before this moment has expired */+ issuedAfter: number;+};++export const DeleteAccountSchema = z.object({+ code: z.string().min(1).max(64),+});++export type AddDeleteAccountCodeArgs = {+ userId: number;+ code: string;+};++export type DeleteAccountByCodeArgs = {+ userId: number;+ code: string;+ /** seconds; a code issued longer ago than this has expired */+ ttlSeconds: number;+};+export const RefreshTokenSchema = z.object({refreshToken: z.string(),});@@ -199,6 +252,7 @@ export const GoalPermissions = {ORG_CAN_MANAGE_MEMBERS: 'org_can_manage_members',SSO_CAN_MANAGE: 'sso_can_manage',WEBHOOKS_CAN_MANAGE: 'webhooks_can_manage',+ WEBHOOKS_CAN_VIEW: 'webhooks_can_view',BILLING_CAN_MANAGE: 'billing_can_manage',SPRINT_CAN_VIEW: 'sprint_can_view',@@ -230,3 +284,11 @@ export type FetchPermissionsForGoalByUserParams = {userId: number;email: string;};++export type FetchPermissionsForGoalsParams = {+ goalIds: number[];+ userId: number;+ email: string;+};++export type GoalPermissionItemsWithGoalFromDb = (GoalPermissionItemsFromDb[number] & { goalId: number })[];diff --git a/api/src/utils/crypto.ts b/api/src/utils/crypto.tsindex c1b6478..bb49484 100644--- a/api/src/utils/crypto.ts+++ b/api/src/utils/crypto.ts@@ -1,4 +1,4 @@-import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';+import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from 'crypto';import { $logger } from '../modules/logget';const ALGORITHM = 'aes-256-gcm';@@ -47,3 +47,10 @@ export function decryptField(value: string | null): string | null {return value}}++export function safeEqual(a: string, b: string): boolean {+ // Hashing first gives equal-length buffers, so the comparison time does not depend on where the inputs differ+ const digestA = createHash('sha256').update(a, 'utf8').digest()+ const digestB = createHash('sha256').update(b, 'utf8').digest()+ return timingSafeEqual(digestA, digestB)+}diff --git a/docs/2.features/12.ui-customization.md b/docs/2.features/12.ui-customization.mdindex 735be93..bc0aa1b 100644--- a/docs/2.features/12.ui-customization.md+++ b/docs/2.features/12.ui-customization.md@@ -42,6 +42,10 @@ When a default project is set, a quick-jump button with the project name also apIf the default project is deleted or you lose access to it, TaskView falls back to the home screen. Choose "Home screen (default)" to turn the feature off.+### Keyboard shortcuts++Turns the single-key [keyboard shortcuts](/docs/features/keyboard-shortcuts) (`C`, `X`, `?`) on or off. They are on by default and work on a desktop screen only.+## How it is storedPreferences are saved automatically (no Save button) through the `ui-preferences` API and kept per user account. Resetting the browser or switching devices does not lose them.diff --git a/docs/2.features/14.scim.md b/docs/2.features/14.scim.mdindex c09f173..b0853a3 100644--- a/docs/2.features/14.scim.md+++ b/docs/2.features/14.scim.md@@ -17,12 +17,32 @@ SCIM works on top of an [SSO configuration](/docs/features/sso): each SSO config4. Click **Generate SCIM Token** and copy the token. It is shown only once; TaskView stores only its hash. **Regenerate Token** replaces it, and the old token stops working.5. In your IdP, set the SCIM base URL to the **SCIM Endpoint URL** shown in the card (`<API URL>/scim/v2`) and the token as a Bearer token.-Switching SCIM off deletes the token. To turn it back on, generate a new one.-::callout{icon="i-lucide-network" color="warning"}Behind a reverse proxy, set [`API_PUBLIC_URL`](/docs/configuration/environment-variables#application) so the SCIM Endpoint URL points to an address your IdP can reach.::+## Turning SCIM off++Switch off **SCIM Provisioning** in the SSO config card. Then:++- **The token is deleted.** Requests from the IdP are refused with `401`.+- **Nothing is removed.** People stay in the organization and its projects. SCIM users, the remembered access of deactivated users, groups and their project links stay in the database. The **Groups** list is hidden while SCIM is off.+- **Group links stop working**, since the IdP no longer sends changes.+- **SSO sign-in adds people again.** As without SCIM, anyone from the SSO domain who signs in is added to the organization with the default role (**member**).++::callout{icon="i-lucide-alert-triangle" color="warning"}+This includes people the IdP deactivated over SCIM. They get back into the organization with the default role and no projects: their remembered role and projects are restored only by a reactivation over SCIM. If they must stay out, block them at the IdP before you switch SCIM off.+::++### Turning it back on++1. Switch **SCIM Provisioning** on and click **Generate SCIM Token**: the old token is gone.+2. Put the new token into your IdP.++The kept SCIM users, groups and links apply again, and changes the IdP sends from then on are handled as usual. Changes made in the IdP while SCIM was off reach TaskView only if the IdP sends them again.++A deactivated person who got back in while SCIM was off stays in the organization, but their next SSO sign-in is refused, since their SCIM record is still deactivated. For the IdP they are already deactivated, so it may never send anything about them: remove them from the organization by hand.+## People| What the IdP does | What happens in TaskView |@@ -56,6 +76,17 @@ With SCIM off, SSO works as described in [User provisioning](/docs/features/sso#If you remove a person from the organization by hand while the IdP still has them as active, they come back with the SSO config's default role (**member**) at their next SSO sign-in. To keep someone out, deactivate them in the IdP.::+### When SSO and SCIM disagree++In the IdP, access to the application over SSO and provisioning over SCIM are often set up separately, so they can get out of step:++- **Deactivated over SCIM, but the IdP still lets them sign in.** TaskView refuses the sign-in: with the same address the person sees *"Your access to the organization is turned off"*, with an address SCIM has not seen *"You have not been added to the organization yet"*. Their sessions were already closed when SCIM deactivated them.+- **Blocked from signing in at the IdP, but still active over SCIM.** The IdP stops new sign-ins, but TaskView has not been told anything: the person stays in the organization and its projects, and sessions that are already open keep working until they expire.++::callout{icon="i-lucide-alert-triangle" color="warning"}+To take someone's access away completely, make sure the IdP deactivates or deletes them **over SCIM** (sends `active: false` or `DELETE`). Only that removes them from the organization and its projects and closes their sessions right away.+::+## Groups and projectsGroups sent by the IdP appear in the SSO config card under **SCIM Provisioning → Groups** (visible while SCIM is on), with the number of members. A group can be linked to one or more projects, each with a **default role**.diff --git a/docs/2.features/15.keyboard-shortcuts.md b/docs/2.features/15.keyboard-shortcuts.mdnew file mode 100644index 0000000..b4ac8aa--- /dev/null+++ b/docs/2.features/15.keyboard-shortcuts.md@@ -0,0 +1,40 @@+---+title: Keyboard Shortcuts+description: Add and complete tasks from the keyboard in TaskView - C for a new task, X to complete the open one, ? for the list of shortcuts, and how to turn them off.+navigation:+ icon: i-lucide-keyboard+---++TaskView has a few single-key shortcuts for the most frequent actions. Press **?** anywhere in the app, or open **Settings → Keyboard shortcuts** at the bottom of the settings page, to see the list.++## Shortcuts++### Everywhere++| Key | Action |+|---|---|+| `C` | New task. Opens the add-task dialog with the project and list you are looking at already selected; on the home screen it picks the project you used last, or the Inbox. The task appears right away in the open list, kanban board or graph. |+| `Cmd+K` / `Ctrl+K` | Search tasks. Type `#123` to find a task by its number. |+| `?` | Show the list of keyboard shortcuts. |+| `Esc` | Close a dialog or the open task. |++### Open task++| Key | Action |+|---|---|+| `X` | Mark the open task complete, or reopen it. Needs the permission to change the task status. |++## When shortcuts do not fire++- While you type in a text field, the task title or the note editor — the key is typed as usual.+- While a dropdown, a confirmation or the search is open over the page.+- With `Cmd`, `Ctrl` or `Alt` held, so `Cmd+C` still copies.+- On a phone-sized screen and in the mobile apps.++Letter shortcuts follow the physical key, so they work the same with any keyboard layout, including Cyrillic ones.++## Turning shortcuts off++If single-key shortcuts get in your way, for example they clash with a browser extension, turn them off in **Settings → UI customization → Others → Keyboard shortcuts**. The setting is personal and follows you across devices. `Cmd+K` and `Esc` keep working.++Choosing your own keys is not available yet.diff --git a/docs/2.features/7.webhooks.md b/docs/2.features/7.webhooks.mdindex c560864..e408e6d 100644--- a/docs/2.features/7.webhooks.md+++ b/docs/2.features/7.webhooks.md@@ -46,6 +46,19 @@ Webhooks let you receive HTTP POST requests when events happen in your projects.6. Click **"Add"**7. Copy the secret and store it securely - it will not be shown again+## Permissions++Two project permissions, in the **Webhooks** group of the role editor, decide who can work with webhooks:++| Permission | Allows |+|---|---|+| `webhooks_can_view` | See the project's webhooks with their URLs and events, and the delivery history including payloads |+| `webhooks_can_manage` | Create, edit, enable/disable, delete and test webhooks, rotate their secrets and retry deliveries. It does not include viewing: without `webhooks_can_view` the webhooks list and delivery history stay hidden |++The two permissions are independent: to see and change webhooks a member needs both. The project owner has both. Any other member gets them only through a role: neither permission is part of the default roles, so add them to a role in the role editor. A webhook sends every subscribed event of the project to its URL, so grant `webhooks_can_manage` only to people you trust with all project data, and `webhooks_can_view` only to people who may see the URLs - many receivers treat the URL itself as a secret.++API tokens and OAuth apps are narrowed as usual: a token restricted to some projects or permissions can only reach the webhooks those allow.+## Allowed destinationsA webhook URL must use `http` or `https` and point to a **public** address. URLs that resolve to loopback (`127.0.0.1`, `localhost`), private (`10/8`, `172.16/12`, `192.168/16`), link-local or cloud-metadata ranges are rejected when you save the webhook, and checked again before every delivery. Redirects are not followed: if your endpoint answers with a `3xx`, the delivery is recorded as failed with that status code.diff --git a/docs/4.configuration/1.environment-variables.md b/docs/4.configuration/1.environment-variables.mdindex c461800..e46d860 100644--- a/docs/4.configuration/1.environment-variables.md+++ b/docs/4.configuration/1.environment-variables.md@@ -48,10 +48,13 @@ Unlike everything else on this page, this variable is set on the **web app conta| `JWT_SIGN` | Yes | - | Secret key for signing JWT tokens. Use a long random string. || `ACCESS_LIFE_TIME` | No | `1d` | How long access tokens are valid. Examples: `1h`, `1d`, `7d` || `REFRESH_LIFE_TIME` | No | `2d` | How long refresh tokens are valid |+| `SESSION_MAX_AGE_DAYS` | No | `90` | How many days a sign-in session lasts. Refreshing tokens does not extend it: after this many days since sign-in the user has to sign in again. Must be a positive integer; anything else stops the server at startup. || `JWT_ALG` | No | `HS256` | JWT signing algorithm || `AUTH_LOGIN_METHODS` | No | all enabled | Comma-separated list of login methods to offer: `magic-link`, `password`, `sso`, `social`. Disabled methods disappear from the login page and their API endpoints return 403. The API refuses to start if the list contains a typo or disables every method. |+| `LOGIN_CODE_HOURLY_LIMIT` | No | `5` | Maximum sign-in codes one account can request by email per hour. Each code also stops working after 5 wrong attempts. Must be a positive integer; anything else stops the server at startup. || `PASSWORD_CHANGE_CONFIRMATION` | No | `email` | How account password changes are confirmed: `email` — a confirmation code is sent to the user's email (requires SMTP); `password` — the user confirms with their current password (works without SMTP, recommended for installs without a mail server). || `ALLOW_PUBLIC_REGISTRATION` | No | `true` | Set to `false` to close the instance: strangers can no longer create accounts — the registration endpoint returns 403, and magic-link / social sign-in stop auto-creating users. Emails invited to an organization or project can still sign in and get their account created on first login. |+| `ALLOW_ACCOUNT_DELETION` | No | `false` | Whether users may delete their own account from **Settings**. Off by default: on a company install an admin decides who has access (by removing the member from the organization, or deactivating them over SCIM), and one person must not be able to wipe the projects they created for the team. While off, the **Delete account** button is hidden and the deletion endpoints return 403. Set to `true` on a public instance where people sign up by themselves. Deleting an account also deletes the projects and organizations the user owns. The value must be `true` or `false`; anything else stops the server at startup. || `OAUTH_DYNAMIC_REGISTRATION` | No | `false` | Whether AI clients may register themselves as OAuth clients (RFC 7591) when connecting to the [MCP server](/docs/integrations/mcp#oauth-cloud-clients). Off by default: the registration endpoint returns 403 and cloud clients such as ChatGPT or Claude cannot start an OAuth connection. Set to `true` to let them connect. Turning it back off later does not affect apps that are already connected. || `SSO_TRUSTED_DOMAINS` | No | empty | Comma-separated email domains that skip DNS/HTTP ownership checks for SSO (air-gapped / closed-network installs). Example: `company.com,corp.local`. On a public instance leave this unset so every org must prove it owns the domain. || `SSO_ALLOW_PRIVATE_URLS` | No | `false` | The server fetches SAML IdP metadata (the **Sync** button) and the SSO domain-ownership file. Those URLs may only point to public addresses: loopback, private, link-local and cloud-metadata ranges are refused, also when a public-looking host name resolves to them, and redirects are not followed. Set to `true` on a self-hosted install whose identity provider (Keycloak, Authentik) lives on the same private network. The value must be `true` or `false`; anything else stops the server at startup. |@@ -328,6 +331,12 @@ REFRESH_LIFE_TIME="9d"# Login methods offered on the login page (unset = all enabled)#AUTH_LOGIN_METHODS="magic-link,password,sso,social"+# Max sign-in codes one account can request by email per hour+#LOGIN_CODE_HOURLY_LIMIT=5+# Days a sign-in session lasts, however often its tokens are refreshed+#SESSION_MAX_AGE_DAYS=90+# Let users delete their own account (off by default: admins remove accounts)+#ALLOW_ACCOUNT_DELETION=false# Password change confirmation: "email" (code by email, needs SMTP) or "password" (no SMTP needed)#PASSWORD_CHANGE_CONFIRMATION="email"# Air-gapped SSO: skip DNS/HTTP domain proof for these email domainsdiff --git a/docs/4.configuration/2.authentication.md b/docs/4.configuration/2.authentication.mdindex d338bd1..bf48896 100644--- a/docs/4.configuration/2.authentication.md+++ b/docs/4.configuration/2.authentication.md@@ -22,6 +22,19 @@ Disabled methods disappear from the login page and their API endpoints return 40The API refuses to start if `AUTH_LOGIN_METHODS` contains an unknown value or disables every method — a broken config can't silently lock everyone out.::+## Email code++Users enter their email and receive a 6-digit sign-in code, valid for 5 minutes. To keep the short code from being guessed:++- a code stops working after 5 wrong attempts, and the user has to request a new one;+- a new code can be requested at most once a minute;+- one account can request at most `LOGIN_CODE_HOURLY_LIMIT` codes per hour (default `5`).++```env+# Max sign-in codes one account can request by email per hour+LOGIN_CODE_HOURLY_LIMIT=5+```+## Email and passwordThis is the default method and works out of the box. Users register with an email and password, and log in the same way (email conformation is required).@@ -81,4 +94,8 @@ You can adjust token lifetimes with the `ACCESS_LIFE_TIME` and `REFRESH_LIFE_TIM## Account deletion-Users can delete their own account from the account settings page. This is a two-step process - they request a deletion code (sent by email if SMTP is configured), then confirm. Account deletion removes all personal data (You cannot undo this action. You can only restore the data from a backup, if you have one.).+Self-service account deletion is **off by default**. On a company install an admin decides who has access, and one person must not be able to wipe the projects they created for the team. While it is off, the **Delete account** button is hidden from the settings page and the deletion endpoints return 403.++Set `ALLOW_ACCOUNT_DELETION=true` to let users delete their own account, for example on a public instance where people sign up by themselves. Deletion is then a two-step process: the user requests a deletion code by email (needs SMTP), then enters it. The code works for 15 minutes, and requesting a new one cancels the previous code. Deletion cannot be started with an API token.++Deleting an account removes all personal data, together with the projects and organizations the user owns. You cannot undo this action; the data can only be restored from a backup, if you have one.diff --git a/taskview-packages/taskview-api/src/api/__tests__/account-deletion.test.ts b/taskview-packages/taskview-api/src/api/__tests__/account-deletion.test.tsnew file mode 100644index 0000000..7748ce3--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/account-deletion.test.ts@@ -0,0 +1,136 @@+import axios from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, initApi } from './init-api'+import { openTestDb } from './test-db'+import { authHeaders, bearerStatus, createSessionUser } from './auth-test-helpers'+import type { AuthTestContext, SessionUser } from './auth-test-helpers.types'++const ctx = {} as AuthTestContext++beforeAll(async () => {+ const init = await initApi()+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Account deletion org ${Date.now()}` })+ ctx.orgId = org.id+})++afterAll(async () => {+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+})++/** A user who has requested an account deletion code; the code is read from the DB. */+async function userWithDeletionCode(): Promise<{ user: SessionUser, code: string }> {+ const user = await createSessionUser({ ctx, prefix: 'del' })+ const sent = await axios.post(`${API_URL}/module/auth/delete/account/code`, {}, authHeaders(user.access))+ expect(sent.status).toBe(200)+ const row = await ctx.db.query<{ code: string }>(+ 'select code from tv_auth.account_deletion where user_id = $1',+ [user.id]+ )+ return { user, code: row.rows[0].code }+}++async function deleteAccount(access: string, code: string) {+ return axios.post(`${API_URL}/module/auth/delete/account`, { code }, authHeaders(access))+}++async function userExists(userId: number): Promise<boolean> {+ const row = await ctx.db.query('select 1 from tv_auth.users where id = $1', [userId])+ return (row.rowCount ?? 0) > 0+}++const INVALID_CODE = { reason: 'invalid_or_expired_code' }+const CODE_TTL_S = 15 * 60++describe('deleting an account', () => {+ it('tells the settings page that deletion is allowed on this stack', async () => {+ const user = await createSessionUser({ ctx, prefix: 'del' })++ const res = await axios.get(`${API_URL}/module/auth/delete/account/options`, authHeaders(user.access))++ expect(res.status).toBe(200)+ expect(res.data).toEqual({ allowed: true })+ })++ it('keeps the account when the code is wrong', async () => {+ const { user } = await userWithDeletionCode()++ const res = await deleteAccount(user.access, 'wrong-code-0')++ expect(res.status).toBe(400)+ expect(res.data).toEqual(INVALID_CODE)+ expect(await userExists(user.id)).toBe(true)+ })++ it('keeps the account when the code is older than 15 minutes', async () => {+ const { user, code } = await userWithDeletionCode()+ await ctx.db.query(+ `update tv_auth.account_deletion set created_at = created_at - make_interval(secs => $1) where user_id = $2`,+ [CODE_TTL_S + 60, user.id]+ )++ const res = await deleteAccount(user.access, code)++ expect(res.status).toBe(400)+ expect(res.data).toEqual(INVALID_CODE)+ expect(await userExists(user.id)).toBe(true)+ })++ it('refuses a request without a code', async () => {+ const { user } = await userWithDeletionCode()++ const res = await axios.post(`${API_URL}/module/auth/delete/account`, {}, authHeaders(user.access))++ expect(res.status).toBe(400)+ expect(await userExists(user.id)).toBe(true)+ })++ it("does not delete either account with another user's code", async () => {+ const victim = await userWithDeletionCode()+ const attacker = await userWithDeletionCode()++ const res = await deleteAccount(attacker.user.access, victim.code)++ expect(res.status).toBe(400)+ expect(await userExists(victim.user.id)).toBe(true)+ expect(await userExists(attacker.user.id)).toBe(true)+ })++ it('a new code replaces the previous one', async () => {+ const { user, code: first } = await userWithDeletionCode()+ const again = await axios.post(`${API_URL}/module/auth/delete/account/code`, {}, authHeaders(user.access))+ expect(again.status).toBe(200)++ const res = await deleteAccount(user.access, first)++ expect(res.status).toBe(400)+ expect(await userExists(user.id)).toBe(true)+ })++ it('cannot be requested or confirmed with an API token', async () => {+ const { user, code } = await userWithDeletionCode()+ const created = await axios.post(`${API_URL}/module/api-tokens`, { name: 'Deletion test token' }, authHeaders(user.access))+ expect(created.status).toBe(200)+ const apiToken = created.data.response.token as string++ const sendCode = await axios.post(`${API_URL}/module/auth/delete/account/code`, {}, authHeaders(apiToken))+ const confirm = await deleteAccount(apiToken, code)++ expect(sendCode.status).toBe(403)+ expect(confirm.status).toBe(403)+ expect(await userExists(user.id)).toBe(true)+ })++ it('deletes the account with its own code and ends its session', async () => {+ const { user, code } = await userWithDeletionCode()++ const res = await deleteAccount(user.access, code)++ expect(res.status).toBe(200)+ expect(res.data).toEqual({ response: { del: true } })+ expect(await userExists(user.id)).toBe(false)+ expect(await bearerStatus(user.access)).toBe(401)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/auth-sessions.test.ts b/taskview-packages/taskview-api/src/api/__tests__/auth-sessions.test.tsnew file mode 100644index 0000000..04bab9d--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/auth-sessions.test.ts@@ -0,0 +1,123 @@+import axios from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, initApi } from './init-api'+import { openTestDb } from './test-db'+import { authHeaders, bearerStatus, createSessionUser, decodeJwt, setPassword, signInWithPassword } from './auth-test-helpers'+import type { AuthTestContext, SessionUser } from './auth-test-helpers.types'++const PASSWORD = 'Sessions-pass-1!'++const ctx = {} as AuthTestContext++beforeAll(async () => {+ const init = await initApi()+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Auth sessions org ${Date.now()}` })+ ctx.orgId = org.id+})++afterAll(async () => {+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+})++/** A user signed in twice: the session from the login code and a second one by password. */+async function userWithTwoSessions(): Promise<{ user: SessionUser, second: string }> {+ const user = await createSessionUser({ ctx, prefix: 'ses' })+ await setPassword({ ctx, user, password: PASSWORD })+ // The reset ended the first session; sign in twice again+ const first = await signInWithPassword(user.email, PASSWORD)+ const second = await signInWithPassword(user.email, PASSWORD)+ expect(first.status).toBe(200)+ expect(second.status).toBe(200)+ return { user: { ...user, access: first.data.access, refresh: first.data.refresh }, second: second.data.access }+}++function sessionId(token: string): number {+ return decodeJwt(token).id as number+}++describe('managing sign-in sessions', () => {+ it('lists the sessions of the caller only, marking the current one', async () => {+ const { user, second } = await userWithTwoSessions()+ const stranger = await createSessionUser({ ctx, prefix: 'ses' })++ const res = await axios.get(`${API_URL}/module/sessions`, authHeaders(user.access))++ expect(res.status).toBe(200)+ const ids = res.data.response.map((s: { id: number }) => s.id)+ expect(ids).toEqual(expect.arrayContaining([sessionId(user.access), sessionId(second)]))+ expect(ids).not.toContain(sessionId(stranger.access))+ const current = res.data.response.filter((s: { isCurrent: boolean }) => s.isCurrent)+ expect(current.map((s: { id: number }) => s.id)).toEqual([sessionId(user.access)])+ })++ it("cannot end another user's session", async () => {+ const attacker = await createSessionUser({ ctx, prefix: 'ses' })+ const victim = await createSessionUser({ ctx, prefix: 'ses' })++ await axios.delete(`${API_URL}/module/sessions`, { ...authHeaders(attacker.access), data: { id: sessionId(victim.access) } })++ expect(await bearerStatus(victim.access)).toBe(200)+ })++ it('cannot end the current session through the session list', async () => {+ const user = await createSessionUser({ ctx, prefix: 'ses' })++ const res = await axios.delete(`${API_URL}/module/sessions`, { ...authHeaders(user.access), data: { id: sessionId(user.access) } })++ expect(res.status).toBe(400)+ expect(await bearerStatus(user.access)).toBe(200)+ })++ it('ends one other session of the caller', async () => {+ const { user, second } = await userWithTwoSessions()++ const res = await axios.delete(`${API_URL}/module/sessions`, { ...authHeaders(user.access), data: { id: sessionId(second) } })++ expect(res.status).toBe(200)+ expect(await bearerStatus(second)).toBe(401)+ expect(await bearerStatus(user.access)).toBe(200)+ })++ it('signs out everywhere else while keeping the current session', async () => {+ const { user, second } = await userWithTwoSessions()++ const res = await axios.delete(`${API_URL}/module/sessions/all`, authHeaders(user.access))++ expect(res.status).toBe(200)+ expect(await bearerStatus(second)).toBe(401)+ expect(await bearerStatus(user.access)).toBe(200)+ })+})++describe('account endpoints refuse API tokens', () => {+ it('sessions, password change and credentials change answer 403 to an API token', async () => {+ const user = await createSessionUser({ ctx, prefix: 'ses' })+ const created = await axios.post(`${API_URL}/module/api-tokens`, { name: 'Auth test token' }, authHeaders(user.access))+ expect(created.status).toBe(200)+ const apiToken = created.data.response.token as string+ expect(apiToken).toMatch(/^tvk_/)++ const calls = [+ axios.get(`${API_URL}/module/sessions`, authHeaders(apiToken)),+ axios.delete(`${API_URL}/module/sessions/all`, authHeaders(apiToken)),+ axios.post(`${API_URL}/module/auth/password/change/code`, {}, authHeaders(apiToken)),+ axios.post(+ `${API_URL}/module/auth/password/change`,+ { code: 'x', password: 'Api-pass-1!', passwordRepeat: 'Api-pass-1!' },+ authHeaders(apiToken)+ ),+ axios.post(+ `${API_URL}/module/auth/credentials/change`,+ { currentPassword: 'x', login: 'apitoken', email: '[email protected]', password: 'Api-pass-1!', passwordRepeat: 'Api-pass-1!' },+ authHeaders(apiToken)+ ),+ ]+ for (const res of await Promise.all(calls)) {+ expect(res.status, `${res.config.method} ${res.config.url}`).toBe(403)+ }+ expect(await bearerStatus(user.access)).toBe(200)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/auth-test-helpers.ts b/taskview-packages/taskview-api/src/api/__tests__/auth-test-helpers.tsnew file mode 100644index 0000000..783cffd--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/auth-test-helpers.ts@@ -0,0 +1,116 @@+import axios from 'axios'+import { createHmac } from 'crypto'+import fs from 'fs'+import path from 'path'+import { expect } from 'vitest'+import { API_URL } from './init-api'+import type { CreateSessionUserArgs, SessionUser, SetPasswordArgs, SignJwtArgs } from './auth-test-helpers.types'++export const noThrow = { validateStatus: () => true }++let emailSeq = 0++function readStackEnv(): Record<string, string> {+ const content = fs.readFileSync(path.resolve(__dirname, 'docker/.env.taskview'), 'utf8')+ return Object.fromEntries(+ content+ .split('\n')+ .filter(line => line.includes('=') && !line.startsWith('#'))+ .map((line) => {+ const [key, ...rest] = line.split('=')+ return [key.trim(), rest.join('=').trim()]+ })+ )+}++/** The JWT key of the test stack, to forge tokens the API must accept or refuse. */+export const STACK_JWT_SIGN = readStackEnv().JWT_SIGN++/**+ * A fresh account with one signed-in session. The stack is a closed instance, so the+ * email is invited to the context org first; the emailed login code is read from the DB.+ */+export async function createSessionUser(args: CreateSessionUserArgs): Promise<SessionUser> {+ const email = `${args.prefix}-${Date.now()}-${emailSeq++}@auth.example`+ await args.ctx.ownerApi.organizations.addMember({ organizationId: args.ctx.orgId, email, role: 'member' })+ expect((await axios.post(`${API_URL}/module/auth/send-login-code`, { email })).status).toBe(200)++ const user = await args.ctx.db.query<{ id: number, login: string, remember_token: string }>(+ 'select id, login, remember_token from tv_auth.users where email = $1',+ [email]+ )+ const code = user.rows[0].remember_token.split(':')[0]+ const session = await axios.post(`${API_URL}/module/auth/login-by-code`, { email, code })+ expect(session.status).toBe(200)++ return {+ id: user.rows[0].id,+ email,+ login: user.rows[0].login,+ access: session.data.access,+ refresh: session.data.refresh,+ }+}++/** Gives a code-created account a known password through the reset flow. */+export async function setPassword(args: SetPasswordArgs): Promise<void> {+ expect((await axios.post(`${API_URL}/module/auth/email/recovery`, { email: args.user.email })).status).toBe(200)+ const row = await args.ctx.db.query<{ remind_password_code: string }>(+ 'select remind_password_code from tv_auth.users where id = $1',+ [args.user.id]+ )+ const reset = await axios.post(`${API_URL}/module/auth/password/reset`, {+ login: args.user.login,+ code: row.rows[0].remind_password_code,+ password: args.password,+ passwordRepeat: args.password,+ })+ expect(reset.status).toBe(200)+}++export async function signInWithPassword(login: string, password: string) {+ return axios.post(`${API_URL}/module/auth/login`, { login, password }, noThrow)+}++/** Status of a request that needs a signed-in session: 200 when the token is accepted as a bearer. */+export async function bearerStatus(token: string): Promise<number> {+ const res = await axios.get(`${API_URL}/module/auth/password/change/mode`, {+ headers: { Authorization: `Bearer ${token}` },+ ...noThrow,+ })+ return res.status+}++export async function refreshWith(token: string) {+ return axios.post(`${API_URL}/module/auth/refresh/token`, { refreshToken: token }, noThrow)+}++export function authHeaders(token: string) {+ return { headers: { Authorization: `Bearer ${token}` }, ...noThrow }+}++function base64Url(value: string | Buffer): string {+ return Buffer.from(value).toString('base64url')+}++/** An HS256 JWT, signed like the API signs its session tokens unless another key is given. */+export function signJwt(args: SignJwtArgs): string {+ const now = Math.floor(Date.now() / 1000)+ const header = base64Url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }))+ const body = base64Url(JSON.stringify({ ...args.payload, iat: now, exp: now + (args.expiresIn ?? 3600) }))+ const signature = createHmac('sha256', args.key ?? STACK_JWT_SIGN).update(`${header}.${body}`).digest()+ return `${header}.${body}.${base64Url(signature)}`+}++/** An unsigned JWT with alg "none". */+export function unsignedJwt(payload: Record<string, unknown>): string {+ const now = Math.floor(Date.now() / 1000)+ const header = base64Url(JSON.stringify({ alg: 'none', typ: 'JWT' }))+ const body = base64Url(JSON.stringify({ ...payload, iat: now, exp: now + 3600 }))+ return `${header}.${body}.`+}++/** The payload of a JWT, without verifying it. */+export function decodeJwt(token: string): Record<string, unknown> {+ return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'))+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/auth-test-helpers.types.ts b/taskview-packages/taskview-api/src/api/__tests__/auth-test-helpers.types.tsnew file mode 100644index 0000000..a314c5e--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/auth-test-helpers.types.ts@@ -0,0 +1,36 @@+import type { Client } from 'pg'+import type { TvApi } from '@/tv'++export type AuthTestContext = {+ ownerApi: TvApi+ db: Client+ orgId: number+}++export type SessionUser = {+ id: number+ email: string+ login: string+ access: string+ refresh: string+}++export type CreateSessionUserArgs = {+ ctx: AuthTestContext+ /** short: tv_auth.users.email is varchar(50) */+ prefix: string+}++export type SetPasswordArgs = {+ ctx: AuthTestContext+ user: SessionUser+ password: string+}++export type SignJwtArgs = {+ payload: Record<string, unknown>+ /** defaults to the stack's JWT_SIGN */+ key?: string+ /** seconds from now; negative for an already expired token */+ expiresIn?: number+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/auth-tokens.test.ts b/taskview-packages/taskview-api/src/api/__tests__/auth-tokens.test.tsnew file mode 100644index 0000000..23af0dd--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/auth-tokens.test.ts@@ -0,0 +1,173 @@+import axios from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, initApi } from './init-api'+import { openTestDb } from './test-db'+import {+ authHeaders,+ bearerStatus,+ createSessionUser,+ decodeJwt,+ refreshWith,+ setPassword,+ signInWithPassword,+ signJwt,+ unsignedJwt,+} from './auth-test-helpers'+import type { AuthTestContext } from './auth-test-helpers.types'++// SESSION_MAX_AGE_DAYS is not set on the test stack, so the default applies+const SESSION_MAX_AGE_DAYS = 90+const PASSWORD = 'Tokens-pass-1!'++const ctx = {} as AuthTestContext++beforeAll(async () => {+ const init = await initApi()+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Auth tokens org ${Date.now()}` })+ ctx.orgId = org.id+})++afterAll(async () => {+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+})++describe('session tokens', () => {+ it('marks the access and the refresh token with their type', async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })++ expect(decodeJwt(user.access).typ).toBe('access')+ expect(decodeJwt(user.refresh).typ).toBe('refresh')+ })++ it('refreshes by the refresh token into a working access token', async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })++ const res = await refreshWith(user.refresh)++ expect(res.status).toBe(200)+ expect(await bearerStatus(res.data.access)).toBe(200)+ })++ it('does not accept a refresh token as a bearer token', async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })++ expect(await bearerStatus(user.refresh)).toBe(401)+ })++ it('does not exchange an access token for new tokens', async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })++ const res = await refreshWith(user.access)++ expect(res.status).toBe(400)+ expect(res.data?.access).toBeUndefined()+ })++ it('refuses a session token without a valid type, even while its session is alive', async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })+ const { id, userData } = decodeJwt(user.access)+ const untyped = signJwt({ payload: { id, userData } })+ const unknownType = signJwt({ payload: { id, userData, typ: 'admin' } })++ for (const token of [untyped, unknownType]) {+ expect(await bearerStatus(token)).toBe(401)+ expect((await refreshWith(token)).status).toBe(400)+ }+ expect(await bearerStatus(user.access)).toBe(200)+ })++ it('refuses forged, unsigned, expired and malformed tokens', async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })+ const { id, userData } = decodeJwt(user.access)++ const otherKey = signJwt({ payload: { id, userData, typ: 'access' }, key: 'not-the-server-key' })+ const unsigned = unsignedJwt({ id, userData, typ: 'access' })+ const expired = signJwt({ payload: { id, userData, typ: 'access' }, expiresIn: -60 })++ for (const token of [otherKey, unsigned, expired, 'not-a-jwt']) {+ expect(await bearerStatus(token), token).toBe(401)+ }+ for (const token of [otherKey, unsigned, 'not-a-jwt']) {+ expect((await refreshWith(token)).status, token).toBe(400)+ }+ })++ it('refuses a validly signed JWT that is not a session token', async () => {+ // e.g. the OAuth state of git integrations is signed with the same key+ const state = signJwt({ payload: { userId: 1, projectId: 1, provider: 'github', nonceHash: 'x' } })++ expect(await bearerStatus(state)).toBe(401)+ expect((await refreshWith(state)).status).toBe(400)+ })++ it('ends the session on logout: neither token works afterwards', async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })++ const res = await axios.post(`${API_URL}/module/auth/logout`, {}, authHeaders(user.access))+ expect(res.status).toBe(204)++ expect(await bearerStatus(user.access)).toBe(401)+ expect((await refreshWith(user.refresh)).status).toBe(401)+ })++ it(`ends a session ${SESSION_MAX_AGE_DAYS} days after sign-in, however it was refreshed`, async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })+ const fresh = await refreshWith(user.refresh)+ expect(fresh.status).toBe(200)++ const { id } = decodeJwt(user.access)+ await ctx.db.query(+ `update tv_auth.user_tokens set time_creation = now() - make_interval(days => $1) - interval '1 minute' where id = $2`,+ [SESSION_MAX_AGE_DAYS, id]+ )++ expect(await bearerStatus(user.access)).toBe(401)+ expect(await bearerStatus(fresh.data.access)).toBe(401)+ expect((await refreshWith(user.refresh)).status).toBe(401)+ })++ it('stops a blocked user: the session token and the password are refused', async () => {+ const user = await createSessionUser({ ctx, prefix: 'tok' })+ await setPassword({ ctx, user, password: PASSWORD })+ const signIn = await signInWithPassword(user.email, PASSWORD)+ expect(signIn.status).toBe(200)++ await ctx.db.query('update tv_auth.users set block = 1 where id = $1', [user.id])++ expect(await bearerStatus(signIn.data.access)).toBe(401)+ expect((await signInWithPassword(user.email, PASSWORD)).status).toBe(403)+ })+})++describe('password sign-in', () => {+ it('answers a wrong password and an unknown user the same way', async () => {+ const user = await createSessionUser({ ctx, prefix: 'pw' })+ await setPassword({ ctx, user, password: PASSWORD })++ const wrong = await signInWithPassword(user.email, 'Wrong-pass-1!')+ const unknown = await signInWithPassword(`nobody-${Date.now()}@auth.example`, PASSWORD)++ expect(wrong.status).toBe(400)+ expect(unknown.status).toBe(wrong.status)+ expect(unknown.data).toEqual(wrong.data)+ })++ it('does not confirm an email with a wrong code', async () => {+ const user = await createSessionUser({ ctx, prefix: 'pw' })+ await ctx.db.query(+ `update tv_auth.users set block = 1, confirm_email_code = 'right-code-123' where id = $1`,+ [user.id]+ )++ await axios.get(`${API_URL}/module/auth/confirm/email/wrong-code-123/login/${user.login}`, { validateStatus: () => true })+ const afterWrong = await ctx.db.query<{ block: number }>('select block from tv_auth.users where id = $1', [user.id])+ expect(afterWrong.rows[0].block).toBe(1)++ await axios.get(`${API_URL}/module/auth/confirm/email/right-code-123/login/${user.login}`, { validateStatus: () => true })+ const afterRight = await ctx.db.query<{ block: number }>('select block from tv_auth.users where id = $1', [user.id])+ expect(afterRight.rows[0].block).toBe(0)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.tsindex c44bdba..8828ebf 100644--- a/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts@@ -90,6 +90,22 @@ describe('Automations permission boundaries', () => {await expectApiError({ request: memberApi.automations.getOptions({ goalId: p.goalId, source: 'tags.goalTags' }), status: 403 })})+ it('does not let automation_can_manage alone read the rules', async () => {+ const p = await project()+ await ownerApi.automations.createRule(createdAddsTag(p, p.tagAId))+ await share(p.goalId, [TvPermissions.AUTOMATION_CAN_MANAGE])++ await expectApiError({ request: memberApi.automations.listRules(p.goalId), status: 403 })+ })++ it('does not offer columns or tags as rule values for manage-only kanban and tag permissions', async () => {+ const p = await project()+ await share(p.goalId, [TvPermissions.AUTOMATION_CAN_VIEW, TvPermissions.KANBAN_CAN_MANAGE, TvPermissions.TASK_CAN_EDIT_TAGS])++ await expectApiError({ request: memberApi.automations.getOptions({ goalId: p.goalId, source: 'kanban.statuses' }), status: 403 })+ await expectApiError({ request: memberApi.automations.getOptions({ goalId: p.goalId, source: 'tags.goalTags' }), status: 403 })+ })+it('refuses a rule whose action needs a permission the author does not have', async () => {const p = await project()await share(p.goalId, [TvPermissions.AUTOMATION_CAN_MANAGE, TvPermissions.TASK_CAN_EDIT_TAGS])diff --git a/taskview-packages/taskview-api/src/api/__tests__/collaboration-roles-token-scope.test.ts b/taskview-packages/taskview-api/src/api/__tests__/collaboration-roles-token-scope.test.tsnew file mode 100644index 0000000..f762f7c--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/collaboration-roles-token-scope.test.ts@@ -0,0 +1,293 @@+import type { TvApi } from '@/tv'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { initApi } from './init-api'+import { openTestDb } from './test-db'+import { createSessionUser } from './auth-test-helpers'+import type { AuthTestContext } from './auth-test-helpers.types'+import { clientFor } from './start-test-helpers'+import type { RolesScopeFixture, RolesScopeTokenArgs } from './collaboration-roles-token-scope.test.types'++/**+ * Role management (/module/collaborationroles) and webhooks are guarded by project+ * ownership. A token acts as its issuer, so the ownership check alone lets a token+ * issued for project A, or a read-only token, create, delete and rewire roles —+ * and manage webhooks — in every project the issuer owns. These tests pin the+ * token scope on top of ownership: the goal must be in allowedGoalIds and the+ * matching permission must survive the token's allowedPermissions.+ *+ * Every write is verified through the owner session, not only by the status code.+ */+const ctx = {} as AuthTestContext+const fx = {} as RolesScopeFixture+const tokenIds: number[] = []++async function tokenClient(args: RolesScopeTokenArgs): Promise<TvApi> {+ const created = await fx.ownerApi.apiTokens.create({+ name: `roles-scope-${Date.now()}-${Math.random()}`,+ allowedPermissions: args.allowedPermissions,+ allowedGoalIds: args.allowedGoalIds,+ })+ tokenIds.push(created!.item.id)+ return clientFor(created!.token)+}++const statusOf = async (call: Promise<unknown>) =>+ call.then(() => 200).catch((err) => err.status ?? err.response?.status)++async function freshRole(goalId: number): Promise<number> {+ const role = await fx.ownerApi.collaboration.createRoleForGoal({ goalId, roleName: `scope-role-${Date.now()}-${Math.random()}` })+ return role!.id+}++async function rolePermissionIds(goalId: number, roleId: number): Promise<number[]> {+ const matrix = await fx.ownerApi.collaboration.fetchRoleToPermissionsForGoal(goalId)+ return matrix!+ .filter((r) => r.roleId === roleId)+ .map((r) => r.permissionId)+ .filter((id): id is number => id !== null)+}++async function roleNames(goalId: number): Promise<string[]> {+ return (await fx.ownerApi.collaboration.fetchRolesForGoal(goalId))!.map((r) => r.name)+}++async function roleIds(goalId: number): Promise<number[]> {+ return (await fx.ownerApi.collaboration.fetchRolesForGoal(goalId))!.map((r) => r.id)+}++async function webhookIds(goalId: number): Promise<number[]> {+ return (await fx.ownerApi.webhooks.fetch(goalId))!.map((w) => w.id)+}++beforeAll(async () => {+ const init = await initApi()+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Roles scope org ${Date.now()}` })+ ctx.orgId = org.id++ fx.owner = await createSessionUser({ ctx, prefix: 'roles' })+ fx.ownerApi = clientFor(fx.owner.access)++ const permissions = await fx.ownerApi.collaboration.fetchAllPermissions()+ fx.watchContentPermissionId = permissions!.find((p) => p.name === 'goal_can_watch_content')!.id++ for (const key of ['projectA', 'projectB'] as const) {+ const goal = await fx.ownerApi.goals.createGoal({ name: `roles-scope-${key}-${Date.now()}` })+ const hook = await fx.ownerApi.webhooks.create({+ goalId: goal!.id!,+ url: `https://receiver.test/${key}-${Date.now()}`,+ events: ['task.created'],+ })+ fx[key] = { goalId: goal!.id!, webhookId: hook!.webhook.id }+ }+})++afterAll(async () => {+ for (const id of tokenIds) {+ await fx.ownerApi.apiTokens.delete(id).catch(() => {})+ }+ for (const project of [fx.projectA, fx.projectB]) {+ if (project) await fx.ownerApi.goals.deleteGoal(project.goalId).catch(() => {})+ }+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+})++describe('toggling a role permission', () => {+ it('denies a token restricted to another project and leaves the role unchanged', async () => {+ const client = await tokenClient({ allowedPermissions: [], allowedGoalIds: [fx.projectA.goalId] })+ const roleId = await freshRole(fx.projectB.goalId)++ const status = await statusOf(client.collaboration.toggleRolePermission({ roleId, permissionId: fx.watchContentPermissionId }))++ expect(status).toBe(403)+ expect(await rolePermissionIds(fx.projectB.goalId, roleId)).toEqual([])+ })++ it('denies a read-only token in its own project and leaves the role unchanged', async () => {+ const client = await tokenClient({ allowedPermissions: ['goal_can_watch_content'], allowedGoalIds: [fx.projectA.goalId] })+ const roleId = await freshRole(fx.projectA.goalId)++ const status = await statusOf(client.collaboration.toggleRolePermission({ roleId, permissionId: fx.watchContentPermissionId }))++ expect(status).toBe(403)+ expect(await rolePermissionIds(fx.projectA.goalId, roleId)).toEqual([])+ })++ it('allows a token holding goal_can_manage_users on the project', async () => {+ const client = await tokenClient({ allowedPermissions: ['goal_can_manage_users'], allowedGoalIds: [fx.projectA.goalId] })+ const roleId = await freshRole(fx.projectA.goalId)++ const toggled = await client.collaboration.toggleRolePermission({ roleId, permissionId: fx.watchContentPermissionId })++ expect(toggled!.add).toBe(true)+ expect(await rolePermissionIds(fx.projectA.goalId, roleId)).toEqual([fx.watchContentPermissionId])+ })++ it('allows an unrestricted token in any owned project', async () => {+ const client = await tokenClient({ allowedPermissions: [], allowedGoalIds: [] })+ const roleId = await freshRole(fx.projectB.goalId)++ const toggled = await client.collaboration.toggleRolePermission({ roleId, permissionId: fx.watchContentPermissionId })++ expect(toggled!.add).toBe(true)+ })++ it('allows the owner session', async () => {+ const roleId = await freshRole(fx.projectB.goalId)++ const toggled = await fx.ownerApi.collaboration.toggleRolePermission({ roleId, permissionId: fx.watchContentPermissionId })++ expect(toggled!.add).toBe(true)+ })+})++describe('creating a role', () => {+ it('denies a token restricted to another project', async () => {+ const client = await tokenClient({ allowedPermissions: [], allowedGoalIds: [fx.projectA.goalId] })+ const roleName = `denied-${Date.now()}`++ const status = await statusOf(client.collaboration.createRoleForGoal({ goalId: fx.projectB.goalId, roleName }))++ expect(status).toBe(403)+ expect(await roleNames(fx.projectB.goalId)).not.toContain(roleName)+ })++ it('denies a read-only token in its own project', async () => {+ const client = await tokenClient({ allowedPermissions: ['goal_can_watch_content'], allowedGoalIds: [fx.projectA.goalId] })+ const roleName = `read-only-${Date.now()}`++ const status = await statusOf(client.collaboration.createRoleForGoal({ goalId: fx.projectA.goalId, roleName }))++ expect(status).toBe(403)+ expect(await roleNames(fx.projectA.goalId)).not.toContain(roleName)+ })++ it('allows a token holding goal_can_manage_users on the project', async () => {+ const client = await tokenClient({ allowedPermissions: ['goal_can_manage_users'], allowedGoalIds: [fx.projectA.goalId] })+ const roleName = `allowed-${Date.now()}`++ const role = await client.collaboration.createRoleForGoal({ goalId: fx.projectA.goalId, roleName })++ expect(role!.id).toBeGreaterThan(0)+ expect(await roleNames(fx.projectA.goalId)).toContain(roleName)+ })+})++describe('deleting a role', () => {+ it('denies a token restricted to another project and keeps the role', async () => {+ const client = await tokenClient({ allowedPermissions: [], allowedGoalIds: [fx.projectA.goalId] })+ const roleId = await freshRole(fx.projectB.goalId)++ const status = await statusOf(client.collaboration.deleteRoleFromGoal({ goalId: fx.projectB.goalId, id: roleId }))++ expect(status).toBe(403)+ expect(await roleIds(fx.projectB.goalId)).toContain(roleId)+ })++ it('denies a read-only token in its own project and keeps the role', async () => {+ const client = await tokenClient({ allowedPermissions: ['goal_can_watch_content'], allowedGoalIds: [fx.projectA.goalId] })+ const roleId = await freshRole(fx.projectA.goalId)++ const status = await statusOf(client.collaboration.deleteRoleFromGoal({ goalId: fx.projectA.goalId, id: roleId }))++ expect(status).toBe(403)+ expect(await roleIds(fx.projectA.goalId)).toContain(roleId)+ })++ it('allows a token holding goal_can_manage_users on the project', async () => {+ const client = await tokenClient({ allowedPermissions: ['goal_can_manage_users'], allowedGoalIds: [fx.projectA.goalId] })+ const roleId = await freshRole(fx.projectA.goalId)++ const deleted = await client.collaboration.deleteRoleFromGoal({ goalId: fx.projectA.goalId, id: roleId })++ expect(deleted).toBe(true)+ expect(await roleIds(fx.projectA.goalId)).not.toContain(roleId)+ })+})++describe('reading the role-to-permission matrix', () => {+ it('denies a token restricted to another project', async () => {+ const client = await tokenClient({ allowedPermissions: [], allowedGoalIds: [fx.projectA.goalId] })++ const status = await statusOf(client.collaboration.fetchRoleToPermissionsForGoal(fx.projectB.goalId))++ expect(status).toBe(403)+ })++ it('denies a read-only token in its own project', async () => {+ const client = await tokenClient({ allowedPermissions: ['goal_can_watch_content'], allowedGoalIds: [fx.projectA.goalId] })++ const status = await statusOf(client.collaboration.fetchRoleToPermissionsForGoal(fx.projectA.goalId))++ expect(status).toBe(403)+ })++ it('allows a token holding goal_can_manage_users on the project', async () => {+ const client = await tokenClient({ allowedPermissions: ['goal_can_manage_users'], allowedGoalIds: [fx.projectA.goalId] })++ const status = await statusOf(client.collaboration.fetchRoleToPermissionsForGoal(fx.projectA.goalId))++ expect(status).toBe(200)+ })+})++describe('webhooks with a token holding webhooks_can_view and webhooks_can_manage for project A only', () => {+ let client: TvApi++ beforeAll(async () => {+ client = await tokenClient({ allowedPermissions: ['webhooks_can_view', 'webhooks_can_manage'], allowedGoalIds: [fx.projectA.goalId] })+ })++ it('manages webhooks of project A', async () => {+ const fetchStatus = await statusOf(client.webhooks.fetch(fx.projectA.goalId))+ const created = await client.webhooks.create({+ goalId: fx.projectA.goalId,+ url: `https://receiver.test/a-${Date.now()}`,+ events: ['task.created'],+ })++ expect(fetchStatus).toBe(200)+ expect(await webhookIds(fx.projectA.goalId)).toContain(created!.webhook.id)+ })++ it('cannot list webhooks of project B', async () => {+ expect(await statusOf(client.webhooks.fetch(fx.projectB.goalId))).toBe(403)+ })++ it('cannot create a webhook in project B', async () => {+ const before = await webhookIds(fx.projectB.goalId)++ const status = await statusOf(client.webhooks.create({+ goalId: fx.projectB.goalId,+ url: `https://exfiltration.test/${Date.now()}`,+ events: ['task.created'],+ }))++ expect(status).toBe(403)+ expect(await webhookIds(fx.projectB.goalId)).toEqual(before)+ })++ it('cannot update, rotate, test or read deliveries of a project B webhook', async () => {+ const id = fx.projectB.webhookId++ const results = await Promise.all([+ statusOf(client.webhooks.update({ id, url: `https://exfiltration.test/${Date.now()}` })),+ statusOf(client.webhooks.rotateSecret(id)),+ statusOf(client.webhooks.testDelivery(id)),+ statusOf(client.webhooks.fetchDeliveries(id)),+ ])++ expect(results).toEqual([403, 403, 403, 403])+ const hook = (await fx.ownerApi.webhooks.fetch(fx.projectB.goalId))!.find((w) => w.id === id)+ expect(hook!.url).toMatch(/^https:\/\/receiver\.test\//)+ })++ it('cannot delete a project B webhook', async () => {+ const status = await statusOf(client.webhooks.delete({ id: fx.projectB.webhookId }))++ expect(status).toBe(403)+ expect(await webhookIds(fx.projectB.goalId)).toContain(fx.projectB.webhookId)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/collaboration-roles-token-scope.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/collaboration-roles-token-scope.test.types.tsnew file mode 100644index 0000000..84275ea--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/collaboration-roles-token-scope.test.types.ts@@ -0,0 +1,22 @@+import type { TvApi } from '@/tv'+import type { SessionUser } from './auth-test-helpers.types'++export type RolesScopeProject = {+ goalId: number+ webhookId: number+}++export type RolesScopeFixture = {+ owner: SessionUser+ ownerApi: TvApi+ /** the only project the project-scoped tokens are issued for */+ projectA: RolesScopeProject+ /** owned by the same user, outside every project-scoped token */+ projectB: RolesScopeProject+ watchContentPermissionId: number+}++export type RolesScopeTokenArgs = {+ allowedPermissions: string[]+ allowedGoalIds: number[]+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/default-roles.test.ts b/taskview-packages/taskview-api/src/api/__tests__/default-roles.test.tsnew file mode 100644index 0000000..f7a7b8e--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/default-roles.test.ts@@ -0,0 +1,50 @@+import type { TvApi } from '@/tv'+import { TvPermissions } from '@/api/permissions'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { initApi } from './init-api'++/**+ * Default roles a new project is created with. timetracking_can_manage_all does not+ * include logging own time, so the editor role carries timetracking_can_log itself.+ */+describe('Default roles of a new project', () => {+ let api: TvApi+ let goalId: number+ let permissionIdByName: Map<string, number>++ beforeAll(async () => {+ api = (await initApi()).$tvApi+ const goal = await api.goals.createGoal({ name: `default-roles-${Date.now()}` })+ goalId = goal!.id!+ const catalogue = await api.collaboration.fetchAllPermissions()+ permissionIdByName = new Map(catalogue!.map((p) => [p.name, p.id]))+ })++ afterAll(async () => {+ await api.goals.deleteGoal(goalId).catch(() => {})+ })++ async function rolePermissionNames(roleName: string): Promise<string[]> {+ const role = (await api.collaboration.fetchRolesForGoal(goalId))!.find((r) => r.name === roleName)+ const matrix = await api.collaboration.fetchRoleToPermissionsForGoal(goalId)+ const ids = matrix!.filter((r) => r.roleId === role!.id).map((r) => r.permissionId)+ return [...permissionIdByName].filter(([, id]) => ids.includes(id)).map(([name]) => name)+ }++ it('lets the editor view, log and manage time', async () => {+ const names = await rolePermissionNames('editor')++ expect(names).toEqual(expect.arrayContaining([+ TvPermissions.TIMETRACKING_CAN_VIEW,+ TvPermissions.TIMETRACKING_CAN_LOG,+ TvPermissions.TIMETRACKING_CAN_MANAGE_ALL,+ ]))+ })++ it('keeps the executor on view and log only', async () => {+ const names = await rolePermissionNames('executor')++ expect(names).toEqual(expect.arrayContaining([TvPermissions.TIMETRACKING_CAN_VIEW, TvPermissions.TIMETRACKING_CAN_LOG]))+ expect(names).not.toContain(TvPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml b/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.ymlindex c9a3b67..11025b1 100644--- a/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml+++ b/taskview-packages/taskview-api/src/api/__tests__/docker/docker-compose.yml@@ -36,6 +36,9 @@ services:# The test suite runs against a closed instance (see registration-flag.test.ts);# no other test creates accounts through public registration paths.ALLOW_PUBLIC_REGISTRATION: "false"+ # Self-service deletion is off by default; account-deletion.test.ts covers the+ # enabled flow, the API unit tests cover the default+ ALLOW_ACCOUNT_DELETION: "true"# IdP-facing URLs are built from this base (see sso-public-urls.test.ts)API_PUBLIC_URL: "https://api.public.example"# Domains that skip DNS/HTTP ownership proof — used by sso.test.ts todiff --git a/taskview-packages/taskview-api/src/api/__tests__/kanban-columns-order.test.ts b/taskview-packages/taskview-api/src/api/__tests__/kanban-columns-order.test.tsnew file mode 100644index 0000000..a072430--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/kanban-columns-order.test.ts@@ -0,0 +1,205 @@+import type { TvApi } from '@/tv'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { initApi } from './init-api'+import { openTestDb } from './test-db'+import { createSessionUser } from './auth-test-helpers'+import type { AuthTestContext } from './auth-test-helpers.types'+import { clientFor } from './start-test-helpers'+import type {+ KanbanOrderMember,+ KanbanOrderProject,+ KanbanOrderShareArgs,+ KanbanOrderTokenArgs,+} from './kanban-columns-order.test.types'++/**+ * Kanban columns are shown in their saved position (view_order), not in creation+ * order. A project starts with TODO, In Progress, Done; a new column goes last; the+ * whole order is saved at once by PATCH /module/kanban/reorder-statuses, which+ * needs kanban_can_manage and must list every column of the project exactly once.+ */+const ctx = {} as AuthTestContext+const goalIds: number[] = []+const tokenIds: number[] = []+let owner: KanbanOrderMember+let viewer: KanbanOrderMember+let manager: KanbanOrderMember+let permissionIdByName: Map<string, number>++const statusOf = async (call: Promise<unknown>) =>+ call.then(() => 200).catch((err) => err.status ?? err.response?.status)++async function freshMember(prefix: string): Promise<KanbanOrderMember> {+ const user = await createSessionUser({ ctx, prefix })+ return { user, api: clientFor(user.access) }+}++async function newProject(): Promise<KanbanOrderProject> {+ const goal = await owner.api.goals.createGoal({ name: `kanban-order-${Date.now()}-${Math.random()}` })+ goalIds.push(goal!.id!)+ const columns = await owner.api.kanban.fetchAllColumns(goal!.id!)+ return { goalId: goal!.id!, columnIds: columns!.map((c) => c.id) }+}++async function columnIds(goalId: number): Promise<number[]> {+ return (await owner.api.kanban.fetchAllColumns(goalId))!.map((c) => c.id)+}++async function share(args: KanbanOrderShareArgs): Promise<void> {+ const collab = await owner.api.collaboration.inviteUserToGoal({ goalId: args.goalId, email: args.member.user.email })+ const role = await owner.api.collaboration.createRoleForGoal({ goalId: args.goalId, roleName: `kanban-order-${Date.now()}` })+ for (const name of args.permissions) {+ await owner.api.collaboration.toggleRolePermission({ roleId: role!.id, permissionId: permissionIdByName.get(name)! })+ }+ await owner.api.collaboration.toggleUserRoles({ goalId: args.goalId, userId: collab!.id, roles: [role!.id] })+}++async function ownerToken(args: KanbanOrderTokenArgs): Promise<TvApi> {+ const created = await owner.api.apiTokens.create({+ name: `kanban-order-${Date.now()}-${Math.random()}`,+ allowedPermissions: args.allowedPermissions,+ allowedGoalIds: args.allowedGoalIds,+ })+ tokenIds.push(created!.item.id)+ return clientFor(created!.token)+}++beforeAll(async () => {+ const init = await initApi()+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Kanban order org ${Date.now()}` })+ ctx.orgId = org.id++ owner = await freshMember('kbown')+ viewer = await freshMember('kbview')+ manager = await freshMember('kbman')+ const catalogue = await owner.api.collaboration.fetchAllPermissions()+ permissionIdByName = new Map(catalogue!.map((p) => [p.name, p.id]))+})++afterAll(async () => {+ for (const id of tokenIds) await owner.api.apiTokens.delete(id).catch(() => {})+ for (const id of goalIds) await owner.api.goals.deleteGoal(id).catch(() => {})+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+})++describe('default columns', () => {+ it('a new project starts with TODO, In Progress, Done in that order', async () => {+ const p = await newProject()+ const columns = await owner.api.kanban.fetchAllColumns(p.goalId)++ expect(columns!.map((c) => c.name)).toEqual(['TODO', 'In Progress', 'Done'])+ expect(columns!.map((c) => c.viewOrder)).toEqual([1, 2, 3])+ })++ it('a column added later goes last', async () => {+ const p = await newProject()+ const added = await owner.api.kanban.addColumn({ goalId: p.goalId, name: 'Review' })++ expect(await columnIds(p.goalId)).toEqual([...p.columnIds, added!.id])+ })+})++describe('reordering', () => {+ it('saves the new order and answers with it', async () => {+ const p = await newProject()+ const [todo, inProgress, done] = p.columnIds++ const saved = await owner.api.kanban.reorderColumns({ goalId: p.goalId, statusIds: [done, todo, inProgress] })++ expect(saved.map((c) => c.id)).toEqual([done, todo, inProgress])+ expect(saved.map((c) => c.viewOrder)).toEqual([1, 2, 3])+ expect(await columnIds(p.goalId)).toEqual([done, todo, inProgress])+ })++ it('still puts a column added after a reorder last', async () => {+ const p = await newProject()+ const [todo, inProgress, done] = p.columnIds+ await owner.api.kanban.reorderColumns({ goalId: p.goalId, statusIds: [inProgress, done, todo] })++ const added = await owner.api.kanban.addColumn({ goalId: p.goalId, name: 'Archive' })++ expect(await columnIds(p.goalId)).toEqual([inProgress, done, todo, added!.id])+ })++ it('refuses an order that leaves a column out', async () => {+ const p = await newProject()+ const [todo, inProgress] = p.columnIds++ const status = await statusOf(owner.api.kanban.reorderColumns({ goalId: p.goalId, statusIds: [inProgress, todo] }))++ expect(status).toBe(400)+ expect(await columnIds(p.goalId)).toEqual(p.columnIds)+ })++ it('refuses an order that repeats a column', async () => {+ const p = await newProject()+ const [todo, inProgress] = p.columnIds++ const status = await statusOf(owner.api.kanban.reorderColumns({ goalId: p.goalId, statusIds: [todo, todo, inProgress] }))++ expect(status).toBe(400)+ expect(await columnIds(p.goalId)).toEqual(p.columnIds)+ })++ it('refuses a column of another project', async () => {+ const p = await newProject()+ const other = await newProject()+ const [todo, inProgress] = p.columnIds++ const status = await statusOf(owner.api.kanban.reorderColumns({+ goalId: p.goalId,+ statusIds: [todo, inProgress, other.columnIds[0]],+ }))++ expect(status).toBe(400)+ expect(await columnIds(p.goalId)).toEqual(p.columnIds)+ expect(await columnIds(other.goalId)).toEqual(other.columnIds)+ })+})++describe('who may reorder', () => {+ it('denies a member with kanban_can_view only', async () => {+ const p = await newProject()+ await share({ goalId: p.goalId, member: viewer, permissions: ['kanban_can_view'] })++ const status = await statusOf(viewer.api.kanban.reorderColumns({ goalId: p.goalId, statusIds: [...p.columnIds].reverse() }))++ expect(status).toBe(403)+ expect(await columnIds(p.goalId)).toEqual(p.columnIds)+ })++ it('allows a member with kanban_can_manage', async () => {+ const p = await newProject()+ await share({ goalId: p.goalId, member: manager, permissions: ['kanban_can_manage'] })+ const reversed = [...p.columnIds].reverse()++ const status = await statusOf(manager.api.kanban.reorderColumns({ goalId: p.goalId, statusIds: reversed }))++ expect(status).toBe(200)+ expect(await columnIds(p.goalId)).toEqual(reversed)+ })++ it('denies an owner token holding kanban_can_view only', async () => {+ const p = await newProject()+ const client = await ownerToken({ allowedPermissions: ['kanban_can_view'], allowedGoalIds: [p.goalId] })++ const status = await statusOf(client.kanban.reorderColumns({ goalId: p.goalId, statusIds: [...p.columnIds].reverse() }))++ expect(status).toBe(403)+ expect(await columnIds(p.goalId)).toEqual(p.columnIds)+ })++ it('denies an owner token restricted to another project', async () => {+ const p = await newProject()+ const other = await newProject()+ const client = await ownerToken({ allowedPermissions: [], allowedGoalIds: [other.goalId] })++ const status = await statusOf(client.kanban.reorderColumns({ goalId: p.goalId, statusIds: [...p.columnIds].reverse() }))++ expect(status).toBe(403)+ expect(await columnIds(p.goalId)).toEqual(p.columnIds)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/kanban-columns-order.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/kanban-columns-order.test.types.tsnew file mode 100644index 0000000..9e42fa6--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/kanban-columns-order.test.types.ts@@ -0,0 +1,24 @@+import type { TvApi } from '@/tv'+import type { SessionUser } from './auth-test-helpers.types'++export type KanbanOrderMember = {+ user: SessionUser+ api: TvApi+}++export type KanbanOrderProject = {+ goalId: number+ /** column ids in the order the project was created with */+ columnIds: number[]+}++export type KanbanOrderShareArgs = {+ goalId: number+ member: KanbanOrderMember+ permissions: string[]+}++export type KanbanOrderTokenArgs = {+ allowedPermissions: string[]+ allowedGoalIds: number[]+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/kanban.access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/kanban.access.test.tsindex 44e4847..f7f961e 100644--- a/taskview-packages/taskview-api/src/api/__tests__/kanban.access.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/kanban.access.test.ts@@ -2,7 +2,9 @@ import { TvApi } from '@/tv'import { TvPermissions } from '@/api/permissions'import axios, { type AxiosInstance } from 'axios'import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import type { Client } from 'pg'import { API_URL, DEFAULT_PASSWORD, DEFAULT_USER_2, initApi } from './init-api'+import { openTestDb } from './test-db'/*** Board writes (columns and task placement) are gated by kanban_can_manage, the@@ -16,6 +18,7 @@ describe('Kanban permission boundaries', () => {let outsiderEmail: stringlet deleteAllGoals: () => Promise<void>let attackerAxios: AxiosInstance+ let db: Clientconst permissionIdByName = new Map<string, number>()beforeAll(async () => {@@ -38,12 +41,21 @@ describe('Kanban permission boundaries', () => {for (const permission of await ownerApi.collaboration.fetchAllPermissions()) {permissionIdByName.set(permission.name, permission.id)}++ db = await openTestDb()})afterAll(async () => {await deleteAllGoals()+ await db.end()})+ async function readPlacement(taskId: number): Promise<{ status_id: number | null, kanban_order: number | null }> {+ const result = await db.query('select status_id, kanban_order from tasks.tasks where id = $1', [taskId])+ expect(result.rows).toHaveLength(1)+ return result.rows[0]+ }+async function expectHttpStatus<T>(promise: Promise<T>, status: number): Promise<void> {try {await promise@@ -217,4 +229,65 @@ describe('Kanban permission boundaries', () => {expect(updateResponse.status).toBe(403)})})++ describe('a task move stays inside the goal it was authorized for', () => {+ it('rejects moving a foreign task when a self-owned goalId is supplied', async () => {+ const victimGoal = await ownerApi.goals.createGoal({ name: `Victim move ${Date.now()}` })+ if (!victimGoal) throw new Error('Failed to create victim goal')+ const victimColumn = await addColumn(victimGoal.id, 'Victim column')+ const victimTask = await ownerApi.tasks.createTask({+ goalId: victimGoal.id,+ description: `victim-${Date.now()}`,+ statusId: victimColumn.id,+ })+ if (!victimTask) throw new Error('Failed to create victim task')+ const before = await readPlacement(victimTask.id)++ const ownGoal = await outsiderApi.goals.createGoal({ name: `Attacker move ${Date.now()}` })+ if (!ownGoal) throw new Error('Failed to create attacker goal')++ const response = await attackerAxios.patch('/module/kanban/update-tasks-order-and-column', {+ goalId: ownGoal.id,+ columnId: null,+ taskId: victimTask.id,+ prevTaskId: null,+ nextTaskId: null,+ })++ expect(response.status).toBe(404)+ expect(await readPlacement(victimTask.id)).toEqual(before)+ })++ it('ignores neighbour tasks from another goal when placing a task', async () => {+ const victimGoal = await ownerApi.goals.createGoal({ name: `Victim neighbour ${Date.now()}` })+ if (!victimGoal) throw new Error('Failed to create victim goal')+ const victimTask = await ownerApi.tasks.createTask({ goalId: victimGoal.id, description: `victim-${Date.now()}` })+ if (!victimTask) throw new Error('Failed to create victim task')+ const victimOrder = 777777+ await db.query('update tasks.tasks set kanban_order = $1 where id = $2', [victimOrder, victimTask.id])++ const ownGoal = await outsiderApi.goals.createGoal({ name: `Attacker neighbour ${Date.now()}` })+ if (!ownGoal) throw new Error('Failed to create attacker goal')+ const ownColumn = await outsiderApi.kanban.addColumn({ goalId: ownGoal.id, name: 'Own column' })+ if (!ownColumn) throw new Error('Failed to create attacker column')+ const ownTask = await outsiderApi.tasks.createTask({ goalId: ownGoal.id, description: `own-${Date.now()}` })+ if (!ownTask) throw new Error('Failed to create attacker task')++ const response = await attackerAxios.patch('/module/kanban/update-tasks-order-and-column', {+ goalId: ownGoal.id,+ columnId: ownColumn.id,+ taskId: ownTask.id,+ prevTaskId: victimTask.id,+ nextTaskId: null,+ })+ expect(response.status).toBe(200)++ // Placed after the foreign task, the order would have been derived from it (777777 + gap)+ const placement = await readPlacement(ownTask.id)+ expect(placement.status_id).toBe(ownColumn.id)+ expect(placement.kanban_order).not.toBeNull()+ expect(placement.kanban_order!).toBeLessThan(victimOrder)+ expect((await readPlacement(victimTask.id)).kanban_order).toBe(victimOrder)+ })+ })})diff --git a/taskview-packages/taskview-api/src/api/__tests__/login-case.test.ts b/taskview-packages/taskview-api/src/api/__tests__/login-case.test.tsnew file mode 100644index 0000000..514bb82--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/login-case.test.ts@@ -0,0 +1,115 @@+import axios from 'axios'+import type { Client } from 'pg'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { TvApi } from '@/tv'+import { API_URL, initApi } from './init-api'+import { openTestDb } from './test-db'+import type { LoginCaseUser } from './login-case.test.types'++// Login and email are stored lowercase and looked up lowercase, so the case a user types+// never matters — including for rows written before the rule, which may still be mixed case.+const PASSWORD = 'Case-pass-1!'++let ownerApi: TvApi+let db: Client+let orgId: number+let emailSeq = 0++beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ db = await openTestDb()++ // The stack runs as a closed instance: only invited emails get an account+ const org = await ownerApi.organizations.create({ name: `Login case org ${Date.now()}` })+ orgId = org.id+})++afterAll(async () => {+ await ownerApi.organizations.delete(orgId).catch(() => {})+ await db.end()+})++const noThrow = { validateStatus: () => true }++async function readUser(email: string): Promise<LoginCaseUser> {+ const result = await db.query<LoginCaseUser>(+ 'select id, login, email, remind_password_code from tv_auth.users where lower(email) = lower($1)',+ [email]+ )+ expect(result.rows).toHaveLength(1)+ return result.rows[0]+}++/** An account created by the emailed login code, which generates its own login, with a known password. */+async function codeCreatedUserWithPassword(): Promise<LoginCaseUser> {+ // tv_auth.users.email is varchar(50)+ const email = `lc-${Date.now()}-${emailSeq++}@logincase.example`+ await ownerApi.organizations.addMember({ organizationId: orgId, email, role: 'member' })+ expect((await axios.post(`${API_URL}/module/auth/send-login-code`, { email })).status).toBe(200)++ expect((await axios.post(`${API_URL}/module/auth/email/recovery`, { email })).status).toBe(200)+ const user = await readUser(email)+ const reset = await axios.post(`${API_URL}/module/auth/password/reset`, {+ login: user.login,+ code: user.remind_password_code,+ password: PASSWORD,+ passwordRepeat: PASSWORD,+ })+ expect(reset.status).toBe(200)+ return readUser(email)+}++async function loginWithPassword(login: string) {+ return axios.post(`${API_URL}/module/auth/login`, { login, password: PASSWORD }, noThrow)+}++describe('login and email are case-insensitive', () => {+ it('stores the generated login of a code-created account in lowercase', async () => {+ const user = await codeCreatedUserWithPassword()+ expect(user.login).toBe(user.login.toLowerCase())+ expect(user.email).toBe(user.email.toLowerCase())+ })++ it('signs in with the password by login, in any case', async () => {+ const user = await codeCreatedUserWithPassword()++ expect((await loginWithPassword(user.login)).status).toBe(200)+ expect((await loginWithPassword(user.login.toUpperCase())).status).toBe(200)+ })++ it('still finds a legacy mixed-case login and email', async () => {+ const user = await codeCreatedUserWithPassword()+ const legacyLogin = `Lc${user.id}MiX`+ const legacyEmail = `Lc-Legacy-${user.id}@LoginCase.Example`+ await db.query('update tv_auth.users set login = $1, email = $2 where id = $3', [legacyLogin, legacyEmail, user.id])++ expect((await loginWithPassword(legacyLogin)).status).toBe(200)+ expect((await loginWithPassword(legacyLogin.toLowerCase())).status).toBe(200)+ expect((await loginWithPassword(legacyEmail.toLowerCase())).status).toBe(200)+ })++ it('delivers a working login code to a legacy mixed-case email', async () => {+ const user = await codeCreatedUserWithPassword()+ const legacyEmail = `Lc-Code-${user.id}@LoginCase.Example`+ await db.query(+ 'update tv_auth.users set email = $1, remember_token = null where id = $2',+ [legacyEmail, user.id]+ )++ // The login form sends what the user types; the API lowercases it+ const sent = await axios.post(`${API_URL}/module/auth/send-login-code`, { email: legacyEmail }, noThrow)+ expect(sent.status).toBe(200)++ const row = await db.query<{ remember_token: string | null }>(+ 'select remember_token from tv_auth.users where id = $1',+ [user.id]+ )+ expect(row.rows[0].remember_token).toBeTruthy()+ const code = row.rows[0].remember_token!.split(':')[0]++ const res = await axios.post(`${API_URL}/module/auth/login-by-code`, { email: legacyEmail, code }, noThrow)+ expect(res.status).toBe(200)+ expect(res.data.access).toBeTruthy()+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/login-case.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/login-case.test.types.tsnew file mode 100644index 0000000..7728e63--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/login-case.test.types.ts@@ -0,0 +1,6 @@+export type LoginCaseUser = {+ id: number+ login: string+ email: string+ remind_password_code: string | null+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/login-code.test.ts b/taskview-packages/taskview-api/src/api/__tests__/login-code.test.tsnew file mode 100644index 0000000..3d600c4--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/login-code.test.ts@@ -0,0 +1,265 @@+import axios from 'axios'+import type { Client } from 'pg'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { TvApi } from '@/tv'+import { API_URL, initApi } from './init-api'+import { openTestDb } from './test-db'+import type { LoginCodeRow } from './login-code.test.types'++// The emailed login code is 6 digits, so its redemption must be capped per code:+// after LOGIN_CODE_MAX_ATTEMPTS wrong guesses the code is dead until a new one is requested.+const LOGIN_CODE_MAX_ATTEMPTS = 5+const RESEND_COOLDOWN_MS = 60 * 1000+// LOGIN_CODE_HOURLY_LIMIT is not set on the test stack, so the default applies+const LOGIN_CODE_HOURLY_LIMIT = 5++let ownerApi: TvApi+let db: Client+let orgId: number+let emailSeq = 0++beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ db = await openTestDb()++ // The stack runs as a closed instance: only invited emails get an account through the login code+ const org = await ownerApi.organizations.create({ name: `Login code org ${Date.now()}` })+ orgId = org.id+})++afterAll(async () => {+ await ownerApi.organizations.delete(orgId).catch(() => {})+ await db.end()+})++/** A fresh account that has just been sent a login code. */+async function userWithPendingCode(): Promise<string> {+ const email = `login-code-${Date.now()}-${emailSeq++}@login-code.example`+ await ownerApi.organizations.addMember({ organizationId: orgId, email, role: 'member' })+ const res = await axios.post(`${API_URL}/module/auth/send-login-code`, { email })+ expect(res.status).toBe(200)+ return email+}++async function readCodeRow(email: string): Promise<LoginCodeRow> {+ const result = await db.query<LoginCodeRow>(+ 'select remember_token, login_code_attempts from tv_auth.users where email = $1',+ [email]+ )+ expect(result.rows).toHaveLength(1)+ return result.rows[0]+}++async function readCode(email: string): Promise<string> {+ const row = await readCodeRow(email)+ expect(row.remember_token).toBeTruthy()+ return row.remember_token!.split(':')[0]+}++function wrongCodeFor(code: string): string {+ return code === '999999' ? '100000' : '999999'+}++async function requestCode(email: string) {+ return axios.post(`${API_URL}/module/auth/send-login-code`, { email }, { validateStatus: () => true })+}++async function countCodeRequests(email: string): Promise<number> {+ const result = await db.query<{ total: number }>(+ `select count(*)::int as total from tv_auth.login_code_requests r+ join tv_auth.users u on u.id = r.user_id where u.email = $1`,+ [email]+ )+ return result.rows[0].total+}++async function loginByCode(email: string, code: string) {+ return axios.post(`${API_URL}/module/auth/login-by-code`, { email, code }, { validateStatus: () => true })+}++/** Moves the issue time of the pending code into the past, as if `ageMs` had passed. */+async function ageCode(email: string, ageMs: number): Promise<void> {+ const row = await readCodeRow(email)+ const [code] = row.remember_token!.split(':')+ await db.query('update tv_auth.users set remember_token = $1 where email = $2', [`${code}:${Date.now() - ageMs}`, email])+}++describe('login by emailed code', () => {+ it('logs in with the right code and the code cannot be used twice', async () => {+ const email = await userWithPendingCode()+ const code = await readCode(email)++ const first = await loginByCode(email, code)+ expect(first.status).toBe(200)+ expect(first.data.access).toBeTruthy()+ expect(first.data.refresh).toBeTruthy()++ const replay = await loginByCode(email, code)+ expect(replay.status).toBe(400)+ })++ it('still accepts the right code after fewer wrong guesses than the limit', async () => {+ const email = await userWithPendingCode()+ const code = await readCode(email)++ for (let i = 0; i < LOGIN_CODE_MAX_ATTEMPTS - 1; i++) {+ const res = await loginByCode(email, wrongCodeFor(code))+ expect(res.status).toBe(400)+ expect(res.data.message).toBe('Invalid code')+ }++ const res = await loginByCode(email, code)+ expect(res.status).toBe(200)+ expect(res.data.access).toBeTruthy()+ })++ it('refuses the right code once the wrong guesses reached the limit', async () => {+ const email = await userWithPendingCode()+ const code = await readCode(email)++ for (let i = 0; i < LOGIN_CODE_MAX_ATTEMPTS; i++) {+ const res = await loginByCode(email, wrongCodeFor(code))+ expect(res.status).toBe(400)+ }++ const res = await loginByCode(email, code)+ expect(res.status).toBe(429)+ expect(res.data.access).toBeUndefined()++ const row = await readCodeRow(email)+ expect(row.login_code_attempts).toBe(LOGIN_CODE_MAX_ATTEMPTS + 1)+ })++ it('counts concurrent guesses one by one, so a burst cannot slip past the limit', async () => {+ const email = await userWithPendingCode()+ const code = await readCode(email)+ const burst = 30++ const responses = await Promise.all(+ Array.from({ length: burst }, () => loginByCode(email, wrongCodeFor(code)))+ )+ const statuses = responses.map(r => r.status)+ expect(statuses.filter(s => s === 400)).toHaveLength(LOGIN_CODE_MAX_ATTEMPTS)+ expect(statuses.filter(s => s === 429)).toHaveLength(burst - LOGIN_CODE_MAX_ATTEMPTS)++ const row = await readCodeRow(email)+ expect(row.login_code_attempts).toBe(burst)++ const res = await loginByCode(email, code)+ expect(res.status).toBe(429)+ })++ it('keeps the resend cooldown after the limit, then a new code gets a fresh attempt budget', async () => {+ const email = await userWithPendingCode()+ const oldCode = await readCode(email)++ for (let i = 0; i < LOGIN_CODE_MAX_ATTEMPTS; i++) {+ await loginByCode(email, wrongCodeFor(oldCode))+ }++ const tooSoon = await axios.post(`${API_URL}/module/auth/send-login-code`, { email }, { validateStatus: () => true })+ expect(tooSoon.status).toBe(429)++ await ageCode(email, RESEND_COOLDOWN_MS + 1000)++ const resent = await axios.post(`${API_URL}/module/auth/send-login-code`, { email })+ expect(resent.status).toBe(200)++ const row = await readCodeRow(email)+ expect(row.login_code_attempts).toBe(0)++ const newCode = await readCode(email)+ const res = await loginByCode(email, newCode)+ expect(res.status).toBe(200)+ expect(res.data.access).toBeTruthy()+ })++ it('refuses an expired code even when it is right', async () => {+ const email = await userWithPendingCode()+ const code = await readCode(email)+ await ageCode(email, 5 * 60 * 1000 + 1000)++ const res = await loginByCode(email, code)+ expect(res.status).toBe(400)+ expect(res.data.access).toBeUndefined()+ })++ it('answers an unknown email and a missing code exactly like a wrong code', async () => {+ const email = await userWithPendingCode()+ const code = await readCode(email)++ const wrong = await loginByCode(email, wrongCodeFor(code))+ const unknown = await loginByCode(`nobody-${Date.now()}@login-code.example`, '123456')++ const used = await userWithPendingCode()+ expect((await loginByCode(used, await readCode(used))).status).toBe(200)+ const noPending = await loginByCode(used, '123456')++ for (const res of [unknown, noPending]) {+ expect(res.status).toBe(wrong.status)+ expect(res.data).toEqual(wrong.data)+ }+ })++ describe('hourly limit on requested codes', () => {+ it('refuses a code beyond the hourly limit and says when to retry', async () => {+ const email = await userWithPendingCode()++ for (let i = 1; i < LOGIN_CODE_HOURLY_LIMIT; i++) {+ await ageCode(email, RESEND_COOLDOWN_MS + 1000)+ const res = await requestCode(email)+ expect(res.status).toBe(200)+ }+ expect(await countCodeRequests(email)).toBe(LOGIN_CODE_HOURLY_LIMIT)++ await ageCode(email, RESEND_COOLDOWN_MS + 1000)+ const lastCode = await readCode(email)+ const refused = await requestCode(email)+ expect(refused.status).toBe(429)+ expect(refused.data.retryAfter).toBeGreaterThan(RESEND_COOLDOWN_MS / 1000)+ expect(refused.data.retryAfter).toBeLessThanOrEqual(3600)+ expect(await countCodeRequests(email)).toBe(LOGIN_CODE_HOURLY_LIMIT)++ // A refused request leaves the last issued code in place+ expect(await readCode(email)).toBe(lastCode)+ })++ it('allows a new code again once the oldest one leaves the hour window', async () => {+ const email = await userWithPendingCode()++ for (let i = 1; i < LOGIN_CODE_HOURLY_LIMIT; i++) {+ await ageCode(email, RESEND_COOLDOWN_MS + 1000)+ expect((await requestCode(email)).status).toBe(200)+ }+ await ageCode(email, RESEND_COOLDOWN_MS + 1000)+ expect((await requestCode(email)).status).toBe(429)++ await db.query(+ `update tv_auth.login_code_requests set requested_at = requested_at - interval '61 minutes'+ where id = (select r.id from tv_auth.login_code_requests r+ join tv_auth.users u on u.id = r.user_id+ where u.email = $1 order by r.requested_at limit 1)`,+ [email]+ )++ const res = await requestCode(email)+ expect(res.status).toBe(200)+ const code = await readCode(email)+ expect((await loginByCode(email, code)).status).toBe(200)+ })++ it('does not let concurrent requests go past the limit', async () => {+ const email = await userWithPendingCode()+ await ageCode(email, RESEND_COOLDOWN_MS + 1000)++ const burst = 10+ const responses = await Promise.all(Array.from({ length: burst }, () => requestCode(email)))+ const statuses = responses.map(r => r.status)++ expect(statuses.filter(s => s === 200)).toHaveLength(LOGIN_CODE_HOURLY_LIMIT - 1)+ expect(statuses.filter(s => s === 429)).toHaveLength(burst - (LOGIN_CODE_HOURLY_LIMIT - 1))+ expect(await countCodeRequests(email)).toBe(LOGIN_CODE_HOURLY_LIMIT)+ })+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/login-code.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/login-code.test.types.tsnew file mode 100644index 0000000..d0e9f99--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/login-code.test.types.ts@@ -0,0 +1,4 @@+export type LoginCodeRow = {+ remember_token: string | null+ login_code_attempts: number+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/password-change.test.ts b/taskview-packages/taskview-api/src/api/__tests__/password-change.test.tsnew file mode 100644index 0000000..162b58c--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/password-change.test.ts@@ -0,0 +1,148 @@+import axios from 'axios'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, initApi } from './init-api'+import { openTestDb } from './test-db'+import { authHeaders, bearerStatus, createSessionUser, setPassword, signInWithPassword } from './auth-test-helpers'+import type { AuthTestContext, SessionUser } from './auth-test-helpers.types'++// PASSWORD_CHANGE_CONFIRMATION is not set on the test stack, so the change is confirmed by an emailed code+const PASSWORD = 'Change-pass-1!'+const NEW_PASSWORD = 'Changed-pass-2!'+const CODE_TTL_S = 15 * 60++const ctx = {} as AuthTestContext++beforeAll(async () => {+ const init = await initApi()+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Password change org ${Date.now()}` })+ ctx.orgId = org.id+})++afterAll(async () => {+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+})++/** A user with a known password, signed in twice, who has just requested a password-change code. */+async function userAwaitingChange(): Promise<{ user: SessionUser, other: string, code: string }> {+ const created = await createSessionUser({ ctx, prefix: 'chg' })+ await setPassword({ ctx, user: created, password: PASSWORD })+ const current = await signInWithPassword(created.email, PASSWORD)+ const other = await signInWithPassword(created.email, PASSWORD)+ const user = { ...created, access: current.data.access, refresh: current.data.refresh }++ const sent = await axios.post(`${API_URL}/module/auth/password/change/code`, {}, authHeaders(user.access))+ expect(sent.status).toBe(200)+ const row = await ctx.db.query<{ remind_password_code: string }>(+ 'select remind_password_code from tv_auth.users where id = $1',+ [user.id]+ )+ return { user, other: other.data.access, code: row.rows[0].remind_password_code }+}++async function changePassword(access: string, code: string) {+ return axios.post(+ `${API_URL}/module/auth/password/change`,+ { code, password: NEW_PASSWORD, passwordRepeat: NEW_PASSWORD },+ authHeaders(access)+ )+}++async function passwordHash(userId: number): Promise<string> {+ const row = await ctx.db.query<{ password: string }>('select password from tv_auth.users where id = $1', [userId])+ return row.rows[0].password+}++describe('changing the password while signed in', () => {+ it('reports the confirmation mode', async () => {+ const user = await createSessionUser({ ctx, prefix: 'chg' })++ const res = await axios.get(`${API_URL}/module/auth/password/change/mode`, authHeaders(user.access))++ expect(res.status).toBe(200)+ expect(res.data).toEqual({ mode: 'email' })+ })++ it('changes the password with the emailed code, ending the other sessions only', async () => {+ const { user, other, code } = await userAwaitingChange()++ const res = await changePassword(user.access, code)++ expect(res.status).toBe(200)+ expect(await bearerStatus(other)).toBe(401)+ expect(await bearerStatus(user.access)).toBe(200)+ expect((await signInWithPassword(user.email, NEW_PASSWORD)).status).toBe(200)+ expect((await signInWithPassword(user.email, PASSWORD)).status).toBe(400)+ })++ it('refuses a wrong code', async () => {+ const { user, other } = await userAwaitingChange()+ const before = await passwordHash(user.id)++ const res = await changePassword(user.access, 'wrong-code-0')++ expect(res.status).toBe(400)+ expect(await passwordHash(user.id)).toBe(before)+ expect(await bearerStatus(other)).toBe(200)+ })++ it('refuses a code older than 15 minutes', async () => {+ const { user, code } = await userAwaitingChange()+ const before = await passwordHash(user.id)+ await ctx.db.query(+ 'update tv_auth.users set remind_password_time = remind_password_time - $1 where id = $2',+ [CODE_TTL_S + 60, user.id]+ )++ const res = await changePassword(user.access, code)++ expect(res.status).toBe(400)+ expect(await passwordHash(user.id)).toBe(before)+ })++ it('accepts a code once', async () => {+ const { user, code } = await userAwaitingChange()++ expect((await changePassword(user.access, code)).status).toBe(200)+ expect((await changePassword(user.access, code)).status).toBe(400)+ })++ it('makes the user wait a minute before another code', async () => {+ const { user } = await userAwaitingChange()++ const res = await axios.post(`${API_URL}/module/auth/password/change/code`, {}, authHeaders(user.access))++ expect(res.status).toBe(429)+ expect(res.data.retryAfter).toBeGreaterThan(0)+ })++ it("does not accept another user's code", async () => {+ const victim = await userAwaitingChange()+ const attacker = await userAwaitingChange()+ const before = await passwordHash(attacker.user.id)++ const res = await changePassword(attacker.user.access, victim.code)++ expect(res.status).toBe(400)+ expect(await passwordHash(attacker.user.id)).toBe(before)+ })+})++describe('changing the default credentials', () => {+ it('is refused to any account but the seeded default one', async () => {+ const created = await createSessionUser({ ctx, prefix: 'chg' })+ await setPassword({ ctx, user: created, password: PASSWORD })+ const signIn = await signInWithPassword(created.email, PASSWORD)++ const res = await axios.post(+ `${API_URL}/module/auth/credentials/change`,+ { currentPassword: PASSWORD, login: `taken${Date.now()}`, email: `taken${Date.now()}@auth.example`, password: NEW_PASSWORD, passwordRepeat: NEW_PASSWORD },+ authHeaders(signIn.data.access)+ )++ expect(res.status).toBe(403)+ expect((await signInWithPassword(created.email, PASSWORD)).status).toBe(200)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/password-reset.test.ts b/taskview-packages/taskview-api/src/api/__tests__/password-reset.test.tsnew file mode 100644index 0000000..77948b5--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/password-reset.test.ts@@ -0,0 +1,181 @@+import axios from 'axios'+import type { Client } from 'pg'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { TvApi } from '@/tv'+import { API_URL, initApi } from './init-api'+import { openTestDb } from './test-db'+import type { ResetCodeRow, UserWithSession } from './password-reset.test.types'++// A password reset is the account-recovery step: it must end every existing session,+// and the emailed reset code must expire like the password-change code does.+const RESET_CODE_TTL_S = 15 * 60+const NEW_PASSWORD = 'Reset-pass-1!'+const INVALID_CODE = { reason: 'invalid_or_expired_code' }++let ownerApi: TvApi+let db: Client+let orgId: number+let emailSeq = 0++beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ db = await openTestDb()++ // The stack runs as a closed instance: only invited emails get an account+ const org = await ownerApi.organizations.create({ name: `Password reset org ${Date.now()}` })+ orgId = org.id+})++afterAll(async () => {+ await ownerApi.organizations.delete(orgId).catch(() => {})+ await db.end()+})++const noThrow = { validateStatus: () => true }++/** A fresh account with one logged-in session, as an attacker holding a stolen token would have. */+async function userWithSession(): Promise<UserWithSession> {+ // tv_auth.users.email is varchar(50)+ const email = `pwr-${Date.now()}-${emailSeq++}@pwreset.example`+ await ownerApi.organizations.addMember({ organizationId: orgId, email, role: 'member' })+ expect((await axios.post(`${API_URL}/module/auth/send-login-code`, { email })).status).toBe(200)++ const user = await db.query<{ login: string, remember_token: string }>(+ 'select login, remember_token from tv_auth.users where email = $1',+ [email]+ )+ const code = user.rows[0].remember_token.split(':')[0]+ const session = await axios.post(`${API_URL}/module/auth/login-by-code`, { email, code })+ expect(session.status).toBe(200)++ return { email, login: user.rows[0].login, access: session.data.access, refresh: session.data.refresh }+}++async function readResetCode(email: string): Promise<ResetCodeRow> {+ const result = await db.query<ResetCodeRow>(+ 'select remind_password_code, remind_password_time, password from tv_auth.users where email = $1',+ [email]+ )+ expect(result.rows).toHaveLength(1)+ return result.rows[0]+}++async function requestReset(email: string): Promise<string> {+ expect((await axios.post(`${API_URL}/module/auth/email/recovery`, { email })).status).toBe(200)+ const row = await readResetCode(email)+ expect(row.remind_password_code).toBeTruthy()+ return row.remind_password_code!+}++async function resetPassword(login: string, code: string, password = NEW_PASSWORD) {+ return axios.post(+ `${API_URL}/module/auth/password/reset`,+ { login, code, password, passwordRepeat: password },+ noThrow+ )+}++async function isAccessTokenValid(access: string): Promise<number> {+ const res = await axios.get(`${API_URL}/module/auth/password/change/mode`, {+ headers: { Authorization: `Bearer ${access}` },+ ...noThrow,+ })+ return res.status+}++async function refresh(refreshToken: string): Promise<number> {+ const res = await axios.post(`${API_URL}/module/auth/refresh/token`, { refreshToken }, noThrow)+ return res.status+}++describe('password reset by emailed code', () => {+ it('ends every existing session, and the new password works', async () => {+ const user = await userWithSession()+ expect(await isAccessTokenValid(user.access)).toBe(200)+ expect(await refresh(user.refresh)).toBe(200)++ const code = await requestReset(user.email)+ const res = await resetPassword(user.login, code)+ expect(res.status).toBe(200)++ expect(await isAccessTokenValid(user.access)).toBe(401)+ expect(await refresh(user.refresh)).toBe(401)++ const login = await axios.post(`${API_URL}/module/auth/login`, { login: user.email, password: NEW_PASSWORD }, noThrow)+ expect(login.status).toBe(200)+ expect(login.data.access).toBeTruthy()+ })++ it('refuses a code older than the reset window', async () => {+ const user = await userWithSession()+ const code = await requestReset(user.email)+ const before = await readResetCode(user.email)+ await db.query(+ 'update tv_auth.users set remind_password_time = remind_password_time - $1 where email = $2',+ [RESET_CODE_TTL_S + 60, user.email]+ )++ const res = await resetPassword(user.login, code)++ expect(res.status).toBe(400)+ expect(res.data).toEqual(INVALID_CODE)+ expect((await readResetCode(user.email)).password).toBe(before.password)+ expect(await isAccessTokenValid(user.access)).toBe(200)+ })++ it('accepts a code once', async () => {+ const user = await userWithSession()+ const code = await requestReset(user.email)++ expect((await resetPassword(user.login, code)).status).toBe(200)+ const after = await readResetCode(user.email)++ const replay = await resetPassword(user.login, code, 'Another-pass-2!')+ expect(replay.status).toBe(400)+ expect(replay.data).toEqual(INVALID_CODE)+ expect((await readResetCode(user.email)).password).toBe(after.password)+ })++ it('lets only one of two concurrent requests with the same code through', async () => {+ const user = await userWithSession()+ const code = await requestReset(user.email)++ const responses = await Promise.all([+ resetPassword(user.login, code, 'Concurrent-pass-1!'),+ resetPassword(user.login, code, 'Concurrent-pass-2!'),+ ])++ expect(responses.map(r => r.status).sort()).toEqual([200, 400])+ })++ it('refuses a wrong code', async () => {+ const user = await userWithSession()+ await requestReset(user.email)+ const before = await readResetCode(user.email)++ const res = await resetPassword(user.login, 'wrong-code-000000')++ expect(res.status).toBe(400)+ expect(res.data).toEqual(INVALID_CODE)+ expect((await readResetCode(user.email)).password).toBe(before.password)+ })++ it('refuses a password shorter than the other password flows allow, keeping the code usable', async () => {+ const user = await userWithSession()+ const code = await requestReset(user.email)++ const short = await resetPassword(user.login, code, '12345')+ expect(short.status).toBe(400)+ expect(short.data).not.toEqual(INVALID_CODE)++ expect((await resetPassword(user.login, code)).status).toBe(200)+ })++ it('answers an unknown login like a wrong code', async () => {+ const res = await resetPassword(`nobody${Date.now()}`, 'any-code-000000')++ expect(res.status).toBe(400)+ expect(res.data).toEqual(INVALID_CODE)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/password-reset.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/password-reset.test.types.tsnew file mode 100644index 0000000..c950803--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/password-reset.test.types.ts@@ -0,0 +1,12 @@+export type UserWithSession = {+ email: string+ login: string+ access: string+ refresh: string+}++export type ResetCodeRow = {+ remind_password_code: string | null+ remind_password_time: number | null+ password: string+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/start-shared-projects.test.ts b/taskview-packages/taskview-api/src/api/__tests__/start-shared-projects.test.tsnew file mode 100644index 0000000..7d4d8a8--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/start-shared-projects.test.ts@@ -0,0 +1,293 @@+import type { TvApi } from '@/tv'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { initApi } from './init-api'+import { ymd } from './test-helpers'+import { openTestDb } from './test-db'+import { createSessionUser } from './auth-test-helpers'+import type { AuthTestContext, SessionUser } from './auth-test-helpers.types'+import {+ clientFor,+ fetchCollaborators,+ fetchLists,+ fetchState,+ fetchTags,+ rawGet,+ searchTasks,+ stateTaskIds,+} from './start-test-helpers'+import type { ScopedToken, ScopedTokenArgs } from './start-token-scope.test.types'+import type { CreateSharedProjectArgs, SharedProjectFixture } from './start-shared-projects.test.types'++/**+ * The positive side of the Start screen scoping: projects shared with a collaborator+ * must show up on the main screen, in search, lists, tags and the collaborator list,+ * and every field must follow the collaborator's role in that project — the same+ * rules the ordinary task routes apply. Tokens the collaborator issues narrow that+ * further, never widen it.+ *+ * Owner and collaborator are fresh accounts, so the LIMIT 30 of the start queries+ * only ever sees this spec's tasks.+ */+const ctx = {} as AuthTestContext+const tokenIds: number[] = []+const marker = `TVSHARED${Date.now()}`+let owner: SessionUser+let ownerApi: TvApi+let collaborator: SessionUser+let collaboratorApi: TvApi+let full: SharedProjectFixture+let contentOnly: SharedProjectFixture+let listOnly: SharedProjectFixture++async function createSharedProject(args: CreateSharedProjectArgs): Promise<SharedProjectFixture> {+ const goal = await ownerApi.goals.createGoal({ name: `${marker}_${args.name}` })+ const goalId = goal!.id!+ const list = await ownerApi.goalLists.createList({ goalId, name: `${marker}_${args.name}_LIST` })+ const tag = await ownerApi.tags.createTag({ goalId, name: `${marker}_${args.name}_TAG`, color: '#00aa00' })+ const collab = await ownerApi.collaboration.inviteUserToGoal({ goalId, email: collaborator.email })++ let roleId: number+ if (args.role === 'editor') {+ const roles = await ownerApi.collaboration.fetchRolesForGoal(goalId)+ roleId = roles!.find((r) => r.name === 'editor')!.id+ } else {+ const role = await ownerApi.collaboration.createRoleForGoal({ goalId, roleName: `${marker}_${args.name}_ROLE` })+ roleId = role!.id+ const permissions = await ownerApi.collaboration.fetchAllPermissions()+ for (const name of args.role) {+ const permission = permissions!.find((p) => p.name === name)+ const toggled = await ownerApi.collaboration.toggleRolePermission({ roleId, permissionId: permission!.id })+ expect(toggled!.add).toBe(true)+ }+ }+ await ownerApi.collaboration.toggleUserRoles({ goalId, userId: collab!.id, roles: [roleId] })++ const note = `${marker}_${args.name}_NOTE`+ const active = await ownerApi.tasks.createTask({ goalId, description: `${marker}_${args.name}_ACTIVE`, note })+ await ownerApi.tags.toggleTag({ tagId: tag!.id, taskId: active!.id })+ await ownerApi.tasks.toggleTasksAssignee({ taskId: active!.id, userIds: [collab!.id] })+ const today = await ownerApi.tasks.createTask({ goalId, description: `${marker}_${args.name}_TODAY` })+ await ownerApi.tasks.updateTask({ id: today!.id, endDate: ymd(0) })+ const upcoming = await ownerApi.tasks.createTask({ goalId, description: `${marker}_${args.name}_UPCOMING` })+ await ownerApi.tasks.updateTask({ id: upcoming!.id, endDate: ymd(7) })+ const completed = await ownerApi.tasks.createTask({ goalId, description: `${marker}_${args.name}_DONE` })+ await ownerApi.tasks.updateTask({ id: completed!.id, complete: true })++ return {+ goalId,+ listId: list!.id,+ tagId: tag!.id,+ activeTaskId: active!.id,+ todayTaskId: today!.id,+ upcomingTaskId: upcoming!.id,+ completedTaskId: completed!.id,+ collaboratorId: collab!.id,+ note,+ }+}++async function issueCollaboratorToken(args: ScopedTokenArgs): Promise<ScopedToken> {+ const created = await collaboratorApi.apiTokens.create({+ name: `start-shared-${Date.now()}-${Math.random()}`,+ allowedPermissions: args.allowedPermissions,+ allowedGoalIds: args.allowedGoalIds,+ })+ tokenIds.push(created!.item.id)+ return { token: created!.token, api: clientFor(created!.token) }+}++function bucketIds(project: SharedProjectFixture): number[] {+ return [project.activeTaskId, project.todayTaskId, project.upcomingTaskId, project.completedTaskId]+}++beforeAll(async () => {+ const init = await initApi()+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Start shared org ${Date.now()}` })+ ctx.orgId = org.id++ owner = await createSessionUser({ ctx, prefix: 'shown' })+ ownerApi = clientFor(owner.access)+ collaborator = await createSessionUser({ ctx, prefix: 'shcol' })+ collaboratorApi = clientFor(collaborator.access)++ full = await createSharedProject({ name: 'FULL', role: 'editor' })+ contentOnly = await createSharedProject({+ name: 'CONTENT',+ role: ['goal_can_watch_content', 'component_can_watch_content'],+ })+ listOnly = await createSharedProject({ name: 'LISTS', role: ['goal_can_watch_content'] })+})++afterAll(async () => {+ for (const id of tokenIds) {+ await collaboratorApi.apiTokens.delete(id).catch(() => {})+ }+ for (const project of [full, contentOnly, listOnly]) {+ if (project) await ownerApi.goals.deleteGoal(project.goalId).catch(() => {})+ }+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+})++describe('collaborator with the editor role', () => {+ it('sees each task in its bucket', async () => {+ const state = await fetchState(collaborator.access)++ expect(state.tasks.map((t) => t.id)).toContain(full.activeTaskId)+ expect(state.tasksToday.map((t) => t.id)).toContain(full.todayTaskId)+ expect(state.tasksUpcoming.map((t) => t.id)).toContain(full.upcomingTaskId)+ expect(state.tasksLastCompleted.map((t) => t.id)).toContain(full.completedTaskId)+ })++ it('sees the note', async () => {+ const task = (await fetchState(collaborator.access)).tasks.find((t) => t.id === full.activeTaskId)++ expect(task!.note).toBe(full.note)+ })++ it('sees the assignee of the task', async () => {+ const state = await fetchState(collaborator.access)++ expect(state.assignees).toContainEqual(expect.objectContaining({+ taskId: full.activeTaskId,+ collabUserId: full.collaboratorId,+ }))+ expect(state.tasks.find((t) => t.id === full.activeTaskId)!.assignedUsers).toEqual([full.collaboratorId])+ })++ it('sees the tags of the task', async () => {+ const task = (await fetchState(collaborator.access)).tasks.find((t) => t.id === full.activeTaskId)++ expect(task!.tags).toEqual([full.tagId])+ })++ it('sees the project members', async () => {+ const state = await fetchState(collaborator.access)++ expect(state.users.find((g) => g.id === full.goalId)?.users.map((u) => u.email)).toContain(collaborator.email)+ })++ it('finds the task with its note in search', async () => {+ const found = (await searchTasks(collaborator.access, marker)).find((t) => t.id === full.activeTaskId)++ expect(found!.note).toBe(full.note)+ })++ it('sees the lists, tags and collaborators of the project', async () => {+ const lists = (await fetchLists(collaborator.access)).map((l) => l.listId)+ const tags = (await fetchTags(collaborator.access)).map((t) => t.id)+ const collaboratorGoals = (await fetchCollaborators(collaborator.access)).map((c) => c.goalId)++ expect(lists).toContain(full.listId)+ expect(tags).toContain(full.tagId)+ expect(collaboratorGoals).toContain(full.goalId)+ })+})++describe('collaborator whose role grants content but not notes, assignees or tags', () => {+ it('sees each task in its bucket', async () => {+ const ids = stateTaskIds(await fetchState(collaborator.access))++ for (const id of bucketIds(contentOnly)) expect(ids).toContain(id)+ })++ it('gets the task serialized like the task route does', async () => {+ const direct = await collaboratorApi.tasks.fetchTaskById(contentOnly.activeTaskId)+ const fromStart = (await fetchState(collaborator.access)).tasks.find((t) => t.id === contentOnly.activeTaskId)++ expect(direct!.note).toBeNull()+ expect(fromStart!.note).toBeNull()+ expect(fromStart!.description).toBe(direct!.description)+ expect(fromStart!.priorityId).toBe(direct!.priorityId)+ })++ it('gets no note in search', async () => {+ const found = (await searchTasks(collaborator.access, marker)).find((t) => t.id === contentOnly.activeTaskId)++ expect(found).toBeDefined()+ expect(found!.note).toBeNull()+ })++ it('sees no assignees, members, task tags or collaborators of the project', async () => {+ const state = await fetchState(collaborator.access)+ const task = state.tasks.find((t) => t.id === contentOnly.activeTaskId)+ const collaboratorGoals = (await fetchCollaborators(collaborator.access)).map((c) => c.goalId)++ expect(state.assignees.some((a) => a.taskId === contentOnly.activeTaskId)).toBe(false)+ expect(task!.assignedUsers).toEqual([])+ expect(task!.tags).toEqual([])+ expect(state.users.map((g) => g.id)).not.toContain(contentOnly.goalId)+ expect(collaboratorGoals).not.toContain(contentOnly.goalId)+ })++ it('sees the lists but not the tags of the project', async () => {+ const lists = (await fetchLists(collaborator.access)).map((l) => l.listId)+ const tags = (await fetchTags(collaborator.access)).map((t) => t.id)++ expect(lists).toContain(contentOnly.listId)+ expect(tags).not.toContain(contentOnly.tagId)+ })+})++describe('collaborator whose role grants only goal_can_watch_content', () => {+ it('sees the lists of the project', async () => {+ const lists = (await fetchLists(collaborator.access)).map((l) => l.listId)++ expect(lists).toContain(listOnly.listId)+ })++ it('is denied the task by the task route', async () => {+ const direct = await rawGet({ token: collaborator.access, path: `/module/tasks/${listOnly.activeTaskId}` })++ expect(direct.status).toBe(403)+ })++ it('gets no task of the project on the main screen or in search', async () => {+ const stateIds = stateTaskIds(await fetchState(collaborator.access))+ const searchIds = (await searchTasks(collaborator.access, marker)).map((t) => t.id)++ for (const id of bucketIds(listOnly)) {+ expect(stateIds).not.toContain(id)+ expect(searchIds).not.toContain(id)+ }+ })+})++describe('tokens issued by the collaborator', () => {+ it('an unrestricted token sees shared projects like the session does', async () => {+ const scoped = await issueCollaboratorToken({ allowedPermissions: [], allowedGoalIds: [] })+ const state = await fetchState(scoped.token)+ const ids = stateTaskIds(state)++ for (const id of [...bucketIds(full), ...bucketIds(contentOnly)]) expect(ids).toContain(id)+ expect(state.tasks.find((t) => t.id === full.activeTaskId)!.note).toBe(full.note)+ })++ it('a token for one shared project sees only that project', async () => {+ const scoped = await issueCollaboratorToken({ allowedPermissions: [], allowedGoalIds: [full.goalId] })+ const stateIds = stateTaskIds(await fetchState(scoped.token))+ const searchIds = (await searchTasks(scoped.token, marker)).map((t) => t.id)+ const lists = (await fetchLists(scoped.token)).map((l) => l.goalId)++ for (const id of bucketIds(full)) expect(stateIds).toContain(id)+ for (const id of bucketIds(contentOnly)) expect(stateIds).not.toContain(id)+ expect(searchIds).toContain(full.activeTaskId)+ expect(searchIds).not.toContain(contentOnly.activeTaskId)+ expect(lists).toContain(full.goalId)+ expect(lists).not.toContain(contentOnly.goalId)+ expect(lists).not.toContain(listOnly.goalId)+ })++ it('a token without task_can_watch_note hides the note the editor role would show', async () => {+ const scoped = await issueCollaboratorToken({+ allowedPermissions: ['goal_can_watch_content', 'component_can_watch_content'],+ allowedGoalIds: [],+ })+ const task = (await fetchState(scoped.token)).tasks.find((t) => t.id === full.activeTaskId)++ expect(task).toBeDefined()+ expect(task!.note).toBeNull()+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/start-shared-projects.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/start-shared-projects.test.types.tsnew file mode 100644index 0000000..a7d2e4f--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/start-shared-projects.test.types.ts@@ -0,0 +1,18 @@+export type SharedProjectRole = 'editor' | string[]++export type CreateSharedProjectArgs = {+ name: string+ role: SharedProjectRole+}++export type SharedProjectFixture = {+ goalId: number+ listId: number+ tagId: number+ activeTaskId: number+ todayTaskId: number+ upcomingTaskId: number+ completedTaskId: number+ collaboratorId: number+ note: string+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/start-test-helpers.ts b/taskview-packages/taskview-api/src/api/__tests__/start-test-helpers.tsnew file mode 100644index 0000000..01ca314--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/start-test-helpers.ts@@ -0,0 +1,59 @@+import { TvApi } from '@/tv'+import axios from 'axios'+import { expect } from 'vitest'+import { API_URL } from './init-api'+import { noThrow } from './auth-test-helpers'+import type { StartScreenState } from '../start.types'+import type { CollaborationResponseFetchAllUsers } from '../collaboration.types'+import type { TagItem } from '../tags.api.types'+import type { RawGetArgs, RawGetResult, StartListRow, StartSearchRow } from './start-test-helpers.types'++export function clientFor(token: string): TvApi {+ return new TvApi(axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${token}` },+ }))+}++export async function rawGet<T>(args: RawGetArgs): Promise<RawGetResult<T>> {+ const res = await axios.get(`${API_URL}${args.path}`, {+ params: args.params,+ headers: { Authorization: `Bearer ${args.token}` },+ ...noThrow,+ })+ return { status: res.status, body: res.data?.response }+}++export async function fetchState(token: string): Promise<StartScreenState> {+ const res = await rawGet<StartScreenState>({ token, path: '/module/about/fetchallstate', params: { tz: 'UTC' } })+ expect(res.status).toBe(200)+ return res.body!+}++export async function searchTasks(token: string, description: string): Promise<StartSearchRow[]> {+ const res = await rawGet<StartSearchRow[]>({ token, path: '/module/about/search-task', params: { description } })+ expect(res.status).toBe(200)+ return res.body!+}++export async function fetchLists(token: string): Promise<StartListRow[]> {+ const res = await rawGet<StartListRow[]>({ token, path: '/module/about/fetch/lists' })+ expect(res.status).toBe(200)+ return res.body!+}++export async function fetchCollaborators(token: string): Promise<CollaborationResponseFetchAllUsers[]> {+ const res = await rawGet<CollaborationResponseFetchAllUsers[]>({ token, path: '/module/collaboration' })+ expect(res.status).toBe(200)+ return res.body!+}++export async function fetchTags(token: string): Promise<TagItem[]> {+ const res = await rawGet<TagItem[]>({ token, path: '/module/tags' })+ expect(res.status).toBe(200)+ return res.body!+}++export function stateTaskIds(state: StartScreenState): number[] {+ return [...state.tasks, ...state.tasksToday, ...state.tasksUpcoming, ...state.tasksLastCompleted].map((t) => t.id)+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/start-test-helpers.types.ts b/taskview-packages/taskview-api/src/api/__tests__/start-test-helpers.types.tsnew file mode 100644index 0000000..f1ff205--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/start-test-helpers.types.ts@@ -0,0 +1,24 @@+export type RawGetArgs = {+ token: string+ path: string+ params?: Record<string, string>+}++export type RawGetResult<T> = {+ status: number+ body: T | undefined+}++export type StartListRow = {+ goalId: number+ goalName: string+ listId: number+ listName: string+}++export type StartSearchRow = {+ id: number+ goalId: number+ description: string+ note: string | null+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/start-token-scope.test.ts b/taskview-packages/taskview-api/src/api/__tests__/start-token-scope.test.tsnew file mode 100644index 0000000..64c66b5--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/start-token-scope.test.ts@@ -0,0 +1,393 @@+import type { TvApi } from '@/tv'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { initApi } from './init-api'+import { ymd } from './test-helpers'+import { openTestDb } from './test-db'+import { createSessionUser } from './auth-test-helpers'+import type { AuthTestContext } from './auth-test-helpers.types'+import {+ clientFor,+ fetchCollaborators,+ fetchLists,+ fetchState,+ fetchTags,+ rawGet,+ searchTasks,+ stateTaskIds,+} from './start-test-helpers'+import type { ScopedToken, ScopedTokenArgs, StartScopeFixture } from './start-token-scope.test.types'++/**+ * The main screen routes (/module/about/*) and the cross-project collaborator and+ * tag lists build their project set from "every project I own or that is shared+ * with me" and never intersect it with the API token's allowedGoalIds or+ * allowedPermissions. A token issued for one project therefore reads tasks, notes,+ * collaborator emails, list names and tags of the issuer's other projects, while+ * the ordinary task and goal routes deny the same token.+ *+ * The owner is a fresh account so the LIMIT 30 of the start queries cannot push+ * the fixture tasks out and make a leak look like a pass.+ */+const ctx = {} as AuthTestContext+const fx = {} as StartScopeFixture+const tokenIds: number[] = []+let otherUserApi: TvApi+let user2Email: string++async function issueToken(args: ScopedTokenArgs): Promise<ScopedToken> {+ const created = await fx.ownerApi.apiTokens.create({+ name: `start-scope-${Date.now()}-${Math.random()}`,+ allowedPermissions: args.allowedPermissions,+ allowedGoalIds: args.allowedGoalIds,+ })+ tokenIds.push(created!.item.id)+ return { token: created!.token, api: clientFor(created!.token) }+}++function excludedTaskIds(): number[] {+ return [+ fx.projectB.activeTaskId,+ fx.projectB.todayTaskId,+ fx.projectB.upcomingTaskId,+ fx.projectB.completedTaskId,+ fx.projectC.activeTaskId,+ ]+}++beforeAll(async () => {+ const init = await initApi()+ otherUserApi = init.$tvApi+ user2Email = init.user2Email+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Start scope org ${Date.now()}` })+ ctx.orgId = org.id++ fx.marker = `TVSCOPE${Date.now()}`+ fx.owner = await createSessionUser({ ctx, prefix: 'scope' })+ fx.ownerApi = clientFor(fx.owner.access)++ const goalA = await fx.ownerApi.goals.createGoal({ name: `${fx.marker}_A` })+ const listA = await fx.ownerApi.goalLists.createList({ goalId: goalA!.id!, name: `${fx.marker}_LIST_A` })+ const tagA = await fx.ownerApi.tags.createTag({ goalId: goalA!.id!, name: `${fx.marker}_TAG_A`, color: '#00aa00' })+ const taskA = await fx.ownerApi.tasks.createTask({+ goalId: goalA!.id!,+ description: `${fx.marker}_TASK_A`,+ note: `${fx.marker}_NOTE_A`,+ })+ const collabA = await fx.ownerApi.collaboration.inviteUserToGoal({ goalId: goalA!.id!, email: user2Email })+ await fx.ownerApi.tasks.toggleTasksAssignee({ taskId: taskA!.id, userIds: [collabA!.id] })+ fx.projectA = {+ goalId: goalA!.id!,+ listId: listA!.id,+ tagId: tagA!.id,+ activeTaskId: taskA!.id,+ collaboratorId: collabA!.id,+ }++ const goalB = await fx.ownerApi.goals.createGoal({ name: `${fx.marker}_B` })+ const goalBId = goalB!.id!+ const listB = await fx.ownerApi.goalLists.createList({ goalId: goalBId, name: `${fx.marker}_LIST_B` })+ const tagB = await fx.ownerApi.tags.createTag({ goalId: goalBId, name: `${fx.marker}_TAG_B`, color: '#aa0000' })+ const collaboratorEmail = `scope-collab-${Date.now()}@leak.example`+ const collabB = await fx.ownerApi.collaboration.inviteUserToGoal({ goalId: goalBId, email: collaboratorEmail })+ const activeB = await fx.ownerApi.tasks.createTask({+ goalId: goalBId,+ description: `${fx.marker}_TASK_B_ACTIVE`,+ note: `${fx.marker}_NOTE_B`,+ })+ await fx.ownerApi.tasks.toggleTasksAssignee({ taskId: activeB!.id, userIds: [collabB!.id] })+ const todayB = await fx.ownerApi.tasks.createTask({ goalId: goalBId, description: `${fx.marker}_TASK_B_TODAY` })+ await fx.ownerApi.tasks.updateTask({ id: todayB!.id, endDate: ymd(0) })+ const upcomingB = await fx.ownerApi.tasks.createTask({ goalId: goalBId, description: `${fx.marker}_TASK_B_UPCOMING` })+ await fx.ownerApi.tasks.updateTask({ id: upcomingB!.id, endDate: ymd(7) })+ const completedB = await fx.ownerApi.tasks.createTask({ goalId: goalBId, description: `${fx.marker}_TASK_B_DONE` })+ await fx.ownerApi.tasks.updateTask({ id: completedB!.id, complete: true })+ fx.projectB = {+ goalId: goalBId,+ listId: listB!.id,+ tagId: tagB!.id,+ activeTaskId: activeB!.id,+ todayTaskId: todayB!.id,+ upcomingTaskId: upcomingB!.id,+ completedTaskId: completedB!.id,+ collaboratorEmail,+ }++ const goalC = await otherUserApi.goals.createGoal({ name: `${fx.marker}_C` })+ const goalCId = goalC!.id!+ const listC = await otherUserApi.goalLists.createList({ goalId: goalCId, name: `${fx.marker}_LIST_C` })+ const tagC = await otherUserApi.tags.createTag({ goalId: goalCId, name: `${fx.marker}_TAG_C`, color: '#0000aa' })+ const taskC = await otherUserApi.tasks.createTask({+ goalId: goalCId,+ description: `${fx.marker}_TASK_C`,+ note: `${fx.marker}_NOTE_C`,+ })+ const ownerInC = await otherUserApi.collaboration.inviteUserToGoal({ goalId: goalCId, email: fx.owner.email })+ const rolesC = await otherUserApi.collaboration.fetchRolesForGoal(goalCId)+ const editorC = rolesC!.find((r) => r.name === 'editor')+ await otherUserApi.collaboration.toggleUserRoles({ goalId: goalCId, userId: ownerInC!.id, roles: [editorC!.id] })+ fx.projectC = {+ goalId: goalCId,+ listId: listC!.id,+ tagId: tagC!.id,+ activeTaskId: taskC!.id,+ }+})++afterAll(async () => {+ for (const id of tokenIds) {+ await fx.ownerApi.apiTokens.delete(id).catch(() => {})+ }+ for (const goalId of [fx.projectA?.goalId, fx.projectB?.goalId]) {+ if (goalId) await fx.ownerApi.goals.deleteGoal(goalId).catch(() => {})+ }+ if (fx.projectC?.goalId) await otherUserApi.goals.deleteGoal(fx.projectC.goalId).catch(() => {})+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+})++describe('fixture sanity: the owner session sees all three projects', () => {+ it('fetchallstate holds every fixture task, note and assignee', async () => {+ const state = await fetchState(fx.owner.access)+ const ids = stateTaskIds(state)++ expect(ids).toContain(fx.projectA.activeTaskId)+ for (const id of excludedTaskIds()) expect(ids).toContain(id)+ expect(state.tasks.find((t) => t.id === fx.projectB.activeTaskId)?.note).toBe(`${fx.marker}_NOTE_B`)+ expect(state.assignees.some((a) => a.taskId === fx.projectB.activeTaskId)).toBe(true)+ expect(state.users.find((g) => g.id === fx.projectB.goalId)?.users.map((u) => u.email))+ .toContain(fx.projectB.collaboratorEmail)+ })++ it('search, lists, collaborators and tags cover all three projects', async () => {+ const found = (await searchTasks(fx.owner.access, fx.marker)).map((t) => t.id)+ const lists = (await fetchLists(fx.owner.access)).map((l) => l.listId)+ const collaboratorGoals = (await fetchCollaborators(fx.owner.access)).map((c) => c.goalId)+ const tags = (await fetchTags(fx.owner.access)).map((t) => t.id)++ expect(found).toEqual(expect.arrayContaining([fx.projectA.activeTaskId, fx.projectB.activeTaskId, fx.projectC.activeTaskId]))+ expect(lists).toEqual(expect.arrayContaining([fx.projectA.listId, fx.projectB.listId, fx.projectC.listId]))+ expect(collaboratorGoals).toEqual(expect.arrayContaining([fx.projectA.goalId, fx.projectB.goalId, fx.projectC.goalId]))+ expect(tags).toEqual(expect.arrayContaining([fx.projectA.tagId, fx.projectB.tagId, fx.projectC.tagId]))+ })+})++describe('token restricted to project A (all permissions)', () => {+ let scoped: ScopedToken++ beforeAll(async () => {+ scoped = await issueToken({ allowedPermissions: [], allowedGoalIds: [fx.projectA.goalId] })+ })++ it('is denied by the ordinary goal and task routes for B and C', async () => {+ const goals = (await scoped.api.goals.fetchGoals())!.map((g) => g.id)+ const directB = await rawGet({ token: scoped.token, path: `/module/tasks/${fx.projectB.activeTaskId}` })+ const directC = await rawGet({ token: scoped.token, path: `/module/tasks/${fx.projectC.activeTaskId}` })++ expect(goals).toEqual([fx.projectA.goalId])+ expect(directB.status).toBe(403)+ expect(directC.status).toBe(403)+ })++ it('fetchallstate keeps project A tasks', async () => {+ const state = await fetchState(scoped.token)++ expect(state.tasks.map((t) => t.id)).toContain(fx.projectA.activeTaskId)+ })++ it('fetchallstate does not return active tasks of B or C', async () => {+ const ids = (await fetchState(scoped.token)).tasks.map((t) => t.id)++ expect(ids).not.toContain(fx.projectB.activeTaskId)+ expect(ids).not.toContain(fx.projectC.activeTaskId)+ })++ it('fetchallstate does not leak B notes anywhere in the payload', async () => {+ const state = await fetchState(scoped.token)++ expect(JSON.stringify(state)).not.toContain(`${fx.marker}_NOTE_B`)+ expect(JSON.stringify(state)).not.toContain(`${fx.marker}_NOTE_C`)+ })++ it('fetchallstate does not return B tasks in the today bucket', async () => {+ const ids = (await fetchState(scoped.token)).tasksToday.map((t) => t.id)++ expect(ids).not.toContain(fx.projectB.todayTaskId)+ })++ it('fetchallstate does not return B tasks in the upcoming bucket', async () => {+ const ids = (await fetchState(scoped.token)).tasksUpcoming.map((t) => t.id)++ expect(ids).not.toContain(fx.projectB.upcomingTaskId)+ })++ it('fetchallstate does not return B tasks in the last completed bucket', async () => {+ const ids = (await fetchState(scoped.token)).tasksLastCompleted.map((t) => t.id)++ expect(ids).not.toContain(fx.projectB.completedTaskId)+ })++ it('fetchallstate keeps A assignees but drops assignees of B tasks', async () => {+ const state = await fetchState(scoped.token)++ expect(state.assignees.some((a) => a.taskId === fx.projectA.activeTaskId)).toBe(true)+ expect(state.assignees.some((a) => a.taskId === fx.projectB.activeTaskId)).toBe(false)+ })++ it('fetchallstate does not disclose B collaborators and their emails', async () => {+ const state = await fetchState(scoped.token)++ expect(state.users.map((g) => g.id)).not.toContain(fx.projectB.goalId)+ expect(JSON.stringify(state)).not.toContain(fx.projectB.collaboratorEmail)+ })++ it('search-task finds A tasks only', async () => {+ const ids = (await searchTasks(scoped.token, fx.marker)).map((t) => t.id)++ expect(ids).toContain(fx.projectA.activeTaskId)+ expect(ids).not.toContain(fx.projectB.activeTaskId)+ expect(ids).not.toContain(fx.projectC.activeTaskId)+ })++ it('search-task by #id does not return a B task', async () => {+ const found = await searchTasks(scoped.token, `#${fx.projectB.activeTaskId}`)++ expect(found).toEqual([])+ })++ it('fetch/lists returns A lists only', async () => {+ const rows = await fetchLists(scoped.token)++ expect(rows.map((r) => r.listId)).toContain(fx.projectA.listId)+ expect(rows.map((r) => r.goalId)).not.toContain(fx.projectB.goalId)+ expect(rows.map((r) => r.goalId)).not.toContain(fx.projectC.goalId)+ })++ it('collaboration list returns A collaborators only', async () => {+ const goalIds = (await fetchCollaborators(scoped.token)).map((c) => c.goalId)++ expect(goalIds).toContain(fx.projectA.goalId)+ expect(goalIds).not.toContain(fx.projectB.goalId)+ expect(goalIds).not.toContain(fx.projectC.goalId)+ })++ it('tags list returns A tags only', async () => {+ const tagIds = (await fetchTags(scoped.token)).map((t) => t.id)++ expect(tagIds).toContain(fx.projectA.tagId)+ expect(tagIds).not.toContain(fx.projectB.tagId)+ expect(tagIds).not.toContain(fx.projectC.tagId)+ })+})++describe('token from the report: goal_can_watch_content + component_can_watch_content on A', () => {+ let scoped: ScopedToken++ beforeAll(async () => {+ scoped = await issueToken({+ allowedPermissions: ['goal_can_watch_content', 'component_can_watch_content'],+ allowedGoalIds: [fx.projectA.goalId],+ })+ })++ it('fetchallstate and search-task return no B or C tasks', async () => {+ const stateIds = stateTaskIds(await fetchState(scoped.token))+ const searchIds = (await searchTasks(scoped.token, fx.marker)).map((t) => t.id)++ for (const id of excludedTaskIds()) {+ expect(stateIds).not.toContain(id)+ expect(searchIds).not.toContain(id)+ }+ })++ it('fetchallstate serializes an A task the same way the task route does for this token', async () => {+ const direct = await scoped.api.tasks.fetchTaskById(fx.projectA.activeTaskId)+ const fromStart = (await fetchState(scoped.token)).tasks.find((t) => t.id === fx.projectA.activeTaskId)++ expect(fromStart).toBeDefined()+ expect(direct!.note).not.toBe(`${fx.marker}_NOTE_A`)+ expect(fromStart!.note).toBe(direct!.note)+ })++ it('search-task does not return the A note without task_can_watch_note', async () => {+ const fromSearch = (await searchTasks(scoped.token, fx.marker)).find((t) => t.id === fx.projectA.activeTaskId)++ expect(fromSearch).toBeDefined()+ expect(fromSearch!.note).not.toBe(`${fx.marker}_NOTE_A`)+ })++ it('fetchallstate does not expose assignees or collaborator emails without the matching permissions', async () => {+ const state = await fetchState(scoped.token)++ expect(state.assignees).toEqual([])+ expect(state.users.flatMap((g) => g.users)).toEqual([])+ })++ it('tags list returns nothing without task_can_watch_tags', async () => {+ const tagIds = (await fetchTags(scoped.token)).map((t) => t.id)++ expect(tagIds).not.toContain(fx.projectA.tagId)+ expect(tagIds).not.toContain(fx.projectB.tagId)+ })+})++describe('list-only token: goal_can_watch_content on B', () => {+ let scoped: ScopedToken++ beforeAll(async () => {+ scoped = await issueToken({ allowedPermissions: ['goal_can_watch_content'], allowedGoalIds: [fx.projectB.goalId] })+ })++ it('is denied by the ordinary task route', async () => {+ const direct = await rawGet({ token: scoped.token, path: `/module/tasks/${fx.projectB.activeTaskId}` })++ expect(direct.status).toBe(403)+ })++ it('may still see B lists, which goal_can_watch_content grants', async () => {+ const rows = await fetchLists(scoped.token)++ expect(rows.map((r) => r.listId)).toContain(fx.projectB.listId)+ })++ it('fetchallstate returns no B task in any bucket', async () => {+ const ids = stateTaskIds(await fetchState(scoped.token))++ expect(ids).not.toContain(fx.projectB.activeTaskId)+ expect(ids).not.toContain(fx.projectB.todayTaskId)+ expect(ids).not.toContain(fx.projectB.upcomingTaskId)+ expect(ids).not.toContain(fx.projectB.completedTaskId)+ })++ it('fetchallstate does not leak the B note', async () => {+ const state = await fetchState(scoped.token)++ expect(JSON.stringify(state)).not.toContain(`${fx.marker}_NOTE_B`)+ })++ it('fetchallstate does not expose B assignees or collaborator emails', async () => {+ const state = await fetchState(scoped.token)++ expect(state.assignees.some((a) => a.taskId === fx.projectB.activeTaskId)).toBe(false)+ expect(JSON.stringify(state)).not.toContain(fx.projectB.collaboratorEmail)+ })++ it('search-task returns no B task', async () => {+ const ids = (await searchTasks(scoped.token, fx.marker)).map((t) => t.id)++ expect(ids).not.toContain(fx.projectB.activeTaskId)+ })++ it('collaboration list does not expose B collaborators without user permissions', async () => {+ const collaborators = await fetchCollaborators(scoped.token)++ expect(collaborators.map((c) => c.email)).not.toContain(fx.projectB.collaboratorEmail)+ })++ it('tags list does not return B tags without task_can_watch_tags', async () => {+ const tagIds = (await fetchTags(scoped.token)).map((t) => t.id)++ expect(tagIds).not.toContain(fx.projectB.tagId)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/start-token-scope.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/start-token-scope.test.types.tsnew file mode 100644index 0000000..fabcc53--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/start-token-scope.test.types.ts@@ -0,0 +1,38 @@+import type { TvApi } from '@/tv'+import type { SessionUser } from './auth-test-helpers.types'++export type StartScopeProject = {+ goalId: number+ listId: number+ tagId: number+ activeTaskId: number+}++export type StartScopeExcludedProject = StartScopeProject & {+ todayTaskId: number+ upcomingTaskId: number+ completedTaskId: number+ collaboratorEmail: string+}++export type StartScopeFixture = {+ marker: string+ owner: SessionUser+ ownerApi: TvApi+ /** owned by `owner`, the only project the scoped tokens are issued for */+ projectA: StartScopeProject & { collaboratorId: number }+ /** owned by `owner`, excluded from every project-scoped token */+ projectB: StartScopeExcludedProject+ /** owned by another user and shared with `owner` as editor, excluded from every project-scoped token */+ projectC: StartScopeProject+}++export type ScopedTokenArgs = {+ allowedPermissions: string[]+ allowedGoalIds: number[]+}++export type ScopedToken = {+ token: string+ api: TvApi+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/start.test.ts b/taskview-packages/taskview-api/src/api/__tests__/start.test.tsindex 9ade617..13671ce 100644--- a/taskview-packages/taskview-api/src/api/__tests__/start.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/start.test.ts@@ -6,8 +6,12 @@ import {beforeAll,afterAll,} from 'vitest';-import { initApi } from './init-api';+import axios from 'axios';+import { API_URL, initApi } from './init-api';import { ymd } from './test-helpers';+import { openTestDb } from './test-db';+import { createSessionUser } from './auth-test-helpers';+import type { AuthTestContext } from './auth-test-helpers.types';/*** The main screen endpoint. It answers "what do I have today" in one request and@@ -87,3 +91,47 @@ describe('Start screen state', () => {expect(status).toBe(400);});});++/**+ * The "recent tasks" bucket lists tasks without a deadline, newest first. A fresh+ * user keeps it free of tasks other specs create in parallel.+ */+describe('Start screen recent tasks', () => {+ const ctx = {} as AuthTestContext;+ let $userApi: TvApi;+ let goalId: number;++ beforeAll(async () => {+ const init = await initApi();+ ctx.ownerApi = init.$tvApi;+ ctx.db = await openTestDb();+ const org = await ctx.ownerApi.organizations.create({ name: `Recent tasks org ${Date.now()}` });+ ctx.orgId = org.id;++ const user = await createSessionUser({ ctx, prefix: 'rec' });+ $userApi = new TvApi(axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${user.access}` },+ }));+ const goal = await $userApi.goals.createGoal({ name: `Recent tasks-${Date.now()}` });+ goalId = goal!.id!;+ });++ afterAll(async () => {+ await $userApi.goals.deleteGoal(goalId).catch(() => {});+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {});+ await ctx.db.end();+ });++ it('lists the last added task first, whatever the priority, including one whose deadline was removed', async () => {+ const highPriority = await $userApi.tasks.createTask({ goalId, description: 'Older, high priority', priorityId: 3 });+ const lowPriority = await $userApi.tasks.createTask({ goalId, description: 'Newer, low priority', priorityId: 1 });+ const wasToday = await $userApi.tasks.createTask({ goalId, description: 'Added to today', endDate: ymd(0) });+ await $userApi.tasks.updateTask({ id: wasToday!.id, endDate: null });++ const state = await $userApi.start.fetchAllState({ tz: 'UTC' });++ expect(state!.tasks.map((t) => t.id)).toEqual([wasToday!.id, lowPriority!.id, highPriority!.id]);+ expect(state!.tasksToday.some((t) => t.id === wasToday!.id)).toBe(false);+ });+});diff --git a/taskview-packages/taskview-api/src/api/__tests__/tasks-cross-goal.test.ts b/taskview-packages/taskview-api/src/api/__tests__/tasks-cross-goal.test.tsnew file mode 100644index 0000000..cb2e4d0--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/tasks-cross-goal.test.ts@@ -0,0 +1,238 @@+import { TvApi } from '@/tv'+import axios, { type AxiosInstance } from 'axios'+import type { Client } from 'pg'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { API_URL, DEFAULT_PASSWORD, DEFAULT_USER_2, initApi } from './init-api'+import { openTestDb } from './test-db'+import type { CrossGoalFixture, TaskRow } from './tasks-cross-goal.test.types'++/**+ * Authorization of a task write is checked on one project: the project of the task being+ * updated, or the goalId of the task being created. A list, kanban column or parent named in+ * the same request must belong to that project — otherwise a DB trigger rewrites goal_id from+ * the list and the task lands on the board of a project the caller is not a member of.+ */+describe('Task writes stay inside the authorized project', () => {+ let ownerApi: TvApi+ let attackerApi: TvApi+ let attackerAxios: AxiosInstance+ let deleteAllGoals: () => Promise<void>+ let db: Client+ let attackerUserId: number+ let victimUserId: number+ const fx = {} as CrossGoalFixture++ beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ attackerApi = init.$tvApiForSecondUser+ deleteAllGoals = init.deleteAllGoals+ db = await openTestDb()++ const auth = await axios.post(`${API_URL}/module/auth/login`, {+ login: DEFAULT_USER_2,+ password: DEFAULT_PASSWORD,+ })+ attackerUserId = auth.data.userData.id+ attackerAxios = axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${auth.data.access}` },+ validateStatus: () => true,+ })+ const victimRow = await db.query<{ id: number }>('select id from tv_auth.users where email = $1', [init.user1Email])+ victimUserId = victimRow.rows[0].id++ const victimGoal = await ownerApi.goals.createGoal({ name: `Victim cross-goal ${Date.now()}` })+ if (!victimGoal) throw new Error('Failed to create victim goal')+ fx.victimGoalId = victimGoal.id+ const victimList = await ownerApi.goalLists.createList({ goalId: victimGoal.id, name: 'Victim list' })+ if (!victimList) throw new Error('Failed to create victim list')+ fx.victimListId = victimList.id+ const victimColumn = await ownerApi.kanban.addColumn({ goalId: victimGoal.id, name: 'Victim column' })+ if (!victimColumn) throw new Error('Failed to create victim column')+ fx.victimColumnId = victimColumn.id+ const victimTask = await ownerApi.tasks.createTask({ goalId: victimGoal.id, description: `victim-${Date.now()}` })+ if (!victimTask) throw new Error('Failed to create victim task')+ fx.victimTaskId = victimTask.id+ const victimSprint = await ownerApi.sprints.create({+ goalId: victimGoal.id,+ name: 'Victim sprint',+ startDate: '2026-01-01',+ endDate: '2026-01-14',+ })+ if (!victimSprint) throw new Error('Failed to create victim sprint')+ fx.victimSprintId = victimSprint.id++ const attackerGoal = await attackerApi.goals.createGoal({ name: `Attacker cross-goal ${Date.now()}` })+ if (!attackerGoal) throw new Error('Failed to create attacker goal')+ fx.attackerGoalId = attackerGoal.id+ const attackerList = await attackerApi.goalLists.createList({ goalId: attackerGoal.id, name: 'Attacker list' })+ if (!attackerList) throw new Error('Failed to create attacker list')+ fx.attackerListId = attackerList.id+ const attackerColumn = await attackerApi.kanban.addColumn({ goalId: attackerGoal.id, name: 'Attacker column' })+ if (!attackerColumn) throw new Error('Failed to create attacker column')+ fx.attackerColumnId = attackerColumn.id+ })++ afterAll(async () => {+ await deleteAllGoals()+ await db.end()+ })++ async function readTask(taskId: number): Promise<TaskRow> {+ const result = await db.query<TaskRow>(+ `select goal_id, goal_list_id, status_id, parent_id, sprint_id, creator_id, source_url, date_complete,+ recurrence_rule_id+ from tasks.tasks where id = $1`,+ [taskId]+ )+ expect(result.rows).toHaveLength(1)+ return result.rows[0]+ }++ async function countTasksWithDescription(description: string): Promise<number> {+ const result = await db.query<{ total: number }>(+ 'select count(*)::int as total from tasks.tasks where description = $1',+ [description]+ )+ return result.rows[0].total+ }++ async function createAttackerTask(): Promise<number> {+ const task = await attackerApi.tasks.createTask({+ goalId: fx.attackerGoalId,+ goalListId: fx.attackerListId,+ description: `attacker-${Date.now()}`,+ })+ if (!task) throw new Error('Failed to create attacker task')+ return task.id+ }++ describe('updating a task (PATCH /module/tasks)', () => {+ it("rejects moving the task into another project's list", async () => {+ const taskId = await createAttackerTask()++ const res = await attackerAxios.patch('/module/tasks', { id: taskId, goalListId: fx.victimListId })++ expect(res.status).toBe(400)+ const row = await readTask(taskId)+ expect(row.goal_id).toBe(fx.attackerGoalId)+ expect(row.goal_list_id).toBe(fx.attackerListId)+ })++ it("rejects putting the task into another project's kanban column", async () => {+ const taskId = await createAttackerTask()++ const res = await attackerAxios.patch('/module/tasks', { id: taskId, statusId: fx.victimColumnId })++ expect(res.status).toBe(400)+ expect((await readTask(taskId)).status_id).toBeNull()+ })++ it("rejects making the task a subtask of another project's task", async () => {+ const taskId = await createAttackerTask()++ const res = await attackerAxios.patch('/module/tasks', { id: taskId, parentId: fx.victimTaskId })++ expect(res.status).toBe(400)+ expect((await readTask(taskId)).parent_id).toBeNull()+ })++ it("the victim's list does not show the attacker's task", async () => {+ const taskId = await createAttackerTask()+ await attackerAxios.patch('/module/tasks', { id: taskId, goalListId: fx.victimListId })++ const victimTasks = await ownerApi.tasks.fetch({+ goalId: fx.victimGoalId,+ componentId: fx.victimListId,+ page: 0,+ showCompleted: 0,+ firstNew: 0,+ })+ const ids = (victimTasks ?? []).map(t => t.id)+ expect(ids).not.toContain(taskId)+ })+ })++ describe('creating a task (POST /module/tasks)', () => {+ it("rejects creating a task in another project's list", async () => {+ const description = `injected-list-${Date.now()}`++ const res = await attackerAxios.post('/module/tasks', {+ goalId: fx.attackerGoalId,+ goalListId: fx.victimListId,+ description,+ })++ expect(res.status).toBe(400)+ expect(await countTasksWithDescription(description)).toBe(0)+ })++ it("rejects creating a task in another project's kanban column", async () => {+ const description = `injected-column-${Date.now()}`++ const res = await attackerAxios.post('/module/tasks', {+ goalId: fx.attackerGoalId,+ statusId: fx.victimColumnId,+ description,+ })++ expect(res.status).toBe(400)+ expect(await countTasksWithDescription(description)).toBe(0)+ })++ it("rejects creating a subtask under another project's task", async () => {+ const description = `injected-subtask-${Date.now()}`++ const res = await attackerAxios.post('/module/tasks', {+ goalId: fx.attackerGoalId,+ parentId: fx.victimTaskId,+ description,+ })++ expect(res.status).toBe(400)+ expect(await countTasksWithDescription(description)).toBe(0)+ })++ it('ignores server-managed columns sent next to the declared fields', async () => {+ const res = await attackerAxios.post('/module/tasks', {+ goalId: fx.attackerGoalId,+ description: `injected-columns-${Date.now()}`,+ sprintId: fx.victimSprintId,+ creatorId: victimUserId,+ sourceUrl: 'https://phishing.example/login',+ dateComplete: '2020-01-01 00:00:00',+ recurrenceRuleId: 1,+ })++ expect(res.status).toBe(200)+ const row = await readTask(res.data.response.id)+ expect(row.goal_id).toBe(fx.attackerGoalId)+ expect(row.sprint_id).toBeNull()+ expect(row.creator_id).toBe(attackerUserId)+ expect(row.source_url).toBeNull()+ expect(row.date_complete).toBeNull()+ expect(row.recurrence_rule_id).toBeNull()+ })++ it("control: creates a task in the project's own list, column and under its own parent", async () => {+ const parentId = await createAttackerTask()++ const res = await attackerAxios.post('/module/tasks', {+ goalId: fx.attackerGoalId,+ goalListId: fx.attackerListId,+ statusId: fx.attackerColumnId,+ parentId,+ description: `own-${Date.now()}`,+ })++ expect(res.status).toBe(200)+ const row = await readTask(res.data.response.id)+ expect(row.goal_id).toBe(fx.attackerGoalId)+ expect(row.goal_list_id).toBe(fx.attackerListId)+ expect(row.status_id).toBe(fx.attackerColumnId)+ expect(row.parent_id).toBe(parentId)+ expect(row.creator_id).toBe(attackerUserId)+ })+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/tasks-cross-goal.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/tasks-cross-goal.test.types.tsnew file mode 100644index 0000000..ff6a2ef--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/tasks-cross-goal.test.types.ts@@ -0,0 +1,22 @@+export type CrossGoalFixture = {+ victimGoalId: number+ victimListId: number+ victimColumnId: number+ victimTaskId: number+ victimSprintId: number+ attackerGoalId: number+ attackerListId: number+ attackerColumnId: number+}++export type TaskRow = {+ goal_id: number+ goal_list_id: number | null+ status_id: number | null+ parent_id: number | null+ sprint_id: number | null+ creator_id: number | null+ source_url: string | null+ date_complete: Date | null+ recurrence_rule_id: number | null+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/tasks.test.ts b/taskview-packages/taskview-api/src/api/__tests__/tasks.test.tsindex 5bab0dd..a66a539 100644--- a/taskview-packages/taskview-api/src/api/__tests__/tasks.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/tasks.test.ts@@ -16,7 +16,8 @@ const taskItemMatch = {description: 'test task-1761603103605',complete: false,goalListId: null,- creatorId: null,+ // set by the server to the user who created the task+ creatorId: 1,note: null,owner: 1,priorityId: 1,diff --git a/taskview-packages/taskview-api/src/api/__tests__/test-db.ts b/taskview-packages/taskview-api/src/api/__tests__/test-db.tsnew file mode 100644index 0000000..03e067c--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/test-db.ts@@ -0,0 +1,15 @@+import { Client } from 'pg'+import { DB_CREDENTIALS } from './db-credentials'++/** A direct connection to the test stack database, for state the API never exposes (e.g. emailed codes). */+export async function openTestDb(): Promise<Client> {+ const client = new Client({+ host: DB_CREDENTIALS.DB_HOST || 'localhost',+ port: parseInt(DB_CREDENTIALS.DB_PORT || '15432', 10),+ database: DB_CREDENTIALS.DB_NAME || 'taskviewdb',+ user: DB_CREDENTIALS.DB_USER || 'tvdbuser',+ password: DB_CREDENTIALS.DB_PASSWORD || 'tvdbpass',+ })+ await client.connect()+ return client+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/time-tracking.test.ts b/taskview-packages/taskview-api/src/api/__tests__/time-tracking.test.tsindex dd5106f..1b74968 100644--- a/taskview-packages/taskview-api/src/api/__tests__/time-tracking.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/time-tracking.test.ts@@ -577,6 +577,41 @@ describe('TvApi time-tracking tests', () => {expect(del?.deleted).toBe(true);});+ it('cannot log own time without TIMETRACKING_CAN_LOG', async () => {+ const status = await $invitedUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(45),+ endedAt: isoMinutesAgo(20),+ }).then(() => 200).catch((err) => err.status);+ expect(status).toBe(403);+ });++ it('cannot list goal entries or read history without TIMETRACKING_CAN_VIEW', async () => {+ const ownerEntry = await $mainUser.timeTracking.createManual({+ taskId,+ startedAt: isoMinutesAgo(60),+ endedAt: isoMinutesAgo(30),+ }).catch(console.error);+ expect(ownerEntry).toBeDefined();++ const listStatus = await $invitedUser.timeTracking.fetchEntries({ goalId })+ .then(() => 200).catch((err) => err.status);+ const historyStatus = await $invitedUser.timeTracking.fetchHistory(ownerEntry!.id)+ .then(() => 200).catch((err) => err.status);+ expect(listStatus).toBe(403);+ expect(historyStatus).toBe(403);+ });+ });++ describe('5b. Invited user with TIMETRACKING_CAN_MANAGE_ALL, _VIEW and _LOG', () => {+ beforeEach(async () => {+ await inviteUserToGoalWithRole(goalId, `tt-manage-view-log-${timestamp}`, [+ TvPermissions.TIMETRACKING_CAN_MANAGE_ALL,+ TvPermissions.TIMETRACKING_CAN_VIEW,+ TvPermissions.TIMETRACKING_CAN_LOG,+ ]);+ });+it('sees all goal entries (own and owner) via fetchEntries with goalId', async () => {const ownerEntry = await $mainUser.timeTracking.createManual({taskId,diff --git a/taskview-packages/taskview-api/src/api/__tests__/token-scope-organization.test.ts b/taskview-packages/taskview-api/src/api/__tests__/token-scope-organization.test.tsindex 3fc6819..ecf9536 100644--- a/taskview-packages/taskview-api/src/api/__tests__/token-scope-organization.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/token-scope-organization.test.ts@@ -360,14 +360,22 @@ describe('API token scope on organization-level surfaces', () => {expect(status).toBe(403);});- it('allows a token holding webhooks_can_manage', async () => {- const client = await scopedClient(['webhooks_can_manage']);+ it('lets a token holding webhooks_can_view list webhooks', async () => {+ const client = await scopedClient(['webhooks_can_view']);const status = await statusOf(client.webhooks.fetch(goalId));expectAllowed(status);});+ it('does not let webhooks_can_manage alone list webhooks', async () => {+ const client = await scopedClient(['webhooks_can_manage']);++ const status = await statusOf(client.webhooks.fetch(goalId));++ expect(status).toBe(403);+ });+it('allows an unrestricted token', async () => {const client = await scopedClient([]);diff --git a/taskview-packages/taskview-api/src/api/__tests__/ui-preferences.test.ts b/taskview-packages/taskview-api/src/api/__tests__/ui-preferences.test.tsindex 5db41f8..160559b 100644--- a/taskview-packages/taskview-api/src/api/__tests__/ui-preferences.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/ui-preferences.test.ts@@ -1,5 +1,12 @@import { TvApi } from '@/tv'-import { UI_SETTINGS_KEY, type UiPreferences, type UiSettings } from '@/api/ui-preferences.types'+import {+ THEME_NEUTRAL_COLORS,+ THEME_PRIMARY_COLORS,+ UI_SETTINGS_KEY,+ type CustomTheme,+ type UiPreferences,+ type UiSettings,+} from '@/api/ui-preferences.types'import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { initApi } from './init-api'import { expectApiError } from './automations-test-helpers'@@ -47,6 +54,108 @@ describe('UI preferences: remembered task sort', () => {})})+ it('stores whether keyboard shortcuts are turned off', async () => {+ const saved = await api.uiPreferences.update({+ ...original,+ [UI_SETTINGS_KEY]: { ...settingsOf(original), keyboardShortcuts: 0 },+ })+ expect(settingsOf(saved)).toMatchObject({ keyboardShortcuts: 0 })+ expect(settingsOf(await api.uiPreferences.fetch())).toMatchObject({ keyboardShortcuts: 0 })++ await expectApiError({+ request: api.uiPreferences.update({ [UI_SETTINGS_KEY]: { keyboardShortcuts: false as never } }),+ status: 400,+ })+ await expectApiError({+ request: api.uiPreferences.update({ [UI_SETTINGS_KEY]: { keyboardShortcuts: 2 as never } }),+ status: 400,+ })+ })++ it('stores the theme accent and neutral colors', async () => {+ const saved = await api.uiPreferences.update({+ ...original,+ [UI_SETTINGS_KEY]: { ...settingsOf(original), primaryColor: 'violet', neutralColor: 'stone' },+ })+ expect(settingsOf(saved)).toMatchObject({ primaryColor: 'violet', neutralColor: 'stone' })+ expect(settingsOf(await api.uiPreferences.fetch())).toMatchObject({ primaryColor: 'violet', neutralColor: 'stone' })+ })++ it('accepts every color the theme picker offers', async () => {+ for (const primaryColor of THEME_PRIMARY_COLORS) {+ const saved = await api.uiPreferences.update({ [UI_SETTINGS_KEY]: { primaryColor } })+ expect(settingsOf(saved).primaryColor).toBe(primaryColor)+ }+ for (const neutralColor of THEME_NEUTRAL_COLORS) {+ const saved = await api.uiPreferences.update({ [UI_SETTINGS_KEY]: { neutralColor } })+ expect(settingsOf(saved).neutralColor).toBe(neutralColor)+ }+ })++ it('rejects a theme color outside the palette', async () => {+ await expectApiError({+ request: api.uiPreferences.update({ [UI_SETTINGS_KEY]: { primaryColor: '#ff0000' as never } }),+ status: 400,+ })+ await expectApiError({+ request: api.uiPreferences.update({ [UI_SETTINGS_KEY]: { primaryColor: 'zinc' as never } }),+ status: 400,+ })+ await expectApiError({+ request: api.uiPreferences.update({ [UI_SETTINGS_KEY]: { neutralColor: 'blue' as never } }),+ status: 400,+ })+ await expectApiError({+ request: api.uiPreferences.update({ [UI_SETTINGS_KEY]: { primaryColor: 'moss' as never } }),+ status: 400,+ })+ })++ const customTheme: CustomTheme = {+ light: { background: '#ffffff', surface: '#f4f7f5', border: '#d9e2dc', text: '#1f2a23', accent: '#16a34a' },+ dark: { background: '#1c2a20', surface: '#233a2c', border: '#2a4434', text: '#e2ebe5', accent: '#4ade80' },+ }++ it('stores a custom theme and whether it is turned on', async () => {+ const saved = await api.uiPreferences.update({+ ...original,+ [UI_SETTINGS_KEY]: { ...settingsOf(original), customTheme, customThemeActive: 1 },+ })+ expect(settingsOf(saved)).toMatchObject({ customTheme, customThemeActive: 1 })+ expect(settingsOf(await api.uiPreferences.fetch())).toMatchObject({ customTheme, customThemeActive: 1 })+ })++ it('rejects a custom theme color that is not a #rrggbb hex value', async () => {+ for (const value of ['red', '#fff', 'oklch(0.5 0.1 150)', '#000000;} body{display:none']) {+ await expectApiError({+ request: api.uiPreferences.update({+ [UI_SETTINGS_KEY]: { customTheme: { ...customTheme, dark: { ...customTheme.dark, background: value } } },+ }),+ status: 400,+ })+ }+ })++ it('rejects a custom theme with a missing or unknown color', async () => {+ const { accent: _accent, ...withoutAccent } = customTheme.light+ await expectApiError({+ request: api.uiPreferences.update({+ [UI_SETTINGS_KEY]: { customTheme: { ...customTheme, light: withoutAccent as never } },+ }),+ status: 400,+ })+ await expectApiError({+ request: api.uiPreferences.update({+ [UI_SETTINGS_KEY]: { customTheme: { ...customTheme, light: { ...customTheme.light, shadow: '#000000' } as never } },+ }),+ status: 400,+ })+ await expectApiError({+ request: api.uiPreferences.update({ [UI_SETTINGS_KEY]: { customThemeActive: 2 as never } }),+ status: 400,+ })+ })+it('rejects a sort field or direction the task list does not support', async () => {await expectApiError({request: api.uiPreferences.update({ [UI_SETTINGS_KEY]: { taskSortBy: 'name' as never } }),diff --git a/taskview-packages/taskview-api/src/api/__tests__/webhooks-permissions.test.ts b/taskview-packages/taskview-api/src/api/__tests__/webhooks-permissions.test.tsnew file mode 100644index 0000000..8f8e6ce--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/webhooks-permissions.test.ts@@ -0,0 +1,323 @@+import type { TvApi } from '@/tv'+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { initApi } from './init-api'+import { openTestDb } from './test-db'+import { createSessionUser } from './auth-test-helpers'+import type { AuthTestContext } from './auth-test-helpers.types'+import { clientFor } from './start-test-helpers'+import { createWebhookReceiver } from './webhook-receiver'+import type {+ AddMemberArgs,+ MemberTokenArgs,+ WebhooksMember,+ WebhooksPermissionsFixture,+} from './webhooks-permissions.test.types'++/**+ * Webhooks are governed by two independent project permissions: webhooks_can_view+ * lists the webhooks and their delivery history, webhooks_can_manage changes them —+ * managing does not include viewing. Both work for any project member whose role+ * grants them, not only for the owner, and a token narrows them like everywhere else. Every write is verified through the+ * owner session, not only by the status code.+ */+const ctx = {} as AuthTestContext+const fx = {} as WebhooksPermissionsFixture+const receiver = createWebhookReceiver()+const tokenIds: { member: WebhooksMember; id: number }[] = []+let permissionIds: Record<string, number> = {}++const statusOf = async (call: Promise<unknown>) =>+ call.then(() => 200).catch((err) => err.status ?? err.response?.status)++async function freshUser(prefix: string): Promise<WebhooksMember> {+ const user = await createSessionUser({ ctx, prefix })+ return { user, api: clientFor(user.access) }+}++async function addMember(member: WebhooksMember, args: AddMemberArgs): Promise<void> {+ const collab = await fx.owner.api.collaboration.inviteUserToGoal({ goalId: args.goalId, email: member.user.email })+ const role = await fx.owner.api.collaboration.createRoleForGoal({+ goalId: args.goalId,+ roleName: `webhooks-${Date.now()}-${Math.random()}`,+ })+ for (const name of args.permissions) {+ const permissionId = permissionIds[name]+ if (!permissionId) throw new Error(`Permission ${name} is not in the catalogue`)+ const toggled = await fx.owner.api.collaboration.toggleRolePermission({ roleId: role!.id, permissionId })+ expect(toggled!.add).toBe(true)+ }+ await fx.owner.api.collaboration.toggleUserRoles({ goalId: args.goalId, userId: collab!.id, roles: [role!.id] })+}++async function memberToken(args: MemberTokenArgs): Promise<TvApi> {+ const created = await args.member.api.apiTokens.create({+ name: `webhooks-perm-${Date.now()}-${Math.random()}`,+ allowedPermissions: args.allowedPermissions,+ allowedGoalIds: args.allowedGoalIds,+ })+ tokenIds.push({ member: args.member, id: created!.item.id })+ return clientFor(created!.token)+}++async function ownerWebhooks(goalId: number) {+ return (await fx.owner.api.webhooks.fetch(goalId))!+}++beforeAll(async () => {+ const init = await initApi()+ ctx.ownerApi = init.$tvApi+ ctx.db = await openTestDb()+ const org = await ctx.ownerApi.organizations.create({ name: `Webhooks permissions org ${Date.now()}` })+ ctx.orgId = org.id+ await receiver.start()++ fx.owner = await freshUser('whown')+ fx.viewer = await freshUser('whview')+ fx.manager = await freshUser('whman')+ fx.member = await freshUser('whmem')+ fx.fullManager = await freshUser('whfull')++ const catalogue = await fx.owner.api.collaboration.fetchAllPermissions()+ permissionIds = Object.fromEntries(catalogue!.map((p) => [p.name, p.id]))++ const goal = await fx.owner.api.goals.createGoal({ name: `webhooks-permissions-${Date.now()}` })+ fx.goalId = goal!.id!+ const privateGoal = await fx.owner.api.goals.createGoal({ name: `webhooks-private-${Date.now()}` })+ fx.privateGoalId = privateGoal!.id!++ fx.webhookUrl = receiver.getUrl()+ const hook = await fx.owner.api.webhooks.create({ goalId: fx.goalId, url: fx.webhookUrl, events: ['task.created'] })+ fx.webhookId = hook!.webhook.id+ const privateHook = await fx.owner.api.webhooks.create({ goalId: fx.privateGoalId, url: fx.webhookUrl, events: ['task.created'] })+ fx.privateWebhookId = privateHook!.webhook.id++ await fx.owner.api.tasks.createTask({ goalId: fx.goalId, description: `webhooks-permissions-task-${Date.now()}` })+ await receiver.waitForDelivery('task.created', 5000)+ const deliveries = await fx.owner.api.webhooks.fetchDeliveries(fx.webhookId)+ fx.deliveryId = deliveries![0].id++ await addMember(fx.viewer, { goalId: fx.goalId, permissions: ['goal_can_watch_content', 'webhooks_can_view'] })+ await addMember(fx.manager, { goalId: fx.goalId, permissions: ['goal_can_watch_content', 'webhooks_can_manage'] })+ await addMember(fx.member, { goalId: fx.goalId, permissions: ['goal_can_watch_content'] })+ await addMember(fx.fullManager, { goalId: fx.goalId, permissions: ['goal_can_watch_content', 'webhooks_can_view', 'webhooks_can_manage'] })+}, 30000)++afterAll(async () => {+ for (const token of tokenIds) {+ await token.member.api.apiTokens.delete(token.id).catch(() => {})+ }+ for (const goalId of [fx.goalId, fx.privateGoalId]) {+ if (goalId) await fx.owner.api.goals.deleteGoal(goalId).catch(() => {})+ }+ await ctx.ownerApi.organizations.delete(ctx.orgId).catch(() => {})+ await ctx.db.end()+ await receiver.stop()+})++describe('permission catalogue', () => {+ it('offers webhooks_can_view and webhooks_can_manage in a webhooks group of their own', async () => {+ const catalogue = await fx.owner.api.collaboration.fetchAllPermissions()+ const view = catalogue!.find((p) => p.name === 'webhooks_can_view')+ const manage = catalogue!.find((p) => p.name === 'webhooks_can_manage')++ expect(view?.permissionGroup).toBe(9)+ expect(manage?.permissionGroup).toBe(9)+ })++ it('carries localized descriptions for webhooks_can_view', async () => {+ const catalogue = await fx.owner.api.apiTokens.fetchPermissions()+ const view = catalogue!.find((p) => p.name === 'webhooks_can_view')++ expect(view?.descriptionLocales?.en).toBeTruthy()+ expect(view?.descriptionLocales?.ru).toBeTruthy()+ })++ it('grants both to the project owner', async () => {+ const goal = (await fx.owner.api.goals.fetchGoals())!.find((g) => g.id === fx.goalId)++ expect(goal!.permissions.webhooks_can_view).toBe(true)+ expect(goal!.permissions.webhooks_can_manage).toBe(true)+ })+})++describe('member with webhooks_can_view', () => {+ it('lists the webhooks of the project with the full URL', async () => {+ const hooks = await fx.viewer.api.webhooks.fetch(fx.goalId)++ expect(hooks!.find((h) => h.id === fx.webhookId)?.url).toBe(fx.webhookUrl)+ })++ it('reads the delivery history with payloads', async () => {+ const deliveries = await fx.viewer.api.webhooks.fetchDeliveries(fx.webhookId)+ const delivery = deliveries!.find((d) => d.id === fx.deliveryId)++ expect(delivery?.event).toBe('task.created')+ expect(delivery?.payload).toBeTruthy()+ })++ it('cannot create a webhook', async () => {+ const before = (await ownerWebhooks(fx.goalId)).map((h) => h.id)++ const status = await statusOf(fx.viewer.api.webhooks.create({+ goalId: fx.goalId,+ url: `https://viewer.test/${Date.now()}`,+ events: ['task.created'],+ }))++ expect(status).toBe(403)+ expect((await ownerWebhooks(fx.goalId)).map((h) => h.id)).toEqual(before)+ })++ it('cannot update, rotate, test or delete a webhook, or retry a delivery', async () => {+ const results = await Promise.all([+ statusOf(fx.viewer.api.webhooks.update({ id: fx.webhookId, url: `https://viewer.test/${Date.now()}` })),+ statusOf(fx.viewer.api.webhooks.rotateSecret(fx.webhookId)),+ statusOf(fx.viewer.api.webhooks.testDelivery(fx.webhookId)),+ statusOf(fx.viewer.api.webhooks.retryDelivery(fx.deliveryId)),+ statusOf(fx.viewer.api.webhooks.delete({ id: fx.webhookId })),+ ])++ expect(results).toEqual([403, 403, 403, 403, 403])+ const hook = (await ownerWebhooks(fx.goalId)).find((h) => h.id === fx.webhookId)+ expect(hook!.url).toBe(fx.webhookUrl)+ })+})++describe('member with webhooks_can_manage', () => {+ it('cannot list webhooks or read deliveries without webhooks_can_view', async () => {+ const results = await Promise.all([+ statusOf(fx.manager.api.webhooks.fetch(fx.goalId)),+ statusOf(fx.manager.api.webhooks.fetchDeliveries(fx.webhookId)),+ ])++ expect(results).toEqual([403, 403])+ })++ it('creates, updates, rotates, tests and deletes a webhook', async () => {+ const created = await fx.manager.api.webhooks.create({+ goalId: fx.goalId,+ url: `https://manager.test/${Date.now()}`,+ events: ['task.created'],+ })+ const id = created!.webhook.id+ const newUrl = `https://manager.test/renamed-${Date.now()}`++ await fx.manager.api.webhooks.update({ id, url: newUrl })+ const rotated = await fx.manager.api.webhooks.rotateSecret(id)+ const testStatus = await statusOf(fx.manager.api.webhooks.testDelivery(id))++ expect((await ownerWebhooks(fx.goalId)).find((h) => h.id === id)?.url).toBe(newUrl)+ expect(rotated!.secret).toBeTruthy()+ expect(testStatus).toBe(200)++ await fx.manager.api.webhooks.delete({ id })+ expect((await ownerWebhooks(fx.goalId)).map((h) => h.id)).not.toContain(id)+ })++ it('retries a delivery of the project', async () => {+ const status = await statusOf(fx.manager.api.webhooks.retryDelivery(fx.deliveryId))++ expect(status).toBe(200)+ })++ it('cannot touch a webhook of a project it is not a member of', async () => {+ const results = await Promise.all([+ statusOf(fx.manager.api.webhooks.fetch(fx.privateGoalId)),+ statusOf(fx.manager.api.webhooks.fetchDeliveries(fx.privateWebhookId)),+ statusOf(fx.manager.api.webhooks.update({ id: fx.privateWebhookId, url: `https://manager.test/${Date.now()}` })),+ statusOf(fx.manager.api.webhooks.delete({ id: fx.privateWebhookId })),+ ])++ expect(results).toEqual([403, 403, 403, 403])+ expect((await ownerWebhooks(fx.privateGoalId)).map((h) => h.id)).toContain(fx.privateWebhookId)+ })+})++describe('member with both webhooks_can_view and webhooks_can_manage', () => {+ it('lists webhooks, reads deliveries and creates a webhook', async () => {+ const hooks = await fx.fullManager.api.webhooks.fetch(fx.goalId)+ const deliveries = await fx.fullManager.api.webhooks.fetchDeliveries(fx.webhookId)+ const created = await fx.fullManager.api.webhooks.create({+ goalId: fx.goalId,+ url: `https://full.test/${Date.now()}`,+ events: ['task.created'],+ })++ expect(hooks!.map((h) => h.id)).toContain(fx.webhookId)+ expect(deliveries!.map((d) => d.id)).toContain(fx.deliveryId)+ expect((await ownerWebhooks(fx.goalId)).map((h) => h.id)).toContain(created!.webhook.id)++ await fx.fullManager.api.webhooks.delete({ id: created!.webhook.id })+ })+})++describe('member without webhook permissions', () => {+ it('cannot list webhooks or read deliveries', async () => {+ const results = await Promise.all([+ statusOf(fx.member.api.webhooks.fetch(fx.goalId)),+ statusOf(fx.member.api.webhooks.fetchDeliveries(fx.webhookId)),+ ])++ expect(results).toEqual([403, 403])+ })++ it('cannot create a webhook or retry a delivery', async () => {+ const results = await Promise.all([+ statusOf(fx.member.api.webhooks.create({+ goalId: fx.goalId,+ url: `https://member.test/${Date.now()}`,+ events: ['task.created'],+ })),+ statusOf(fx.member.api.webhooks.retryDelivery(fx.deliveryId)),+ ])++ expect(results).toEqual([403, 403])+ })+})++describe('owner', () => {+ it('retries a delivery of its own webhook', async () => {+ const status = await statusOf(fx.owner.api.webhooks.retryDelivery(fx.deliveryId))++ expect(status).toBe(200)+ })++ it('cannot retry a delivery id of another project through its own webhook', async () => {+ const outsider = await freshUser('whout')+ const outsiderGoal = await outsider.api.goals.createGoal({ name: `webhooks-outsider-${Date.now()}` })+ await outsider.api.webhooks.create({ goalId: outsiderGoal!.id!, url: `https://outsider.test/${Date.now()}`, events: ['task.created'] })++ const status = await statusOf(outsider.api.webhooks.retryDelivery(fx.deliveryId))++ expect(status).toBe(403)+ await outsider.api.goals.deleteGoal(outsiderGoal!.id!).catch(() => {})+ })+})++describe('tokens narrow webhook permissions', () => {+ it('an owner token holding only webhooks_can_view lists but cannot create', async () => {+ const client = await memberToken({ member: fx.owner, allowedPermissions: ['webhooks_can_view'], allowedGoalIds: [fx.goalId] })++ const fetchStatus = await statusOf(client.webhooks.fetch(fx.goalId))+ const createStatus = await statusOf(client.webhooks.create({+ goalId: fx.goalId,+ url: `https://token.test/${Date.now()}`,+ events: ['task.created'],+ }))++ expect(fetchStatus).toBe(200)+ expect(createStatus).toBe(403)+ })++ it('a viewer token asking for webhooks_can_manage still cannot create', async () => {+ const client = await memberToken({ member: fx.viewer, allowedPermissions: ['webhooks_can_manage'], allowedGoalIds: [fx.goalId] })++ const status = await statusOf(client.webhooks.create({+ goalId: fx.goalId,+ url: `https://token.test/${Date.now()}`,+ events: ['task.created'],+ }))++ expect(status).toBe(403)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/webhooks-permissions.test.types.ts b/taskview-packages/taskview-api/src/api/__tests__/webhooks-permissions.test.types.tsnew file mode 100644index 0000000..0ee17a7--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/webhooks-permissions.test.types.ts@@ -0,0 +1,37 @@+import type { TvApi } from '@/tv'+import type { SessionUser } from './auth-test-helpers.types'++export type WebhooksMember = {+ user: SessionUser+ api: TvApi+}++export type WebhooksPermissionsFixture = {+ owner: WebhooksMember+ /** role: goal_can_watch_content + webhooks_can_view */+ viewer: WebhooksMember+ /** role: goal_can_watch_content + webhooks_can_manage */+ manager: WebhooksMember+ /** role: goal_can_watch_content only */+ member: WebhooksMember+ /** role: goal_can_watch_content + webhooks_can_view + webhooks_can_manage */+ fullManager: WebhooksMember+ goalId: number+ /** another project of the owner nobody else is a member of */+ privateGoalId: number+ privateWebhookId: number+ webhookId: number+ webhookUrl: string+ deliveryId: number+}++export type AddMemberArgs = {+ goalId: number+ permissions: string[]+}++export type MemberTokenArgs = {+ member: WebhooksMember+ allowedPermissions: string[]+ allowedGoalIds: number[]+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/webhooks-sprints.test.ts b/taskview-packages/taskview-api/src/api/__tests__/webhooks-sprints.test.tsindex 85909d2..997275a 100644--- a/taskview-packages/taskview-api/src/api/__tests__/webhooks-sprints.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/webhooks-sprints.test.ts@@ -133,7 +133,10 @@ describe('Webhooks: sprint events', () => {expect(typeof signature).toBe('string')expect(String(signature)).toMatch(/^sha256=/)- await $api.sprints.remove(sprint.id).catch(() => {})+ receiver.clear()+ await $api.sprints.remove(sprint.id)+ // Drain our own sprint.deleted here: delivered late, it would land in the next test.+ await receiver.waitForDelivery('sprint.deleted')}, 15000)it('delivers sprint.deleted with ids only (no sprint body)', async () => {diff --git a/taskview-packages/taskview-api/src/api/kanban.ts b/taskview-packages/taskview-api/src/api/kanban.tsindex 8056768..8f2d7a0 100644--- a/taskview-packages/taskview-api/src/api/kanban.ts+++ b/taskview-packages/taskview-api/src/api/kanban.ts@@ -1,6 +1,6 @@import TvApiBase from './base';import type { AppResponse } from '@/api/base.types';-import type { KanbanArgAddColumn, KanbanArgDeleteColumn, KanbanArgUpdateColumn, KanbanArgUpdateTasksOrder, KanbanColumnItem, KanbanFilters, KanbanResponseDeleteColumn, KanbanResponseTasksForColumn, KanbanResponseTasksOrderForColumnAndCursor, KanbanResponseUpdateColumn, KanbanResponseUpdateTasksOrder } from './kanban.types';+import type { KanbanArgAddColumn, KanbanArgDeleteColumn, KanbanArgReorderColumns, KanbanArgUpdateColumn, KanbanArgUpdateTasksOrder, KanbanColumnItem, KanbanFilters, KanbanResponseDeleteColumn, KanbanResponseReorderColumns, KanbanResponseTasksForColumn, KanbanResponseTasksOrderForColumnAndCursor, KanbanResponseUpdateColumn, KanbanResponseUpdateTasksOrder } from './kanban.types';import type { Task } from './tasks.api.types';export default class TvKanban extends TvApiBase {@@ -44,6 +44,12 @@ export default class TvKanban extends TvApiBase {);}+ public async reorderColumns(data: KanbanArgReorderColumns) {+ return this.request(+ this.$axios.patch<AppResponse<KanbanResponseReorderColumns>>(`${this.moduleUrl}/reorder-statuses`, data)+ );+ }+public async deleteColumn(data: KanbanArgDeleteColumn) {return this.request(this.$axios.post<AppResponse<KanbanResponseDeleteColumn>>(`${this.moduleUrl}/delete-status`, data)diff --git a/taskview-packages/taskview-api/src/api/kanban.types.ts b/taskview-packages/taskview-api/src/api/kanban.types.tsindex fa9334a..13eee95 100644--- a/taskview-packages/taskview-api/src/api/kanban.types.ts+++ b/taskview-packages/taskview-api/src/api/kanban.types.ts@@ -20,6 +20,13 @@ export type KanbanResponseAddColumn = KanbanColumnItem | null;export type KanbanArgUpdateColumn = { id: number; name: string; viewOrder?: number };export type KanbanResponseUpdateColumn = boolean;+export type KanbanArgReorderColumns = {+ goalId: number;+ /** every column of the project, in the new order */+ statusIds: number[];+};+export type KanbanResponseReorderColumns = KanbanColumnItem[];+export type KanbanArgDeleteColumn = { id: number };export type KanbanResponseDeleteColumn = boolean;diff --git a/taskview-packages/taskview-api/src/api/permissions.ts b/taskview-packages/taskview-api/src/api/permissions.tsindex 9edadcd..93b55ae 100644--- a/taskview-packages/taskview-api/src/api/permissions.ts+++ b/taskview-packages/taskview-api/src/api/permissions.ts@@ -142,9 +142,9 @@ export const TvPermissions: Record<Uppercase<keyof GoalPermissions>, keyof GoalP*/TIMETRACKING_CAN_LOG: 'timetracking_can_log',/**- * Full time-tracking access on this project: log own time, view all entries- * (own and other members'), and edit/delete entries of any project member.- * Implies both view and log permissions.+ * Edit and delete time entries of any project member and stop their timers.+ * Does not include viewing entries (TIMETRACKING_CAN_VIEW) or logging own+ * time (TIMETRACKING_CAN_LOG) — grant those separately.*/TIMETRACKING_CAN_MANAGE_ALL: 'timetracking_can_manage_all',@@ -182,6 +182,15 @@ export const TvPermissions: Record<Uppercase<keyof GoalPermissions>, keyof GoalP* Can create, edit, enable, disable and delete automation rules*/AUTOMATION_CAN_MANAGE: 'automation_can_manage',++ /**+ * Can see the project's webhooks, their URLs and the delivery history with payloads+ */+ WEBHOOKS_CAN_VIEW: 'webhooks_can_view',+ /**+ * Can create, edit, delete and test the project's webhooks and retry deliveries+ */+ WEBHOOKS_CAN_MANAGE: 'webhooks_can_manage',} as const;export type GoalPermissions = {@@ -241,4 +250,7 @@ export type GoalPermissions = {automation_can_view?: true;automation_can_manage?: true;++ webhooks_can_view?: true;+ webhooks_can_manage?: true;};\ No newline at end of filediff --git a/taskview-packages/taskview-api/src/api/ui-preferences.types.ts b/taskview-packages/taskview-api/src/api/ui-preferences.types.tsindex 77de580..a90e6cc 100644--- a/taskview-packages/taskview-api/src/api/ui-preferences.types.ts+++ b/taskview-packages/taskview-api/src/api/ui-preferences.types.ts@@ -11,6 +11,36 @@ export type FirstDayOfWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6export type DefaultView = 'tasks' | 'kanban' | 'graph' | 'sprints'+export const THEME_PRIMARY_COLORS = [+ 'red', 'orange', 'amber', 'yellow', 'lime', 'green', 'emerald', 'teal', 'cyan',+ 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose',+] as const++export const THEME_NEUTRAL_COLORS = [+ 'slate', 'gray', 'zinc', 'neutral', 'stone',+ 'moss', 'tide', 'ink', 'plum', 'wine', 'sand',+] as const++export type ThemePrimaryColor = typeof THEME_PRIMARY_COLORS[number]++export type ThemeNeutralColor = typeof THEME_NEUTRAL_COLORS[number]++export const DEFAULT_THEME_PRIMARY_COLOR: ThemePrimaryColor = 'green'++export const DEFAULT_THEME_NEUTRAL_COLOR: ThemeNeutralColor = 'zinc'++export const CUSTOM_THEME_COLOR_KEYS = ['background', 'surface', 'border', 'text', 'accent'] as const++export type CustomThemeColorKey = typeof CUSTOM_THEME_COLOR_KEYS[number]++/** Hex colors (#rrggbb) for one color mode. */+export type CustomThemePalette = Record<CustomThemeColorKey, string>++export type CustomTheme = {+ light: CustomThemePalette+ dark: CustomThemePalette+}+export type UiSettings = {firstDayOfWeek?: FirstDayOfWeekdefaultProjectId?: number@@ -18,6 +48,11 @@ export type UiSettings = {taskSortBy?: TaskSortBytaskSortFirstNew?: 0 | 1showTaskId?: 0 | 1+ keyboardShortcuts?: 0 | 1+ primaryColor?: ThemePrimaryColor+ neutralColor?: ThemeNeutralColor+ customTheme?: CustomTheme+ customThemeActive?: 0 | 1}export const UI_SETTINGS_KEY = '__settings__'diff --git a/taskview-packages/taskview-db-schemas/src/index.ts b/taskview-packages/taskview-db-schemas/src/index.tsindex dac9b12..9d9ad33 100644--- a/taskview-packages/taskview-db-schemas/src/index.ts+++ b/taskview-packages/taskview-db-schemas/src/index.ts@@ -5,6 +5,8 @@ export * from './schemas/tags.schema';export * from './schemas/users.schema';export * from './schemas/collaboration-users.schema';export * from './schemas/invite-emails.schema';+export * from './schemas/login-code-requests.schema';+export * from './schemas/account-deletion.schema';export * from './schemas/tasks-assignee.schema';export * from './schemas/goals.schema';export * from './schemas/goals-list.schema';diff --git a/taskview-packages/taskview-db-schemas/src/schemas/account-deletion.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/account-deletion.schema.tsnew file mode 100644index 0000000..3dfb837--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/account-deletion.schema.ts@@ -0,0 +1,12 @@+import { integer, pgSchema, serial, timestamp, varchar } from "drizzle-orm/pg-core";+import { UsersSchema } from "./users.schema";++export const AccountDeletionSchema = pgSchema('tv_auth').table('account_deletion', {+ id: serial().notNull(),+ code: varchar(),+ userId: integer('user_id').references(() => UsersSchema.id, { onDelete: 'cascade' }),+ createdAt: timestamp('created_at').notNull().defaultNow(),+});++export type AccountDeletionSchemaTypeForSelect = typeof AccountDeletionSchema.$inferSelect;+export type AccountDeletionSchemaTypeForInsert = typeof AccountDeletionSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/login-code-requests.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/login-code-requests.schema.tsnew file mode 100644index 0000000..a3573c7--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/login-code-requests.schema.ts@@ -0,0 +1,11 @@+import { integer, pgSchema, timestamp } from "drizzle-orm/pg-core";+import { UsersSchema } from "./users.schema";++export const LoginCodeRequestsSchema = pgSchema('tv_auth').table('login_code_requests', {+ id: integer().primaryKey().generatedAlwaysAsIdentity(),+ userId: integer('user_id').notNull().references(() => UsersSchema.id, { onDelete: 'cascade' }),+ requestedAt: timestamp('requested_at').notNull().defaultNow(),+});++export type LoginCodeRequestsSchemaTypeForSelect = typeof LoginCodeRequestsSchema.$inferSelect;+export type LoginCodeRequestsSchemaTypeForInsert = typeof LoginCodeRequestsSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/tasks-statuses.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/tasks-statuses.schema.tsindex bb8965b..44baa0f 100644--- a/taskview-packages/taskview-db-schemas/src/schemas/tasks-statuses.schema.ts+++ b/taskview-packages/taskview-db-schemas/src/schemas/tasks-statuses.schema.ts@@ -5,6 +5,7 @@ export const TasksStatusesSchema = pgSchema('tasks').table('statuses', {id: integer().primaryKey().generatedAlwaysAsIdentity(),name: varchar().notNull(),goalId: integer('goal_id').notNull().references(() => GoalsSchema.id, { onDelete: 'cascade' }),+ viewOrder: integer('view_order'),columnVersion: integer('column_version'),});diff --git a/taskview-packages/taskview-db-schemas/src/schemas/users.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/users.schema.tsindex 7d831ad..b55dd15 100644--- a/taskview-packages/taskview-db-schemas/src/schemas/users.schema.ts+++ b/taskview-packages/taskview-db-schemas/src/schemas/users.schema.ts@@ -10,6 +10,7 @@ export const UsersSchema = pgSchema('tv_auth').table('users', {remindPasswordCode: varchar('remind_password_code'),remindPasswordTime: integer('remind_password_time'),rememberToken: varchar('remember_token'),+ loginCodeAttempts: integer('login_code_attempts').notNull().default(0),});export const PermissionsSchema = pgSchema('tv_auth').table('permissions', {diff --git a/web/e2e/fixtures/auth.ts b/web/e2e/fixtures/auth.tsindex 9b8cce1..f244d7a 100644--- a/web/e2e/fixtures/auth.ts+++ b/web/e2e/fixtures/auth.ts@@ -1,8 +1,19 @@/**- * E2E auth fixtures. Credentials match DB seed from community migrations- * (user / user1!#Q from app_permissions.sql).+ * E2E auth fixtures. TEST_USER matches the DB seed from community migrations+ * (user / user1!#Q from app_permissions.sql); the INBOX_* accounts come from+ * fixtures/seed-users.sql, applied by docker-setup.sh.*/export const TEST_USER = {login: 'user',password: 'user1!#Q',}++export const INBOX_OWNER = {+ login: 'inbox_owner',+ password: 'user1!#Q',+}++export const INBOX_COLLEAGUE = {+ login: 'inbox_colleague',+ password: 'user1!#Q',+}diff --git a/web/e2e/fixtures/seed-users.sql b/web/e2e/fixtures/seed-users.sqlnew file mode 100644index 0000000..8e47e67--- /dev/null+++ b/web/e2e/fixtures/seed-users.sql@@ -0,0 +1,26 @@+-- E2E-only accounts, applied by docker-setup.sh after the migrations. Password: user1!#Q (same as the seed user).+-- Each gets a personal workspace with an Inbox, like a regular sign-up. Safe to run repeatedly.+INSERT INTO tv_auth.users (login, email, password, block, confirm_email_code)+SELECT v.login, v.email, '$2y$10$q8SLauZ0Syz9aEFdiq0i8.jIlafLj5T0ujXYD7RmRzyNkZ2hR7uhO', 0, ''+FROM (VALUES ('inbox_owner', '[email protected]'), ('inbox_colleague', '[email protected]')) AS v(login, email)+WHERE NOT EXISTS (SELECT 1 FROM tv_auth.users u WHERE u.email = v.email);++INSERT INTO tv_auth.organizations (name, slug, owner_id, is_personal)+SELECT u.login || '''s workspace', 'e2e-' || replace(u.login, '_', '-'), u.id, 1+FROM tv_auth.users u+WHERE u.email IN ('[email protected]', '[email protected]')+ AND NOT EXISTS (SELECT 1 FROM tv_auth.organizations o WHERE o.owner_id = u.id AND o.is_personal = 1);++INSERT INTO tv_auth.organization_members (organization_id, email, role)+SELECT o.id, u.email, 'owner'+FROM tv_auth.organizations o+JOIN tv_auth.users u ON u.id = o.owner_id+WHERE o.is_personal = 1 AND u.email IN ('[email protected]', '[email protected]')+ON CONFLICT (organization_id, email) DO NOTHING;++INSERT INTO tasks.goals (name, owner, organization_id, is_inbox)+SELECT 'Inbox', o.owner_id, o.id, TRUE+FROM tv_auth.organizations o+JOIN tv_auth.users u ON u.id = o.owner_id+WHERE o.is_personal = 1 AND u.email IN ('[email protected]', '[email protected]')+ AND NOT EXISTS (SELECT 1 FROM tasks.goals g WHERE g.organization_id = o.id AND g.is_inbox);diff --git a/web/e2e/inbox.spec.ts b/web/e2e/inbox.spec.tsnew file mode 100644index 0000000..62f9bfb--- /dev/null+++ b/web/e2e/inbox.spec.ts@@ -0,0 +1,150 @@+import { test, expect, request as pwRequest, type APIRequestContext, type Page } from '@playwright/test'+import { INBOX_COLLEAGUE, INBOX_OWNER } from './fixtures/auth'+import { setEnglishLocale } from './test-helpers'+import type {+ InboxE2eAccount,+ InboxE2eCredentials,+ InboxE2eApiGetArgs,+ InboxE2eApiSendArgs,+ InboxE2eGoal,+ InboxE2eJwtUser,+ InboxE2eOpenWorkspaceArgs,+ InboxE2eOrganization,+} from './inbox.spec.types'++/**+ * Being invited into a project of someone else's personal workspace makes you a member of+ * that workspace, so the workspace list holds several personal workspaces and a shared Inbox+ * may be among your projects. The sidebar Inbox must still be your own one.+ */+const API_URL = process.env.E2E_API_URL ?? 'http://localhost:1401'+const ALL_TASKS_LIST_ID = -1401++let api: APIRequestContext+let me: InboxE2eAccount+let colleague: InboxE2eAccount++function jwtUserData(token: string): InboxE2eJwtUser {+ return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()).userData+}++async function apiGet<T>(args: InboxE2eApiGetArgs): Promise<T> {+ const response = await api.get(`${API_URL}${args.path}`, { headers: { Authorization: `Bearer ${args.token}` } })+ expect(response.status()).toBe(200)+ return (await response.json()).response+}++async function apiSend(args: InboxE2eApiSendArgs): Promise<void> {+ const response = await api[args.method](`${API_URL}${args.path}`, {+ data: args.data,+ headers: { Authorization: `Bearer ${args.token}` },+ })+ expect(response.status()).toBe(200)+}++async function accountFor(token: string): Promise<InboxE2eAccount> {+ const user = jwtUserData(token)+ const orgs = await apiGet<InboxE2eOrganization[]>({+ token,+ path: '/module/organizations',+ })+ const personal = orgs.find((org) => org.isPersonal && org.ownerId === user.id)!+ const goals = await apiGet<InboxE2eGoal[]>({+ token,+ path: `/module/goals?organizationId=${personal.id}`,+ })+ return {+ token,+ email: user.email,+ personalOrgId: personal.id,+ personalOrgSlug: personal.slug,+ inboxId: goals.find((goal) => goal.isInbox)!.id,+ }+}++async function loginByPassword(user: InboxE2eCredentials): Promise<string> {+ const response = await api.post(`${API_URL}/module/auth/login`, {+ form: { login: user.login, password: user.password },+ })+ expect(response.status()).toBe(200)+ return (await response.json()).access+}++async function loginAsOwner(page: Page) {+ await page.goto('/')+ await setEnglishLocale(page)+ await page.reload()+ await page.getByRole('tab', { name: /password/i }).click()+ await page.getByTestId('login-input').fill(INBOX_OWNER.login)+ await page.getByTestId('password-input').fill(INBOX_OWNER.password)+ await page.getByTestId('sign-in-button').click()+ await expect(page.getByTestId('sidebar-inbox-link')).toBeVisible({ timeout: 10000 })+}++async function openWorkspace(args: InboxE2eOpenWorkspaceArgs) {+ await args.page.goto(`/${args.slug}`)+ await expect(args.page.getByTestId('sidebar-inbox-link')).toBeVisible({ timeout: 10000 })+}++function sidebarInboxLink(page: Page) {+ return page.getByTestId('sidebar-inbox-link').locator('xpath=ancestor::*[.//a][1]//a/span')+}++async function openProjectPicker(page: Page) {+ await page.getByTestId('project-select-trigger').click()+}++test.describe('Sidebar Inbox', () => {+ test.beforeAll(async () => {+ api = await pwRequest.newContext()+ me = await accountFor(await loginByPassword(INBOX_OWNER))+ colleague = await accountFor(await loginByPassword(INBOX_COLLEAGUE))+ await apiSend({ method: 'post', token: colleague.token, path: '/module/collaboration', data: { goalId: colleague.inboxId, email: me.email } })+ })++ test.afterAll(async () => {+ await apiSend({+ method: 'delete',+ token: colleague.token,+ path: '/module/organizations/members',+ data: { organizationId: colleague.personalOrgId, email: me.email },+ }).catch(() => {})+ await api.dispose()+ })++ test.beforeEach(async ({ page }) => {+ await loginAsOwner(page)+ })++ test('opens your own Inbox from your personal workspace', async ({ page }) => {+ await openWorkspace({ page, slug: me.personalOrgSlug })++ await sidebarInboxLink(page).click()++ await expect(page).toHaveURL(`/${me.personalOrgSlug}/${me.inboxId}/${ALL_TASKS_LIST_ID}`)+ })++ test('opens your own Inbox from a colleague\'s personal workspace that shares their Inbox', async ({ page }) => {+ await openWorkspace({ page, slug: colleague.personalOrgSlug })++ await sidebarInboxLink(page).click()++ await expect(page).toHaveURL(`/${me.personalOrgSlug}/${me.inboxId}/${ALL_TASKS_LIST_ID}`)+ })++ test('lists a colleague\'s shared Inbox as an ordinary project of their workspace', async ({ page }) => {+ await openWorkspace({ page, slug: colleague.personalOrgSlug })+ await openProjectPicker(page)++ await page.getByTestId('project-option-Inbox').click()++ await expect(page).toHaveURL(`/${colleague.personalOrgSlug}/${colleague.inboxId}/${ALL_TASKS_LIST_ID}`)+ })++ test('keeps your own Inbox out of the project list', async ({ page }) => {+ await openWorkspace({ page, slug: me.personalOrgSlug })+ await openProjectPicker(page)++ await expect(page.getByTestId('project-option-Inbox')).toHaveCount(0)+ })+})diff --git a/web/e2e/inbox.spec.types.ts b/web/e2e/inbox.spec.types.tsnew file mode 100644index 0000000..38a3572--- /dev/null+++ b/web/e2e/inbox.spec.types.ts@@ -0,0 +1,46 @@+import type { Page } from '@playwright/test'++export type InboxE2eAccount = {+ token: string+ email: string+ personalOrgId: number+ personalOrgSlug: string+ inboxId: number+}++export type InboxE2eCredentials = {+ login: string+ password: string+}++export type InboxE2eJwtUser = {+ id: number+ email: string+}++export type InboxE2eOrganization = {+ id: number+ slug: string+ ownerId: number+ isPersonal: number+}++export type InboxE2eGoal = {+ id: number+ isInbox: boolean+}++export type InboxE2eApiGetArgs = {+ token: string+ path: string+}++export type InboxE2eApiSendArgs = InboxE2eApiGetArgs & {+ method: 'post' | 'delete'+ data: unknown+}++export type InboxE2eOpenWorkspaceArgs = {+ page: Page+ slug: string+}diff --git a/web/src/App.vue b/web/src/App.vueindex bd79a9d..380eecc 100644--- a/web/src/App.vue+++ b/web/src/App.vue@@ -6,4 +6,7 @@<script setup lang="ts">import { RouterView } from 'vue-router'+import { useThemeColorsSync } from '@/composables/useThemeColors'++useThemeColorsSync()</script>diff --git a/web/src/assets/css/main.css b/web/src/assets/css/main.cssindex 3034ab1..a51775b 100644--- a/web/src/assets/css/main.css+++ b/web/src/assets/css/main.css@@ -2,6 +2,8 @@@import "@nuxt/ui";+@import "./theme-palettes.css";+@source "../../";@source "../../../vite.ui.options.ts";diff --git a/web/src/assets/css/theme-palettes.css b/web/src/assets/css/theme-palettes.cssnew file mode 100644index 0000000..892abfb--- /dev/null+++ b/web/src/assets/css/theme-palettes.css@@ -0,0 +1,69 @@+/* Tinted neutrals for the theme picker: gray scales carrying a low-chroma hue, so backgrounds follow the theme. */+@theme static {+ --color-moss-50: oklch(0.985 0.006 155);+ --color-moss-100: oklch(0.967 0.01 155);+ --color-moss-200: oklch(0.925 0.016 155);+ --color-moss-300: oklch(0.87 0.024 155);+ --color-moss-400: oklch(0.71 0.04 155);+ --color-moss-500: oklch(0.56 0.045 155);+ --color-moss-600: oklch(0.45 0.048 155);+ --color-moss-700: oklch(0.38 0.046 155);+ --color-moss-800: oklch(0.325 0.038 155);+ --color-moss-900: oklch(0.269 0.027 155);+ --color-moss-950: oklch(0.2 0.02 155);+ --color-tide-50: oklch(0.985 0.006 195);+ --color-tide-100: oklch(0.967 0.01 195);+ --color-tide-200: oklch(0.925 0.016 195);+ --color-tide-300: oklch(0.87 0.024 195);+ --color-tide-400: oklch(0.71 0.04 195);+ --color-tide-500: oklch(0.56 0.045 195);+ --color-tide-600: oklch(0.45 0.048 195);+ --color-tide-700: oklch(0.38 0.046 195);+ --color-tide-800: oklch(0.325 0.038 195);+ --color-tide-900: oklch(0.269 0.027 195);+ --color-tide-950: oklch(0.2 0.02 195);+ --color-ink-50: oklch(0.985 0.006 255);+ --color-ink-100: oklch(0.967 0.01 255);+ --color-ink-200: oklch(0.925 0.016 255);+ --color-ink-300: oklch(0.87 0.024 255);+ --color-ink-400: oklch(0.71 0.04 255);+ --color-ink-500: oklch(0.56 0.045 255);+ --color-ink-600: oklch(0.45 0.048 255);+ --color-ink-700: oklch(0.38 0.046 255);+ --color-ink-800: oklch(0.325 0.038 255);+ --color-ink-900: oklch(0.269 0.027 255);+ --color-ink-950: oklch(0.2 0.02 255);+ --color-plum-50: oklch(0.985 0.006 300);+ --color-plum-100: oklch(0.967 0.01 300);+ --color-plum-200: oklch(0.925 0.016 300);+ --color-plum-300: oklch(0.87 0.024 300);+ --color-plum-400: oklch(0.71 0.04 300);+ --color-plum-500: oklch(0.56 0.045 300);+ --color-plum-600: oklch(0.45 0.048 300);+ --color-plum-700: oklch(0.38 0.046 300);+ --color-plum-800: oklch(0.325 0.038 300);+ --color-plum-900: oklch(0.269 0.027 300);+ --color-plum-950: oklch(0.2 0.02 300);+ --color-wine-50: oklch(0.985 0.006 10);+ --color-wine-100: oklch(0.967 0.01 10);+ --color-wine-200: oklch(0.925 0.016 10);+ --color-wine-300: oklch(0.87 0.024 10);+ --color-wine-400: oklch(0.71 0.04 10);+ --color-wine-500: oklch(0.56 0.045 10);+ --color-wine-600: oklch(0.45 0.048 10);+ --color-wine-700: oklch(0.38 0.046 10);+ --color-wine-800: oklch(0.325 0.038 10);+ --color-wine-900: oklch(0.269 0.027 10);+ --color-wine-950: oklch(0.2 0.02 10);+ --color-sand-50: oklch(0.985 0.006 70);+ --color-sand-100: oklch(0.967 0.01 70);+ --color-sand-200: oklch(0.925 0.016 70);+ --color-sand-300: oklch(0.87 0.024 70);+ --color-sand-400: oklch(0.71 0.04 70);+ --color-sand-500: oklch(0.56 0.045 70);+ --color-sand-600: oklch(0.45 0.048 70);+ --color-sand-700: oklch(0.38 0.046 70);+ --color-sand-800: oklch(0.325 0.038 70);+ --color-sand-900: oklch(0.269 0.027 70);+ --color-sand-950: oklch(0.2 0.02 70);+}diff --git a/web/src/components/features/account/AccountSettings.vue b/web/src/components/features/account/AccountSettings.vueindex 8b32c54..734db7c 100644--- a/web/src/components/features/account/AccountSettings.vue+++ b/web/src/components/features/account/AccountSettings.vue@@ -51,12 +51,18 @@{{ userStore.email }}</div>- <div>+ <div v-if="deletionAllowed"><DeleteAccountButton@code-sent="showCodeModal = true"@error="onCodeSendError"/></div>+ <p+ v-else-if="deletionAllowed === false"+ class="text-sm text-muted"+ >+ {{ t('account.deletionDisabled') }}+ </p></div></UPageCard>@@ -65,8 +71,10 @@</template><script setup lang="ts">-import { computed, ref } from 'vue'+import { computed, onMounted, ref } from 'vue'import { useI18n } from 'vue-i18n'+import $api from '@/helpers/axios'+import { logError } from '@/helpers/Helper'import { useUserStore } from '@/stores/user.store'import DeleteAccountButton from './parts/DeleteAccountButton.vue'import DeleteAccountCodeModal from './parts/DeleteAccountCodeModal.vue'@@ -82,6 +90,15 @@ const userStore = useUserStore()const toast = useToast()const showCodeModal = ref(false)+// null until the server answers, so the button does not flash on servers where deletion is off+const deletionAllowed = ref<boolean | null>(null)++onMounted(async () => {+ const result = await $api+ .get<{ allowed: boolean }>('/module/auth/delete/account/options')+ .catch(logError)+ if (result) deletionAllowed.value = result.data.allowed+})// Seeded default user on self-hosted installs (migration 0.0.0); backend enforces the same checkconst isDefaultUser = computed(() => userStore.email.toLowerCase() === '[email protected]')diff --git a/web/src/components/features/account/parts/DeleteAccountCodeModal.vue b/web/src/components/features/account/parts/DeleteAccountCodeModal.vueindex e8e1c7c..6379d6c 100644--- a/web/src/components/features/account/parts/DeleteAccountCodeModal.vue+++ b/web/src/components/features/account/parts/DeleteAccountCodeModal.vue@@ -55,16 +55,22 @@ const code = ref('')async function handleConfirm() {const result = await $api- .post<AppResponse<{ del: boolean }>>('/module/auth/delete/account', { code: code.value })+ .post<AppResponse<{ del: boolean }>>('/module/auth/delete/account', { code: code.value.trim() }).catch((err) => console.log(err))- if (result && result.data.response.del) {+ if (!result?.data?.response?.del) {toast.add({- title: t('account.deleted'),- color: 'success',+ title: t('account.deleteCodeInvalid'),+ color: 'error',})- $ls.invalidateTokens()- router.push('/')+ return}++ toast.add({+ title: t('account.deleted'),+ color: 'success',+ })+ $ls.invalidateTokens()+ router.push('/')}</script>diff --git a/web/src/components/features/auth/LoginForm.vue b/web/src/components/features/auth/LoginForm.vueindex 8a2b530..de52384 100644--- a/web/src/components/features/auth/LoginForm.vue+++ b/web/src/components/features/auth/LoginForm.vue@@ -134,6 +134,7 @@<script setup lang="ts">import { ref, computed, reactive, onMounted, watch } from 'vue'import { useI18n } from 'vue-i18n'+import { useRoute } from 'vue-router'import $api from '@/helpers/axios'import { logError } from '@/helpers/Helper'import { getConfiguredApiUrl } from '@/helpers/serverConfig'@@ -160,7 +161,10 @@ type LoginOptions = {publicRegistration: boolean}-const currentView = ref<View>('code')+const route = useRoute()++// /login?view=forgot opens the password recovery form, e.g. from an expired reset link+const currentView = ref<View>(route.query.view === 'forgot' ? 'forgot' : 'code')const isLoadingOptions = ref(true)const isServerLocked = getConfiguredApiUrl() !== nulldiff --git a/web/src/components/features/auth/ResetPassword.vue b/web/src/components/features/auth/ResetPassword.vueindex 02ca090..14bf068 100644--- a/web/src/components/features/auth/ResetPassword.vue+++ b/web/src/components/features/auth/ResetPassword.vue@@ -26,32 +26,8 @@</div></template>- <!-- Error state - invalid reset link -->- <template v-else-if="!isValidLink">- <div class="text-center space-y-4">- <div class="mx-auto w-12 h-12 rounded-full bg-error/10 flex items-center justify-center">- <UIcon- name="i-lucide-alert-circle"- class="w-6 h-6 text-error"- />- </div>- <div>- <h3 class="font-medium">- {{ t('auth.invalidResetLink') }}- </h3>- <p class="text-sm text-muted mt-1">- {{ t('auth.invalidResetLinkDescription') }}- </p>- </div>- <UButton- :label="t('auth.backToLogin')"- variant="outline"- color="neutral"- block- @click="goToLogin"- />- </div>- </template>+ <!-- Error state - invalid, used or expired reset link -->+ <ResetPasswordInvalidLink v-else-if="!isValidLink || isLinkRejected" /><!-- Form --><template v-else>@@ -146,6 +122,7 @@ import { ref, reactive, computed } from 'vue'import { useI18n } from 'vue-i18n'import { useRoute, useRouter } from 'vue-router'import $api from '@/helpers/axios'+import ResetPasswordInvalidLink from './parts/ResetPasswordInvalidLink.vue'const { t } = useI18n()const route = useRoute()@@ -155,6 +132,7 @@ const toast = useToast()const isLoading = ref(false)const isReset = ref(false)+const isLinkRejected = ref(false)const showPassword = ref(false)const showPasswordRepeat = ref(false)@@ -214,7 +192,12 @@ async function onSubmit() {color: 'error',})}- } catch {+ } catch (error: unknown) {+ const reason = (error as { response?: { data?: { reason?: string } } }).response?.data?.reason+ if (reason === 'invalid_or_expired_code') {+ isLinkRejected.value = true+ return+ }toast.add({title: t('auth.error'),description: t('auth.canNotResetPassword'),diff --git a/web/src/components/features/auth/parts/ResetPasswordInvalidLink.vue b/web/src/components/features/auth/parts/ResetPasswordInvalidLink.vuenew file mode 100644index 0000000..d4e63ab--- /dev/null+++ b/web/src/components/features/auth/parts/ResetPasswordInvalidLink.vue@@ -0,0 +1,47 @@+<template>+ <div class="text-center space-y-4">+ <div class="mx-auto w-12 h-12 rounded-full bg-error/10 flex items-center justify-center">+ <UIcon+ name="i-lucide-alert-circle"+ class="w-6 h-6 text-error"+ />+ </div>+ <div>+ <h3 class="font-medium">+ {{ t('auth.invalidResetLink') }}+ </h3>+ <p class="text-sm text-muted mt-1">+ {{ t('auth.invalidResetLinkDescription') }}+ </p>+ </div>+ <UButton+ :label="t('auth.requestNewResetLink')"+ color="primary"+ block+ @click="requestNewLink"+ />+ <UButton+ :label="t('auth.backToLogin')"+ variant="outline"+ color="neutral"+ block+ @click="goToLogin"+ />+ </div>+</template>++<script setup lang="ts">+import { useI18n } from 'vue-i18n'+import { useRouter } from 'vue-router'++const { t } = useI18n()+const router = useRouter()++function requestNewLink() {+ router.push({ path: '/login', query: { view: 'forgot' } })+}++function goToLogin() {+ router.push('/')+}+</script>diff --git a/web/src/components/features/base/TvContextMenu.types.ts b/web/src/components/features/base/TvContextMenu.types.tsnew file mode 100644index 0000000..f3724a8--- /dev/null+++ b/web/src/components/features/base/TvContextMenu.types.ts@@ -0,0 +1,4 @@+export type TvContextMenuPoint = {+ x: number+ y: number+}diff --git a/web/src/components/features/base/TvContextMenu.vue b/web/src/components/features/base/TvContextMenu.vueindex 515f0af..33a376d 100644--- a/web/src/components/features/base/TvContextMenu.vue+++ b/web/src/components/features/base/TvContextMenu.vue@@ -17,6 +17,7 @@<script setup lang="ts">import { ref, computed, onMounted, onUnmounted } from 'vue'+import type { TvContextMenuPoint } from './TvContextMenu.types'const isOpen = defineModel<boolean>('open', { default: false })@@ -53,12 +54,18 @@ function openAt(event: MouseEvent) {isOpen.value = true}+function openAtPoint(point: TvContextMenuPoint) {+ anchorPosition.value = { ...point }+ isOpen.value = true+}+function close() {isOpen.value = false}defineExpose({openAt,+ openAtPoint,close,})</script>diff --git a/web/src/components/features/graph/ProjectGraph.vue b/web/src/components/features/graph/ProjectGraph.vueindex 803b0c4..4740269 100644--- a/web/src/components/features/graph/ProjectGraph.vue+++ b/web/src/components/features/graph/ProjectGraph.vue@@ -99,7 +99,8 @@ import type { GraphDirection } from '@/types/graph.types'import { useGoalPermissions } from '@/composables/useGoalPermissions'import { useAppRouteInfo } from '@/composables/useAppRouteInfo'import AddNewTaskToGraph from './AddNewTaskToGraph.vue'-import { layoutCenter, useLayout } from './composables/useLayout'+import { estimateNodeSize, layoutCenter, placeNodeInFreeSpot, useLayout } from './composables/useLayout'+import { provideGraphViewportCenter } from './composables/useGraphViewportCenter'import TaskNode from './TaskNode.vue'const listIds = defineModel<number[]>('listIds', { default: () => [] })@@ -141,8 +142,20 @@ const {onNodeDragStop,removeEdges,screenToFlowCoordinate,+ viewport,+ dimensions,} = useVueFlow()+// Where a new node goes: the middle of what is on screen, or the nearest free spot to it+provideGraphViewportCenter(() => {+ const { width, height } = estimateNodeSize({ data: {} })+ const target = {+ x: Math.round((dimensions.value.width / 2 - viewport.value.x) / viewport.value.zoom - width / 2),+ y: Math.round((dimensions.value.height / 2 - viewport.value.y) / viewport.value.zoom - height / 2),+ }+ return placeNodeInFreeSpot({ target, node: { data: {} }, obstacles: store.nodes })+})+const { projectId } = useAppRouteInfo()const { layout } = useLayout()const store = useGraphStore()diff --git a/web/src/components/features/graph/composables/useGraphViewportCenter.ts b/web/src/components/features/graph/composables/useGraphViewportCenter.tsnew file mode 100644index 0000000..1147fb2--- /dev/null+++ b/web/src/components/features/graph/composables/useGraphViewportCenter.ts@@ -0,0 +1,20 @@+import { onBeforeUnmount } from 'vue'+import type { XYPosition } from '@vue-flow/core'++type CenterProvider = () => XYPosition+++let provider: CenterProvider | null = null++/** Registers the mounted graph as the source of the visible center. */+export function provideGraphViewportCenter(centerProvider: CenterProvider) {+ provider = centerProvider+ onBeforeUnmount(() => {+ if (provider === centerProvider) provider = null+ })+}++/** Where a new node lands in the visible part of the graph, or null when no graph is on screen. */+export function graphViewportCenter(): XYPosition | null {+ return provider?.() ?? null+}diff --git a/web/src/components/features/graph/composables/useLayout.ts b/web/src/components/features/graph/composables/useLayout.tsindex c4f86b9..863e952 100644--- a/web/src/components/features/graph/composables/useLayout.ts+++ b/web/src/components/features/graph/composables/useLayout.ts@@ -1,6 +1,6 @@import dagre from '@dagrejs/dagre'import { type Edge, type GraphNode, type Node, Position, type XYPosition } from '@vue-flow/core'-import type { GraphPlaceNodeNearArgs } from '@/types/graph.types'+import type { GraphPlaceNodeFreeArgs, GraphPlaceNodeNearArgs } from '@/types/graph.types'import { useUiPreferencesStore } from '@/stores/uiPreferences.store'const NODE_WIDTH = 288 // w-72 wrapper in TaskNode@@ -139,6 +139,38 @@ export function placeNodeNear({ anchor, node, side, direction, obstacles }: Grapreturn origin}+/**+ * The free spot nearest to the wanted one: kept as is when nothing is there, otherwise moved+ * flush against a side of a node in the way, keeping NODE_SEP from every node.+ */+export function placeNodeInFreeSpot({ target, node, obstacles }: GraphPlaceNodeFreeArgs): XYPosition {+ const size = estimateNodeSize(node)+ const rects = obstacles.map((item) => ({ ...item.position, ...nodeSize(item) }))+ const isFree = (position: XYPosition) =>+ rects.every(+ (rect) =>+ position.x + size.width + NODE_SEP <= rect.x ||+ rect.x + rect.width + NODE_SEP <= position.x ||+ position.y + size.height + NODE_SEP <= rect.y ||+ rect.y + rect.height + NODE_SEP <= position.y,+ )+ if (isFree(target)) return target++ // Slide along one axis at a time, like placeNodeNear, and keep the closest result+ const candidates: XYPosition[] = []+ for (const rect of rects) {+ candidates.push(+ { x: target.x, y: rect.y - NODE_SEP - size.height },+ { x: target.x, y: rect.y + rect.height + NODE_SEP },+ { x: rect.x - NODE_SEP - size.width, y: target.y },+ { x: rect.x + rect.width + NODE_SEP, y: target.y },+ )+ }+ const distance = (position: XYPosition) => Math.hypot(position.x - target.x, position.y - target.y)+ candidates.sort((a, b) => distance(a) - distance(b))+ return candidates.find(isFree) ?? target+}+/*** Composable to run the layout algorithm on the graph.* Connected nodes are laid out with `dagre`; isolated nodes (no edges) arediff --git a/web/src/components/features/kanban/KanbanBoard.vue b/web/src/components/features/kanban/KanbanBoard.vueindex acb5e33..35c658a 100644--- a/web/src/components/features/kanban/KanbanBoard.vue+++ b/web/src/components/features/kanban/KanbanBoard.vue@@ -8,69 +8,75 @@@pointerdown="pointerDownHandler"@touchend="boardStopScrolling">- <div- v-for="status in kanbanStore.statuses"- :key="status.id"- :data-testid="`kanban-column-${t(status.name)}`"- class="h-full max-w-[340px] min-w-[272px] shadow-lg gap-2 flex flex-col w-[91.666667%] rounded-lg"+ <TransitionGroup+ tag="div"+ class="contents"+ move-class="motion-safe:transition-transform motion-safe:duration-300 motion-safe:ease-out">- <div class="bg-elevated rounded-lg p-2 px-3 flex items-center text-base h-10 rounded-b-none">- <span class="grow truncate">- {{ t(status.name) }}- </span>- <KanbanTitleMenu- v-if="status.id !== DEFAULT_ID"- :status="status"+ <div+ v-for="status in kanbanStore.statuses"+ :key="status.id"+ :data-testid="`kanban-column-${t(status.name)}`"+ class="h-full max-w-[340px] min-w-[272px] shadow-lg gap-2 flex flex-col w-[91.666667%] rounded-lg"+ >+ <div class="bg-elevated rounded-lg p-2 px-3 flex items-center text-base h-10 rounded-b-none">+ <span class="grow truncate">+ {{ t(status.name) }}+ </span>+ <KanbanTitleMenu+ v-if="status.id !== DEFAULT_ID"+ :status="status"+ />+ </div>++ <KanbanAddTask+ v-if="canAddTask"+ :goal-id="kanbanStore.goalId"+ :status-id="status.id"+ class="mx-1"/>- </div>- <KanbanAddTask- v-if="canAddTask"- :goal-id="kanbanStore.goalId"- :status-id="status.id"- class="mx-1"- />-- <draggable- v-bind="sortableOptions"- :list="kanbanStore.tasksData[status.id]?.tasks"- :data-column-id="status.id"- :animation="150"- class="flex gap-2 p-2 h-full flex-col overflow-auto overflow-x-hidden"- item-key="id"- group="kanban-tasks"- @start="startHandler"- @end="onDragEnd"- @clone="onClone"- >- <template #item="{ element }">- <div- :data-order="element.kanbanOrder"- :data-task-id="element.id"- data-testid="kanban-task-card"- >- <TaskItem- :task="element"- :ui="{ additionalInfo: 'flex-col items-stretch flex-nowrap' }"- @toggle="updateTaskChecked"- />- </div>- </template>-- <template #footer>- <UButton- v-if="kanbanStore.tasksData[status.id]?.nextCursor !== null"- icon="i-lucide-circle-arrow-down"- variant="soft"- color="info"- class="w-full mt-2"- @click="loadMoreTasks(status.id)"- >- {{ t('kanban.loadMore') }}- </UButton>- </template>- </draggable>- </div>+ <draggable+ v-bind="sortableOptions"+ :list="kanbanStore.tasksData[status.id]?.tasks"+ :data-column-id="status.id"+ :animation="150"+ class="flex gap-2 p-2 h-full flex-col overflow-auto overflow-x-hidden"+ item-key="id"+ group="kanban-tasks"+ @start="startHandler"+ @end="onDragEnd"+ @clone="onClone"+ >+ <template #item="{ element }">+ <div+ :data-order="element.kanbanOrder"+ :data-task-id="element.id"+ data-testid="kanban-task-card"+ >+ <TaskItem+ :task="element"+ :ui="{ additionalInfo: 'flex-col items-stretch flex-nowrap' }"+ @toggle="updateTaskChecked"+ />+ </div>+ </template>++ <template #footer>+ <UButton+ v-if="kanbanStore.tasksData[status.id]?.nextCursor !== null"+ icon="i-lucide-circle-arrow-down"+ variant="soft"+ color="info"+ class="w-full mt-2"+ @click="loadMoreTasks(status.id)"+ >+ {{ t('kanban.loadMore') }}+ </UButton>+ </template>+ </draggable>+ </div>+ </TransitionGroup><KanbanAddStatus :goal-id="kanbanStore.goalId" /></div>diff --git a/web/src/components/features/kanban/parts/KanbanTitleMenu.vue b/web/src/components/features/kanban/parts/KanbanTitleMenu.vueindex b99bf75..9b14868 100644--- a/web/src/components/features/kanban/parts/KanbanTitleMenu.vue+++ b/web/src/components/features/kanban/parts/KanbanTitleMenu.vue@@ -31,10 +31,27 @@ import type { KanbanColumnItem } from 'taskview-api'import type { DropdownMenuItem } from '@nuxt/ui'import KanbanEditModal from './KanbanEditModal.vue'import KanbanDeleteModal from './KanbanDeleteModal.vue'+import { useKanbanStore } from '@/stores/kanban.store'+import { useGoalPermissions } from '@/composables/useGoalPermissions'+import { DEFAULT_ID } from '@/types/app.types'+import type { KanbanMoveStatusArgs } from '@/types/kanban.types'const props = defineProps<{ status: KanbanColumnItem }>()const { t } = useI18n()+const toast = useToast()+const kanbanStore = useKanbanStore()+const { canManageKanban } = useGoalPermissions()++const columnIds = computed(() => kanbanStore.statuses.filter((stat) => stat.id !== DEFAULT_ID).map((stat) => stat.id))+const position = computed(() => columnIds.value.indexOf(props.status.id))++async function move(direction: KanbanMoveStatusArgs['direction']) {+ const moved = await kanbanStore.moveStatus({ statusId: props.status.id, direction })+ if (!moved) {+ toast.add({ title: t('kanban.moveFailed'), color: 'error' })+ }+}const editOpen = ref(false)const deleteOpen = ref(false)@@ -43,7 +60,27 @@ const ui = {itemLeadingIcon: 'size-4',item: 'items-center',} as DropdownMenuItem['ui']+const moveItems = computed<DropdownMenuItem[]>(() => [+ {+ label: t('kanban.moveLeft'),+ icon: 'i-lucide-arrow-left',+ ui,+ disabled: position.value <= 0,+ 'data-testid': 'kanban-menu-move-left',+ onSelect: () => move('left'),+ },+ {+ label: t('kanban.moveRight'),+ icon: 'i-lucide-arrow-right',+ ui,+ disabled: position.value === -1 || position.value >= columnIds.value.length - 1,+ 'data-testid': 'kanban-menu-move-right',+ onSelect: () => move('right'),+ },+])+const menuItems = computed<DropdownMenuItem[][]>(() => [+ ...(canManageKanban.value ? [moveItems.value] : []),[{label: t('kanban.edit'),diff --git a/web/src/components/features/main/screen-main/DashboardList/parts/DashboardAddTask.vue b/web/src/components/features/main/screen-main/DashboardList/parts/DashboardAddTask.vueindex 8505dc0..f87a541 100644--- a/web/src/components/features/main/screen-main/DashboardList/parts/DashboardAddTask.vue+++ b/web/src/components/features/main/screen-main/DashboardList/parts/DashboardAddTask.vue@@ -7,34 +7,40 @@:no-dates="noDates"><template #activator="props">- <UButton- v-if="compact"- v-bind="props"- icon="i-lucide-plus"- color="neutral"- variant="soft"- size="sm"- :disabled="disabled"- :ui="{ base: 'rounded-full hover:bg-primary/10 hover:text-primary' }"- data-testid="dashboard-add-task"- @click.stop- />- <button- v-else- v-bind="props"- type="button"- :disabled="disabled"- data-testid="dashboard-add-task"- class="flex items-center gap-2.5 w-full px-4 py-3 rounded-2xl border border-dashed border-default text-muted hover:text-primary hover:border-primary hover:bg-primary/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"+ <UTooltip+ :text="t(SHORTCUTS.addTask.labelKey)"+ :kbds="SHORTCUTS.addTask.kbds"+ :disabled="!shortcutsEnabled">- <span class="flex items-center justify-center size-6 rounded-full border border-dashed border-current shrink-0">- <UIcon- name="i-lucide-plus"- class="size-3.5"- />- </span>- <span class="text-[15px]">{{ t('msg.addTask') }}</span>- </button>+ <UButton+ v-if="compact"+ v-bind="props"+ icon="i-lucide-plus"+ color="neutral"+ variant="soft"+ size="sm"+ :disabled="disabled"+ :ui="{ base: 'rounded-full hover:bg-primary/10 hover:text-primary' }"+ data-testid="dashboard-add-task"+ @click.stop+ />+ <button+ v-else+ v-bind="props"+ type="button"+ :disabled="disabled"+ data-testid="dashboard-add-task"+ class="flex items-center gap-2.5 w-full px-4 py-3 rounded-2xl border border-dashed border-default text-muted hover:text-primary hover:border-primary hover:bg-primary/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"+ >+ <span class="flex items-center justify-center size-6 rounded-full border border-dashed border-current shrink-0">+ <UIcon+ name="i-lucide-plus"+ class="size-3.5"+ />+ </span>+ <span class="text-[15px]">{{ t('msg.addTask') }}</span>+ </button>+ </UTooltip></template></MainScreenAddTaskDialog></template>@@ -43,6 +49,8 @@import { ref } from 'vue'import { useI18n } from 'vue-i18n'import MainScreenAddTaskDialog from '@/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue'+import { SHORTCUTS } from '@/shortcuts/registry'+import { useShortcutsEnabled } from '@/shortcuts/useShortcutsEnabled'defineProps<{title: string@@ -54,4 +62,5 @@ defineProps<{const { t } = useI18n()const open = ref(false)+const shortcutsEnabled = useShortcutsEnabled()</script>diff --git a/web/src/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue b/web/src/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vueindex 531edd0..481f88b 100644--- a/web/src/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue+++ b/web/src/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue@@ -1,7 +1,8 @@<template>- <UModal- v-model:open="model"+ <UModal+ v-model:open="model":fullscreen="isMobile"+ :content="{ onOpenAutoFocus: focusDescription }"><template #header><div class="flex items-center justify-between w-full">@@ -22,6 +23,7 @@<div class="flex flex-col gap-4"><UFormField :label="t('tasks.description')"><UInput+ ref="descriptionInput"v-model="taskDescription":placeholder="t('tasks.addPlaceholder')"class="w-full"@@ -101,11 +103,15 @@</template><script setup lang="ts">-import { computed, ref, watch } from 'vue'+import { computed, ref, useTemplateRef, watch } from 'vue'import { useI18n } from 'vue-i18n'import { CalendarDate } from '@internationalized/date'import { useGoalsStore } from '@/stores/goals.store'import { useBaseScreenStore } from '@/stores/base-screen.store'+import { useTasksStore } from '@/stores/tasks.store'+import { useKanbanStore } from '@/stores/kanban.store'+import { useGraphStore } from '@/stores/graph.store'+import { graphViewportCenter } from '@/components/features/graph/composables/useGraphViewportCenter'import { $ls, $tvApi } from '@/plugins/axios'import { useTaskView } from '@/composables/useTaskView'import { useInbox } from '@/composables/useInbox'@@ -121,12 +127,21 @@ const props = withDefaults(defineProps<{upcomingTask?: booleannoDates?: booleantaskName?: string+ /** preselected instead of the last chosen project, e.g. the project on screen */+ defaultGoalId?: number+ /** list the task goes to while the default project stays selected */+ defaultListId?: number+ /** show the deadline field but leave it empty */+ emptyDeadline?: boolean}>(), {title: '',disabled: false,upcomingTask: false,noDates: false,taskName: '',+ defaultGoalId: undefined,+ defaultListId: undefined,+ emptyDeadline: false,})const emit = defineEmits<{@@ -139,8 +154,22 @@ const model = defineModel<boolean>({ default: false })const { t } = useI18n()const goalsStore = useGoalsStore()const baseScreenStore = useBaseScreenStore()+const tasksStore = useTasksStore()+const kanbanStore = useKanbanStore()+const graphStore = useGraphStore()const { isMobile } = useTaskView()-const { inbox } = useInbox()+const { inbox, isOwnInbox } = useInbox()++const descriptionInput = useTemplateRef('descriptionInput')++// The dialog would focus its close button first; typing should go straight into the title.+// On a phone this would pop the keyboard over the form, so the default stays there+function focusDescription(event: Event) {+ const input = descriptionInput.value?.inputRef+ if (!input || isMobile.value) return+ event.preventDefault()+ input.focus()+}const taskDescription = ref(props.taskName)const selectedGoalId = ref<number | undefined>(undefined)@@ -154,7 +183,7 @@ watch(() => props.taskName, (newVal) => {watch(model, async (isOpen) => {if (isOpen) {// Set default deadline based on widget type- if (!props.noDates) {+ if (!props.noDates && !props.emptyDeadline) {const today = new Date()if (props.upcomingTask) {today.setDate(today.getDate() + 1)@@ -166,6 +195,14 @@ watch(model, async (isOpen) => {)}+ const defaultGoal = props.defaultGoalId+ ? goalsStore.goals.find(g => !g.archive && g.id === props.defaultGoalId)+ : undefined+ if (defaultGoal) {+ selectedGoalId.value = defaultGoal.id+ return+ }+// Use the last chosen project (it may be the Inbox); otherwise default to the// Inbox — that's exactly what it's for.const saved = await $ls.getValue(LAST_SELECTED_PROJECT_KEY)@@ -184,7 +221,7 @@ watch(model, async (isOpen) => {const goalOptions = computed(() => {const active = goalsStore.goals.filter(g => !g.archive)const options = active- .filter(g => !g.isInbox)+ .filter(g => !isOwnInbox(g)).map(g => ({ label: g.name, value: g.id }))if (inbox.value) {options.unshift({ label: t('projects.inbox'), value: inbox.value.id })@@ -214,15 +251,24 @@ async function addTask() {? `${deadline.value.year}-${String(deadline.value.month).padStart(2, '0')}-${String(deadline.value.day).padStart(2, '0')}`: null+ // A task for the project whose graph is on screen is placed in the visible part of it+ const nodeGraphPosition = selectedGoalId.value === graphStore.goalId ? graphViewportCenter() : null+const task = await $tvApi.tasks.createTask({description: taskDescription.value.trim(),goalId: selectedGoalId.value,- goalListId: null,+ goalListId: selectedGoalId.value === props.defaultGoalId ? props.defaultListId ?? null : null,endDate,+ ...(nodeGraphPosition && { nodeGraphPosition }),})if (task) {baseScreenStore.addCreatedTask(task)+ // Show it right away in the project list, kanban or graph on screen; each skips a+ // task that does not belong to the current view or is already there+ tasksStore.applyRemoteTask({ task, created: true })+ kanbanStore.insertTask(task)+ if (nodeGraphPosition) graphStore.insertTask({ task })emit('added')close()}diff --git a/web/src/components/features/main/screen-main/parts/NoGoals.vue b/web/src/components/features/main/screen-main/parts/NoGoals.vueindex 1f5e11b..35311e9 100644--- a/web/src/components/features/main/screen-main/parts/NoGoals.vue+++ b/web/src/components/features/main/screen-main/parts/NoGoals.vue@@ -17,12 +17,14 @@import { computed } from 'vue'import ProjectAddInput from '@/components/features/projects/parts/ProjectAddInput.vue'import { useGoalsStore } from '@/stores/goals.store'+import { useInbox } from '@/composables/useInbox'import { useI18n } from 'vue-i18n'const goalsStore = useGoalsStore()+const { isOwnInbox } = useInbox()const { t } = useI18n()-const noGoals = computed(() => goalsStore.goals.filter((g) => !g.archive && !g.isInbox).length === 0)+const noGoals = computed(() => goalsStore.goals.filter((g) => !g.archive && !isOwnInbox(g)).length === 0)async function addProject(name: string) {await goalsStore.addGoal({ name })diff --git a/web/src/components/features/main/screen-main/parts/SearchAll.vue b/web/src/components/features/main/screen-main/parts/SearchAll.vueindex fce7cb8..85cdf40 100644--- a/web/src/components/features/main/screen-main/parts/SearchAll.vue+++ b/web/src/components/features/main/screen-main/parts/SearchAll.vue@@ -24,7 +24,7 @@taskId: task.id,},}"- class="flex w-full text-base px-4 py-2"+ class="flex w-full text-base text-start px-4 py-2">{{ task.description }}</ULink>diff --git a/web/src/components/features/projects/ProjectsSidebar.vue b/web/src/components/features/projects/ProjectsSidebar.vueindex 7a3e03f..03e1f9b 100644--- a/web/src/components/features/projects/ProjectsSidebar.vue+++ b/web/src/components/features/projects/ProjectsSidebar.vue@@ -26,16 +26,18 @@ import ProjectsList from '@/components/features/projects/ProjectsList.vue'import ArchiveList from '@/components/features/projects/ArchiveList.vue'import type { Project, ProjectSaveData } from '@/components/features/projects/types'import { useProjectRoute } from '@/composables/useProjectRoute'+import { useInbox } from '@/composables/useInbox'const router = useRouter()const { projectRoute } = useProjectRoute()+const { isOwnInbox } = useInbox()const goalsStore = useGoalsStore()const orgStore = useOrganizationStore()const { goals } = storeToRefs(goalsStore)-const activeProjects = computed(() => goals.value.filter(p => p.archive === 0 && !p.isInbox))-const archivedProjects = computed(() => goals.value.filter(p => p.archive === 1 && !p.isInbox))+const activeProjects = computed(() => goals.value.filter(p => p.archive === 0 && !isOwnInbox(p)))+const archivedProjects = computed(() => goals.value.filter(p => p.archive === 1 && !isOwnInbox(p)))watch(() => orgStore.currentOrg, async () => {diff --git a/web/src/components/features/projects/parts/ProjectListBase.vue b/web/src/components/features/projects/parts/ProjectListBase.vueindex a8f9b31..6d81858 100644--- a/web/src/components/features/projects/parts/ProjectListBase.vue+++ b/web/src/components/features/projects/parts/ProjectListBase.vue@@ -119,7 +119,7 @@/><!-- Webhooks --><UButton- v-if="canViewIntegrations"+ v-if="canViewWebhooks":label="t('contextMenu.webhooks')"icon="i-lucide-webhook"variant="ghost"@@ -257,6 +257,7 @@ const {canViewKanban,canViewGraph,canViewIntegrations,+ canViewWebhooks,canViewTimeTracking,canManageUsers,canEditGoal,diff --git a/web/src/components/features/settings/SettingsScreen.vue b/web/src/components/features/settings/SettingsScreen.vueindex 9113293..8ed935a 100644--- a/web/src/components/features/settings/SettingsScreen.vue+++ b/web/src/components/features/settings/SettingsScreen.vue@@ -18,6 +18,10 @@v-if="item.kind === 'nav'":item="item"/>+ <SettingsActionRow+ v-else-if="item.kind === 'action'"+ :item="item"+ /><SettingsSelectRowv-else:item="item"@@ -38,6 +42,7 @@ import { useSettingsHub } from './composables/useSettingsHub'import SettingsProfileHeader from './parts/SettingsProfileHeader.vue'import SettingsSection from './parts/SettingsSection.vue'import SettingsNavRow from './parts/SettingsNavRow.vue'+import SettingsActionRow from './parts/SettingsActionRow.vue'import SettingsSelectRow from './parts/SettingsSelectRow.vue'import SettingsVersionRow from './parts/SettingsVersionRow.vue'import SettingsLogoutRow from './parts/SettingsLogoutRow.vue'diff --git a/web/src/components/features/settings/composables/useSettingsHub.ts b/web/src/components/features/settings/composables/useSettingsHub.tsindex 2ef78b3..b8117a2 100644--- a/web/src/components/features/settings/composables/useSettingsHub.ts+++ b/web/src/components/features/settings/composables/useSettingsHub.ts@@ -8,6 +8,9 @@ import { useUserStore } from '@/stores/user.store'import { useOrganizationStore } from '@/stores/organization.store'import { useOrgSwitcher } from '@/composables/useOrgSwitcher'import { saveLocale } from '@/plugins/i18n'+import { useTaskView } from '@/composables/useTaskView'+import { SHORTCUTS } from '@/shortcuts/registry'+import { useShortcutsHelp } from '@/shortcuts/useShortcutsHelp'import type { SettingsSection } from '../types'const LANGUAGE_OPTIONS = [@@ -25,6 +28,8 @@ export function useSettingsHub() {const userStore = useUserStore()const orgStore = useOrganizationStore()const { switchOrg } = useOrgSwitcher()+ const { isDesktop } = useTaskView()+ const shortcutsHelp = useShortcutsHelp()const identity = computed(() => ({name: userStore.login || userStore.email,@@ -75,6 +80,14 @@ export function useSettingsHub() {get: () => colorMode.value,set: (value) => { colorMode.value = value as typeof colorMode.value },},+ {+ kind: 'nav',+ key: 'theme-colors',+ icon: 'i-lucide-palette',+ color: 'cyan',+ title: t('uiCustomization.theme.navTitle'),+ to: { name: 'ui-customization', query: { tab: 'theme' } },+ },{kind: 'select',key: 'language',@@ -133,7 +146,25 @@ export function useSettingsHub() {],}- return [account, appearance, layout, about]+ const shortcuts: SettingsSection = {+ key: 'shortcuts',+ title: '',+ items: [+ {+ kind: 'action',+ key: 'shortcuts',+ icon: 'i-lucide-keyboard',+ color: 'zinc',+ title: t('userMenu.shortcuts'),+ kbds: SHORTCUTS.showShortcuts.kbds,+ onSelect: shortcutsHelp.open,+ },+ ],+ }++ return isDesktop.value+ ? [account, appearance, layout, about, shortcuts]+ : [account, appearance, layout, about]})return { identity, sections }diff --git a/web/src/components/features/settings/parts/SettingsActionRow.vue b/web/src/components/features/settings/parts/SettingsActionRow.vuenew file mode 100644index 0000000..50727b1--- /dev/null+++ b/web/src/components/features/settings/parts/SettingsActionRow.vue@@ -0,0 +1,40 @@+<template>+ <button+ type="button"+ class="flex w-full items-center gap-3 px-3 py-2.5 text-start transition-colors hover:bg-elevated focus-visible:bg-elevated focus:outline-none cursor-pointer"+ :data-testid="`settings-row-${item.key}`"+ @click="item.onSelect"+ >+ <SettingsIconTile+ :icon="item.icon"+ :color="item.color"+ />+ <span class="min-w-0 flex-1 truncate text-sm font-medium text-highlighted">+ {{ item.title }}+ </span>+ <span+ v-if="item.kbds?.length"+ class="flex shrink-0 items-center gap-1"+ >+ <UKbd+ v-for="kbd in item.kbds"+ :key="kbd"+ :value="kbd"+ />+ </span>+ <UIcon+ v-else+ name="i-lucide-chevron-right"+ class="size-4 shrink-0 text-dimmed"+ />+ </button>+</template>++<script setup lang="ts">+import type { SettingsActionRowItem } from '../types'+import SettingsIconTile from './SettingsIconTile.vue'++defineProps<{+ item: SettingsActionRowItem+}>()+</script>diff --git a/web/src/components/features/settings/types.ts b/web/src/components/features/settings/types.tsindex 526b278..9293166 100644--- a/web/src/components/features/settings/types.ts+++ b/web/src/components/features/settings/types.ts@@ -37,7 +37,13 @@ export type SettingsSelectRowItem = SettingsRowBase & {set: (value: string) => void}-export type SettingsRowItem = SettingsNavRowItem | SettingsSelectRowItem+export type SettingsActionRowItem = SettingsRowBase & {+ kind: 'action'+ kbds?: string[]+ onSelect: () => void+}++export type SettingsRowItem = SettingsNavRowItem | SettingsSelectRowItem | SettingsActionRowItemexport type SettingsSection = {key: stringdiff --git a/web/src/components/features/shortcuts/AppShortcuts.vue b/web/src/components/features/shortcuts/AppShortcuts.vuenew file mode 100644index 0000000..ccebddd--- /dev/null+++ b/web/src/components/features/shortcuts/AppShortcuts.vue@@ -0,0 +1,60 @@+<template>+ <MainScreenAddTaskDialog+ v-model="addTaskOpen"+ :title="t('msg.addTask')"+ :default-goal-id="currentGoalId"+ :default-list-id="currentListId"+ empty-deadline+ />++ <ShortcutsHelpModal />+</template>++<script setup lang="ts">+import { computed, ref } from 'vue'+import { useI18n } from 'vue-i18n'+import { useRoute } from 'vue-router'+import MainScreenAddTaskDialog from '@/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue'+import ShortcutsHelpModal from './ShortcutsHelpModal.vue'+import { useTaskDetailPanel } from '@/composables/useTaskDetailPanel'+import { SHORTCUT_OPTIONS, isPlainKeyPress, openDialogCount } from '@/shortcuts/shortcut-guards'+import { SHORTCUTS, shortcutBinding } from '@/shortcuts/registry'+import { useShortcutsEnabled } from '@/shortcuts/useShortcutsEnabled'+import { useShortcutsHelp } from '@/shortcuts/useShortcutsHelp'++const { t } = useI18n()+const route = useRoute()+const { isOpen: isTaskOpen } = useTaskDetailPanel()+const enabled = useShortcutsEnabled()+const shortcutsHelp = useShortcutsHelp()++const addTaskOpen = ref(false)++const currentGoalId = computed(() => {+ const id = Number(route.params.projectId)+ return Number.isInteger(id) && id > 0 ? id : undefined+})++const currentListId = computed(() => {+ const id = Number(route.params.listId)++ return Number.isInteger(id) && id > 0 ? id : undefined+})++function canHandle(event: KeyboardEvent) {+ if (!enabled.value || !isPlainKeyPress(event)) return false+ return openDialogCount() <= (isTaskOpen.value ? 1 : 0)+}++function openAddTask(event: KeyboardEvent) {+ if (canHandle(event)) addTaskOpen.value = true+}++function openShortcutsHelp(event: KeyboardEvent) {+ if (canHandle(event)) shortcutsHelp.open()+}++defineShortcuts({ [shortcutBinding(SHORTCUTS.addTask)]: openAddTask }, SHORTCUT_OPTIONS)+// "?" is matched by the typed character: it sits on different keys in different layouts+defineShortcuts({ 'shift_?': openShortcutsHelp })+</script>diff --git a/web/src/components/features/shortcuts/ShortcutsHelpModal.vue b/web/src/components/features/shortcuts/ShortcutsHelpModal.vuenew file mode 100644index 0000000..5bc250e--- /dev/null+++ b/web/src/components/features/shortcuts/ShortcutsHelpModal.vue@@ -0,0 +1,65 @@+<template>+ <UModal+ v-model:open="shortcutsHelp.isOpen.value"+ :title="t('shortcuts.title')"+ :description="t('shortcuts.description')"+ >+ <template #body>+ <div+ class="flex flex-col gap-6"+ data-testid="shortcuts-help"+ >+ <UAlert+ v-if="!enabled"+ color="neutral"+ variant="soft"+ icon="i-lucide-keyboard-off"+ :title="t('shortcuts.turnedOff')"+ :actions="[{ label: t('shortcuts.openSettings'), color: 'neutral', variant: 'outline', onClick: openSettings }]"+ />++ <section+ v-for="scope in SHORTCUT_SCOPES"+ :key="scope"+ class="flex flex-col gap-1"+ >+ <h3 class="text-xs font-medium uppercase tracking-wide text-muted mb-1">+ {{ t(`shortcuts.scope.${scope}`) }}+ </h3>+ <div+ v-for="shortcut in shortcutsOfScope(scope)"+ :key="shortcut.labelKey"+ class="flex items-center justify-between gap-4 py-1.5"+ >+ <span class="text-sm">{{ t(shortcut.labelKey) }}</span>+ <span class="flex items-center gap-1 shrink-0">+ <UKbd+ v-for="kbd in shortcut.kbds"+ :key="kbd"+ :value="kbd"+ />+ </span>+ </div>+ </section>+ </div>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { useI18n } from 'vue-i18n'+import { useRouter } from 'vue-router'+import { SHORTCUT_SCOPES, shortcutsOfScope } from '@/shortcuts/registry'+import { useShortcutsEnabled } from '@/shortcuts/useShortcutsEnabled'+import { useShortcutsHelp } from '@/shortcuts/useShortcutsHelp'++const { t } = useI18n()+const router = useRouter()+const enabled = useShortcutsEnabled()+const shortcutsHelp = useShortcutsHelp()++function openSettings() {+ shortcutsHelp.isOpen.value = false+ router.push({ name: 'ui-customization' })+}+</script>diff --git a/web/src/components/features/tasks/TaskDetailPanel.vue b/web/src/components/features/tasks/TaskDetailPanel.vueindex 03fa2ca..9f70d73 100644--- a/web/src/components/features/tasks/TaskDetailPanel.vue+++ b/web/src/components/features/tasks/TaskDetailPanel.vue@@ -20,13 +20,19 @@><template #leading><div class="h-full">- <UCheckbox- :disabled="!canEditTaskStatus"- :model-value="!!task.complete"- class="mt-0.5"- data-testid="task-detail-complete"- @update:model-value="toggleComplete"- />+ <UTooltip+ :text="t(SHORTCUTS.toggleComplete.labelKey)"+ :kbds="SHORTCUTS.toggleComplete.kbds"+ :disabled="!shortcutsEnabled || !canEditTaskStatus"+ >+ <UCheckbox+ :disabled="!canEditTaskStatus"+ :model-value="!!task.complete"+ class="mt-0.5"+ data-testid="task-detail-complete"+ @update:model-value="toggleComplete"+ />+ </UTooltip></div></template></UTextarea>@@ -194,6 +200,9 @@ import type { StatusValue } from '@/composables/useKanbanStatusOptions'import { useGoalPermissions } from '@/composables/useGoalPermissions'import { useUiPreferences } from '@/composables/useUiPreferences'import { tasksSection } from '@/uiCustomization/sections/tasks'+import { useTaskShortcuts } from '@/shortcuts/useTaskShortcuts'+import { useShortcutsEnabled } from '@/shortcuts/useShortcutsEnabled'+import { SHORTCUTS } from '@/shortcuts/registry'const { t } = useI18n()const toast = useToast()@@ -276,6 +285,9 @@ async function toggleComplete() {}+useTaskShortcuts({ canToggleComplete: canEditTaskStatus, toggleComplete })+const shortcutsEnabled = useShortcutsEnabled()+async function updateNote(note: string) {if (!task.value) returnif (note !== task.value.note) {diff --git a/web/src/components/features/tasks/TvTaskDetailOverlay.vue b/web/src/components/features/tasks/TvTaskDetailOverlay.vueindex bc9fdb0..80fbedf 100644--- a/web/src/components/features/tasks/TvTaskDetailOverlay.vue+++ b/web/src/components/features/tasks/TvTaskDetailOverlay.vue@@ -26,9 +26,10 @@</template><template #footer><TaskDetailFooter- :can-move="canMove"- @delete="openDeleteDialog"- @move="isMoveDialogOpen = true"+ :can-move="!!task && canMove(task)"+ :can-delete="!!task && canDelete(task)"+ @delete="task && requestDelete(task)"+ @move="task && requestMove(task)"@close="closeTask"/></template>@@ -66,40 +67,26 @@</template><template #footer><TaskDetailFooter- :can-move="canMove"- @delete="openDeleteDialog"- @move="isMoveDialogOpen = true"+ :can-move="!!task && canMove(task)"+ :can-delete="!!task && canDelete(task)"+ @delete="task && requestDelete(task)"+ @move="task && requestMove(task)"@close="closeTask"/></template></UModal>-- <!-- Delete Confirmation Dialog -->- <TaskDeleteDialog- v-model:open="isDeleteDialogOpen"- :task="task"- @confirm="handleDelete"- />-- <TaskMoveDialog- v-model:open="isMoveDialogOpen"- :task="task"- @moved="handleMoved"- /></template>++ <TaskActionsHost /></template><script setup lang="ts">-import { computed, ref } from 'vue'+import { computed } from 'vue'import { storeToRefs } from 'pinia'import { useI18n } from 'vue-i18n'import TaskDetailPanel from './TaskDetailPanel.vue'-import TaskDeleteDialog from '@/components/features/tasks/parts/TaskDeleteDialog.vue'-import TaskMoveDialog from '@/components/features/tasks/parts/TaskMoveDialog.vue'import TaskDetailFooter from '@/components/features/tasks/parts/TaskDetailFooter.vue'-import { useRouter } from 'vue-router'-import { ALL_TASKS_LIST_ID, type TaskResponseMoveToProject } from 'taskview-api'-import { useOrganizationStore } from '@/stores/organization.store'+import TaskActionsHost from '@/components/features/tasks/parts/TaskActionsHost.vue'import { useTasksStore } from '@/stores/tasks.store'import { useGoalsStore } from '@/stores/goals.store'import { useAppStore } from '@/stores/app.store'@@ -109,6 +96,7 @@ import { AllGoalPermissions } from '@/types/goals.types'import { useTaskView } from '@/composables/useTaskView'import { useTaskDetailPanel } from '@/composables/useTaskDetailPanel'import { useSelectedTaskSync } from '@/composables/useSelectedTaskSync'+import { useTaskActions } from '@/composables/useTaskActions'const { t } = useI18n()const tasksStore = useTasksStore()@@ -116,7 +104,8 @@ const goalsStore = useGoalsStore()const appStore = useAppStore()const { isFullscreenModal } = useTaskView()const { isOpen, closeTask } = useTaskDetailPanel()-const { broadcastRemoval } = useSelectedTaskSync()+const { canMove, canDelete, requestMove, requestDelete } = useTaskActions()+useSelectedTaskSync()const task = computed(() => tasksStore.selectedTask ?? null)@@ -139,54 +128,5 @@ const canViewTaskDetails = computed(() =>!!taskGoal.value?.permissions[AllGoalPermissions.TASK_CAN_WATCH_DETAILS],)-const isDeleteDialogOpen = ref(false)-const isMoveDialogOpen = ref(false)-const router = useRouter()-const toast = useToast()-const organizationStore = useOrganizationStore()--// Subtasks move only together with their parent task-const canMove = computed(() => !!task.value && !task.value.parentId)const { taskDetailDisplayMode: displayMode } = storeToRefs(appStore)--function openDeleteDialog() {- isDeleteDialogOpen.value = true-}--async function handleDelete() {- if (!task.value) return- const taskId = task.value.id- const success = await tasksStore.deleteTask(taskId)- if (success) {- broadcastRemoval(taskId)- closeTask()- }-}--function handleMoved(result: TaskResponseMoveToProject) {- const project = goalsStore.goalMap.get(result.goalId)?.name ?? ''- const open = async () => {- await router.push({- name: 'user',- params: {- orgSlug: organizationStore.currentOrgSlug,- projectId: String(result.goalId),- listId: String(ALL_TASKS_LIST_ID),- taskId: String(result.taskId),- },- })- }-- isMoveDialogOpen.value = false- if (result.mode === 'move') {- tasksStore.removeTaskLocally(result.taskId)- broadcastRemoval(result.taskId)- closeTask()- }- toast.add({- title: t(result.mode === 'move' ? 'tasks.move.moved' : 'tasks.move.copied', { project }),- color: 'success',- actions: [{ label: t('tasks.move.open'), onClick: open }],- })-}</script>diff --git a/web/src/components/features/tasks/parts/TaskActionsHost.vue b/web/src/components/features/tasks/parts/TaskActionsHost.vuenew file mode 100644index 0000000..169094d--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskActionsHost.vue@@ -0,0 +1,153 @@+<template>+ <TvContextMenu ref="contextMenu">+ <div+ v-if="actionTask"+ class="p-1 flex flex-col gap-1"+ >+ <UButton+ v-if="canMove(actionTask)"+ :label="t('tasks.move.button')"+ data-testid="task-menu-move"+ icon="i-lucide-folder-input"+ variant="ghost"+ color="neutral"+ class="w-full justify-start"+ @click="handleMenuMove"+ />+ <USeparator+ v-if="canMove(actionTask) && canDelete(actionTask)"+ class="my-1"+ />+ <UButton+ v-if="canDelete(actionTask)"+ :label="t('common.delete')"+ data-testid="task-menu-delete"+ icon="i-lucide-trash-2"+ variant="ghost"+ color="error"+ class="w-full justify-start"+ @click="handleMenuDelete"+ />+ </div>+ </TvContextMenu>++ <TaskDeleteDialog+ v-if="renderDeleteDialog"+ v-model:open="isDeleteDialogOpen"+ :task="actionTask"+ @confirm="handleDelete"+ @after:leave="renderDeleteDialog = false"+ />++ <TaskMoveDialog+ v-if="renderMoveDialog"+ v-model:open="isMoveDialogOpen"+ :task="actionTask"+ @moved="handleMoved"+ @after:leave="renderMoveDialog = false"+ />+</template>++<script setup lang="ts">+import { ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { useRouter } from 'vue-router'+import { ALL_TASKS_LIST_ID, type TaskResponseMoveToProject } from 'taskview-api'+import TvContextMenu from '@/components/features/base/TvContextMenu.vue'+import TaskDeleteDialog from './TaskDeleteDialog.vue'+import TaskMoveDialog from './TaskMoveDialog.vue'+import { useTasksStore } from '@/stores/tasks.store'+import { useGoalsStore } from '@/stores/goals.store'+import { useOrganizationStore } from '@/stores/organization.store'+import { useTaskActions } from '@/composables/useTaskActions'+import { useTaskDetailPanel } from '@/composables/useTaskDetailPanel'+import { useTaskRemovalBroadcast } from '@/composables/useSelectedTaskSync'++const { t } = useI18n()+const router = useRouter()+const toast = useToast()+const tasksStore = useTasksStore()+const goalsStore = useGoalsStore()+const organizationStore = useOrganizationStore()+const { activeTaskId, closeTask } = useTaskDetailPanel()+const { broadcastRemoval } = useTaskRemovalBroadcast()+const {+ actionTask,+ menuRequest,+ isMoveDialogOpen,+ isDeleteDialogOpen,+ canDelete,+ canMove,+ requestMove,+ requestDelete,+} = useTaskActions()++const contextMenu = ref<InstanceType<typeof TvContextMenu>>()++// A teleported dialog keeps the body position from its first mount; mounting on open+// puts it above the task dialog, which is mounted later than this host+const renderDeleteDialog = ref(false)+const renderMoveDialog = ref(false)+watch(isDeleteDialogOpen, (open) => {+ if (open) renderDeleteDialog.value = true+})+watch(isMoveDialogOpen, (open) => {+ if (open) renderMoveDialog.value = true+})++watch(menuRequest, (request) => {+ if (request) contextMenu.value?.openAtPoint(request.point)+})++function handleMenuMove() {+ contextMenu.value?.close()+ if (actionTask.value) requestMove(actionTask.value)+}++function handleMenuDelete() {+ contextMenu.value?.close()+ if (actionTask.value) requestDelete(actionTask.value)+}++function closeIfOpened(taskId: number) {+ if (activeTaskId.value === taskId) closeTask()+}++async function handleDelete() {+ if (!actionTask.value) return+ const taskId = actionTask.value.id+ const success = await tasksStore.deleteTask(taskId)+ if (success) {+ broadcastRemoval(taskId)+ closeIfOpened(taskId)+ }+}++function handleMoved(result: TaskResponseMoveToProject) {+ const project = goalsStore.goalMap.get(result.goalId)?.name ?? ''+ const open = async () => {+ await router.push({+ name: 'user',+ params: {+ orgSlug: organizationStore.currentOrgSlug,+ projectId: String(result.goalId),+ listId: String(ALL_TASKS_LIST_ID),+ taskId: String(result.taskId),+ },+ })+ }++ isMoveDialogOpen.value = false+ if (result.mode === 'move') {+ const sourceTaskId = actionTask.value?.id ?? result.taskId+ tasksStore.removeTaskLocally(sourceTaskId)+ broadcastRemoval(sourceTaskId)+ closeIfOpened(sourceTaskId)+ }+ toast.add({+ title: t(result.mode === 'move' ? 'tasks.move.moved' : 'tasks.move.copied', { project }),+ color: 'success',+ actions: [{ label: t('tasks.move.open'), onClick: open }],+ })+}+</script>diff --git a/web/src/components/features/tasks/parts/TaskDetailFooter.vue b/web/src/components/features/tasks/parts/TaskDetailFooter.vueindex b5f0436..18a5dc5 100644--- a/web/src/components/features/tasks/parts/TaskDetailFooter.vue+++ b/web/src/components/features/tasks/parts/TaskDetailFooter.vue@@ -2,6 +2,7 @@<div class="flex justify-between gap-2 w-full"><div class="flex gap-2"><UButton+ v-if="canDelete":label="t('common.delete')"color="error"variant="soft"@@ -33,6 +34,7 @@ import { useI18n } from 'vue-i18n'defineProps<{canMove: boolean+ canDelete: boolean}>()const emit = defineEmits<{diff --git a/web/src/components/features/tasks/parts/TaskItem.vue b/web/src/components/features/tasks/parts/TaskItem.vueindex fff1e14..685040d 100644--- a/web/src/components/features/tasks/parts/TaskItem.vue+++ b/web/src/components/features/tasks/parts/TaskItem.vue@@ -1,8 +1,9 @@<template><div- class="flex flex-col gap-3 p-3.5 rounded-2xl hover:bg-elevated bg-accented/20 transition-colors cursor-pointer"+ class="group flex flex-col gap-3 p-3.5 rounded-2xl hover:bg-elevated bg-accented/20 transition-colors cursor-pointer":data-testid="`task-item-${task.id}`"@click="handleOpenTask"+ @contextmenu="handleContextMenu"><div class="flex items-center gap-3"><div class="self-start mt-0.5 flex flex-col items-center gap-2">@@ -68,7 +69,12 @@size="md"data-testid="task-recurrence-badge"/>-++ <TaskSubtasksProgress+ v-if="task.subtasks?.length"+ :subtasks="task.subtasks"+ />+<!-- Attached files --><UBadgev-if="task.filesCount"@@ -148,12 +154,25 @@</div></div></div>++ <UButton+ v-if="showActions"+ icon="i-lucide-ellipsis-vertical"+ :aria-label="t('tasks.actions')"+ :data-testid="`task-menu-trigger-${task.id}`"+ color="neutral"+ variant="ghost"+ size="sm"+ class="nodrag self-start -my-1 -me-1 lg:opacity-0 lg:group-hover:opacity-100 focus-visible:opacity-100"+ @click.stop="handleMenuButton"+ /></div></div></template><script setup lang="ts">import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'import { type Task } from 'taskview-api'import { useGoalsStore } from '@/stores/goals.store'import { useGoalListsStore } from '@/stores/goal-lists.store'@@ -164,7 +183,9 @@ import { formatDate, normalizeDate } from '@vueuse/core'import { AllGoalPermissions } from '@/types/goals.types'import { useTaskDetailPanel } from '@/composables/useTaskDetailPanel'import { useUiPreferencesStore } from '@/stores/uiPreferences.store'+import { useTaskActions } from '@/composables/useTaskActions'import TaskIdCopy from './TaskIdCopy.vue'+import TaskSubtasksProgress from './TaskSubtasksProgress.vue'const TOGGLE_DELAY = 200const props = defineProps<{@@ -201,6 +222,22 @@ function handleOpenTask() {openTask(props.task.id)}+const { t } = useI18n()+const { hasActions, openMenu } = useTaskActions()+const showActions = computed(() => hasActions(props.task))++function handleMenuButton(event: MouseEvent) {+ const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()+ openMenu({ task: props.task, point: { x: rect.right, y: rect.bottom } })+}++// Touch long-press also fires contextmenu; keep it for drag on kanban+function handleContextMenu(event: MouseEvent) {+ if (!showActions.value || !window.matchMedia('(pointer: fine)').matches) return+ event.preventDefault()+ openMenu({ task: props.task, point: { x: event.clientX, y: event.clientY } })+}+const goalListsStore = useGoalListsStore()const baseScreenStore = useBaseScreenStore()const collaborationStore = useCollaborationStore()@@ -297,6 +334,7 @@ const hasAdditionalInfo = computed(() => {props.task.amount ||props.task.recurrenceRuleId ||props.task.filesCount ||+ props.task.subtasks?.length ||assigneeEmails.value.length > 0 ||taskTags.value.length > 0})diff --git a/web/src/components/features/tasks/parts/TaskMoveDialog.vue b/web/src/components/features/tasks/parts/TaskMoveDialog.vueindex ca1ee57..231cde6 100644--- a/web/src/components/features/tasks/parts/TaskMoveDialog.vue+++ b/web/src/components/features/tasks/parts/TaskMoveDialog.vue@@ -72,6 +72,7 @@ import type { Task, TaskResponseMovePreview, TaskResponseMoveToProject } from 'timport { useGoalsStore } from '@/stores/goals.store'import { useTasksStore } from '@/stores/tasks.store'import { useTaskView } from '@/composables/useTaskView'+import { useInbox } from '@/composables/useInbox'import { AllGoalPermissions } from '@/types/goals.types'import TaskMovePreview from './TaskMovePreview.vue'@@ -87,6 +88,7 @@ const isOpen = defineModel<boolean>('open', { required: true })const { t } = useI18n()const goalsStore = useGoalsStore()+const { isOwnInbox } = useInbox()const tasksStore = useTasksStore()const { isFullscreenModal } = useTaskView()@@ -100,7 +102,7 @@ const targets = computed(() => {return goalsStore.goals.filter((g) => g.id !== props.task?.goalId && !g.archive && g.organizationId === sourceGoal?.organizationId).filter((g) => !!g.permissions[AllGoalPermissions.COMPONENT_CAN_ADD_TASKS])- .map((g) => ({ label: g.isInbox ? t('projects.inbox') : g.name, value: g.id }))+ .map((g) => ({ label: isOwnInbox(g) ? t('projects.inbox') : g.name, value: g.id }))})watch(isOpen, (open) => {diff --git a/web/src/components/features/tasks/parts/TaskSubtasksProgress.vue b/web/src/components/features/tasks/parts/TaskSubtasksProgress.vuenew file mode 100644index 0000000..0364ab7--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskSubtasksProgress.vue@@ -0,0 +1,65 @@+<template>+ <UBadge+ :label="`${done}/${total}`"+ color="neutral"+ class="bg-elevated tabular-nums"+ :class="allDone ? 'text-primary' : 'text-muted'"+ :ui="{ base: 'rounded-md' }"+ :title="t('tasks.subtasksProgress', { done, total })"+ :aria-label="t('tasks.subtasksProgress', { done, total })"+ variant="subtle"+ size="md"+ data-testid="task-subtasks-badge"+ >+ <template #leading>+ <svg+ viewBox="0 0 16 16"+ class="size-3 shrink-0 -rotate-90"+ aria-hidden="true"+ >+ <circle+ cx="8"+ cy="8"+ :r="RADIUS"+ fill="none"+ stroke="currentColor"+ stroke-width="2.5"+ class="opacity-25"+ />+ <circle+ v-if="done > 0"+ cx="8"+ cy="8"+ :r="RADIUS"+ fill="none"+ stroke="currentColor"+ stroke-width="2.5"+ stroke-linecap="round"+ :stroke-dasharray="CIRCUMFERENCE"+ :stroke-dashoffset="dashOffset"+ class="text-primary transition-[stroke-dashoffset] duration-300 ease-out motion-reduce:transition-none"+ />+ </svg>+ </template>+ </UBadge>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import type { Task } from 'taskview-api'++const RADIUS = 6+const CIRCUMFERENCE = 2 * Math.PI * RADIUS++const props = defineProps<{+ subtasks: Task[]+}>()++const { t } = useI18n()++const total = computed(() => props.subtasks.length)+const done = computed(() => props.subtasks.filter(subtask => subtask.complete).length)+const allDone = computed(() => total.value > 0 && done.value === total.value)+const dashOffset = computed(() => CIRCUMFERENCE * (1 - done.value / total.value))+</script>diff --git a/web/src/components/features/ui-customization/UiCustomizationOthers.vue b/web/src/components/features/ui-customization/UiCustomizationOthers.vueindex d10c743..ec7a977 100644--- a/web/src/components/features/ui-customization/UiCustomizationOthers.vue+++ b/web/src/components/features/ui-customization/UiCustomizationOthers.vue@@ -52,6 +52,13 @@:description="t('uiCustomization.others.showTaskIdHint')"data-testid="show-task-id-switch"/>++ <USwitch+ v-model="keyboardShortcuts"+ :label="t('uiCustomization.others.keyboardShortcuts')"+ :description="t('uiCustomization.others.keyboardShortcutsHint')"+ data-testid="keyboard-shortcuts-switch"+ /></div></template>@@ -94,6 +101,13 @@ const showTaskId = computed<boolean>({},})+const keyboardShortcuts = computed<boolean>({+ get: () => store.settings.keyboardShortcuts !== 0,+ set: (value) => {+ store.setSetting('keyboardShortcuts', value ? undefined : 0)+ },+})+const projectItems = computed(() => [{ value: NONE, label: t('uiCustomization.others.defaultProjectNone') },...goalsStore.goals.map((goal) => ({ value: goal.id, label: goal.name })),diff --git a/web/src/components/features/ui-customization/UiCustomizationTheme.vue b/web/src/components/features/ui-customization/UiCustomizationTheme.vuenew file mode 100644index 0000000..08b28f9--- /dev/null+++ b/web/src/components/features/ui-customization/UiCustomizationTheme.vue@@ -0,0 +1,92 @@+<template>+ <div class="flex flex-col gap-8">+ <section class="flex flex-col gap-3">+ <div>+ <h3 class="text-base font-medium text-highlighted">+ {{ t('uiCustomization.theme.presetsTitle') }}+ </h3>+ <p class="text-sm text-muted">+ {{ t('uiCustomization.theme.presetsHint') }}+ </p>+ </div>+ <div class="grid grid-cols-2 gap-2 sm:grid-cols-3">+ <UiCustomizationThemePreset+ v-for="preset in THEME_PRESETS"+ :key="preset.id"+ :preset="preset"+ :active="!customActive && preset.primary === colors.primary && preset.neutral === colors.neutral"+ @select="setColors(preset)"+ />+ </div>+ </section>++ <UFormField+ :label="t('uiCustomization.theme.primaryTitle')"+ :description="t('uiCustomization.theme.primaryHint')"+ :ui="{ container: 'mt-3' }"+ >+ <UiCustomizationThemeSwatches+ v-model="primary"+ :colors="THEME_PRIMARY_COLORS"+ kind="primary"+ :label="t('uiCustomization.theme.primaryTitle')"+ />+ </UFormField>++ <UFormField+ :label="t('uiCustomization.theme.neutralTitle')"+ :description="t('uiCustomization.theme.neutralHint')"+ :ui="{ container: 'mt-3' }"+ >+ <UiCustomizationThemeSwatches+ v-model="neutral"+ :colors="THEME_NEUTRAL_COLORS"+ kind="neutral"+ :label="t('uiCustomization.theme.neutralTitle')"+ />+ </UFormField>++ <UiCustomizationThemeCustom />++ <div>+ <UButton+ icon="i-lucide-rotate-ccw"+ color="neutral"+ variant="soft"+ :disabled="isDefault"+ data-testid="theme-reset"+ @click="reset"+ >+ {{ t('uiCustomization.theme.reset') }}+ </UButton>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { THEME_NEUTRAL_COLORS, THEME_PRIMARY_COLORS, type ThemeNeutralColor, type ThemePrimaryColor } from 'taskview-api'+import { useThemeColors } from '@/composables/useThemeColors'+import UiCustomizationThemePreset from './parts/UiCustomizationThemePreset.vue'+import UiCustomizationThemeSwatches from './parts/UiCustomizationThemeSwatches.vue'+import UiCustomizationThemeCustom from './parts/UiCustomizationThemeCustom.vue'+import { THEME_PRESETS } from './parts/theme-presets'++const { t } = useI18n()+const { colors, customActive, isDefault, setColors, reset } = useThemeColors()++const primary = computed<ThemePrimaryColor | null>({+ get: () => (customActive.value ? null : colors.value.primary),+ set: (value) => {+ if (value) setColors({ ...colors.value, primary: value })+ },+})++const neutral = computed<ThemeNeutralColor | null>({+ get: () => (customActive.value ? null : colors.value.neutral),+ set: (value) => {+ if (value) setColors({ ...colors.value, neutral: value })+ },+})+</script>diff --git a/web/src/components/features/ui-customization/parts/UiCustomizationThemeColorField.vue b/web/src/components/features/ui-customization/parts/UiCustomizationThemeColorField.vuenew file mode 100644index 0000000..29ffa78--- /dev/null+++ b/web/src/components/features/ui-customization/parts/UiCustomizationThemeColorField.vue@@ -0,0 +1,77 @@+<template>+ <div class="flex items-center justify-between gap-3 py-2.5">+ <div class="min-w-0">+ <p class="text-sm font-medium text-highlighted">+ {{ label }}+ </p>+ <p class="text-xs text-muted">+ {{ hint }}+ </p>+ </div>+ <div class="flex shrink-0 items-center gap-2">+ <UPopover>+ <button+ type="button"+ class="size-9 rounded-lg border border-accented shadow-xs outline-none transition hover:scale-105 focus-visible:ring-2 focus-visible:ring-primary"+ :style="{ background: model }"+ :aria-label="t('uiCustomization.theme.custom.pickColor', { name: label })"+ :data-testid="`theme-custom-${field}-swatch`"+ />+ <template #content>+ <UColorPicker+ :model-value="model"+ class="p-3"+ @update:model-value="pick"+ />+ </template>+ </UPopover>+ <UInput+ v-model="draft"+ :maxlength="7"+ size="md"+ class="w-28"+ :ui="{ base: 'font-mono uppercase rounded-lg' }"+ :aria-label="label"+ :data-testid="`theme-custom-${field}-input`"+ @change="commit"+ @keydown.enter="commit"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'++defineProps<{+ field: string+ label: string+ hint: string+}>()++const model = defineModel<string>({ required: true })++const { t } = useI18n()++const HEX_COLOR = /^#?([0-9a-fA-F]{6})$/++const draft = ref(model.value)++watch(model, (value) => {+ draft.value = value+})++function pick(value: string | undefined) {+ if (value && HEX_COLOR.test(value)) model.value = value.toLowerCase()+}++function commit() {+ const match = draft.value.trim().match(HEX_COLOR)+ if (match) {+ model.value = `#${match[1].toLowerCase()}`+ } else {+ draft.value = model.value+ }+}+</script>diff --git a/web/src/components/features/ui-customization/parts/UiCustomizationThemeCustom.vue b/web/src/components/features/ui-customization/parts/UiCustomizationThemeCustom.vuenew file mode 100644index 0000000..dee7779--- /dev/null+++ b/web/src/components/features/ui-customization/parts/UiCustomizationThemeCustom.vue@@ -0,0 +1,109 @@+<template>+ <section class="flex flex-col gap-3">+ <div class="flex items-start justify-between gap-4">+ <div>+ <h3 class="text-base font-medium text-highlighted">+ {{ t('uiCustomization.theme.custom.title') }}+ </h3>+ <p class="text-sm text-muted">+ {{ t('uiCustomization.theme.custom.hint') }}+ </p>+ </div>+ <USwitch+ :model-value="customActive"+ :aria-label="t('uiCustomization.theme.custom.title')"+ data-testid="theme-custom-switch"+ @update:model-value="setCustomActive"+ />+ </div>++ <div+ v-if="customActive && customTheme"+ class="flex flex-col gap-2 rounded-2xl border border-default p-3 lg:p-4"+ >+ <div class="flex flex-wrap items-center justify-between gap-2">+ <UTabs+ v-model="mode"+ :items="modeItems"+ :content="false"+ size="sm"+ :ui="{ list: 'rounded-xl', trigger: 'rounded-lg', indicator: 'rounded-lg' }"+ />+ <UButton+ icon="i-lucide-wand-sparkles"+ color="neutral"+ variant="ghost"+ size="sm"+ data-testid="theme-custom-refill"+ @click="refillCustomTheme"+ >+ {{ t('uiCustomization.theme.custom.refill') }}+ </UButton>+ </div>++ <p+ v-if="mode !== activeMode"+ class="text-xs text-muted"+ >+ {{ t(mode === 'dark' ? 'uiCustomization.theme.custom.otherModeDark' : 'uiCustomization.theme.custom.otherModeLight') }}+ </p>++ <div class="divide-y divide-default">+ <UiCustomizationThemeColorField+ v-for="key in CUSTOM_THEME_COLOR_KEYS"+ :key="key"+ :field="key"+ :label="t(`uiCustomization.theme.custom.fields.${key}`)"+ :hint="t(`uiCustomization.theme.custom.fields.${key}Hint`)"+ :model-value="customTheme[mode][key]"+ @update:model-value="(value) => update(key, value)"+ />+ </div>++ <UAlert+ v-if="contrast < MIN_TEXT_CONTRAST"+ color="warning"+ variant="soft"+ icon="i-lucide-triangle-alert"+ :title="t('uiCustomization.theme.custom.lowContrast', { ratio: contrast.toFixed(1) })"+ data-testid="theme-custom-low-contrast"+ />+ </div>+ </section>+</template>++<script setup lang="ts">+import { computed, ref } from 'vue'+import { useI18n } from 'vue-i18n'+import { useColorMode } from '@vueuse/core'+import { CUSTOM_THEME_COLOR_KEYS, type CustomThemeColorKey } from 'taskview-api'+import { useThemeColors } from '@/composables/useThemeColors'+import { contrastRatio } from '@/helpers/custom-theme'+import UiCustomizationThemeColorField from './UiCustomizationThemeColorField.vue'++const MIN_TEXT_CONTRAST = 4.5++const { t } = useI18n()+const { customActive, customTheme, setCustomActive, setCustomTheme, refillCustomTheme } = useThemeColors()+const { state: colorModeState } = useColorMode()++const activeMode = computed<'light' | 'dark'>(() => (colorModeState.value === 'dark' ? 'dark' : 'light'))+const mode = ref<'light' | 'dark'>(activeMode.value)++const modeItems = computed(() => [+ { value: 'light', label: t('uiCustomization.theme.custom.light'), icon: 'i-lucide-sun' },+ { value: 'dark', label: t('uiCustomization.theme.custom.dark'), icon: 'i-lucide-moon' },+])++const contrast = computed(() => {+ const palette = customTheme.value?.[mode.value]+ if (!palette) return Infinity+ return Math.min(contrastRatio(palette.text, palette.background), contrastRatio(palette.text, palette.surface))+})++function update(key: CustomThemeColorKey, value: string) {+ const theme = customTheme.value+ if (!theme) return+ setCustomTheme({ ...theme, [mode.value]: { ...theme[mode.value], [key]: value } })+}+</script>diff --git a/web/src/components/features/ui-customization/parts/UiCustomizationThemePreset.vue b/web/src/components/features/ui-customization/parts/UiCustomizationThemePreset.vuenew file mode 100644index 0000000..5b62d36--- /dev/null+++ b/web/src/components/features/ui-customization/parts/UiCustomizationThemePreset.vue@@ -0,0 +1,85 @@+<template>+ <button+ type="button"+ class="group flex flex-col gap-2 rounded-2xl p-1.5 text-start outline-none transition focus-visible:ring-2 focus-visible:ring-primary"+ :class="active ? 'bg-elevated ring-2 ring-primary' : 'hover:bg-elevated/60'"+ :style="vars"+ :aria-pressed="active"+ :data-testid="`theme-preset-${preset.id}`"+ @click="emit('select')"+ >+ <span+ class="flex aspect-[16/10] w-full overflow-hidden rounded-xl border border-(--pv-border) bg-(--pv-surface) dark:border-(--pv-border-dark) dark:bg-(--pv-surface-dark)"+ aria-hidden="true"+ >+ <span class="flex w-[34%] flex-col gap-1.5 bg-(--pv-sidebar) p-2 dark:bg-(--pv-sidebar-dark)">+ <span class="h-1.5 w-3/4 rounded-full bg-(--pv-line) dark:bg-(--pv-line-dark)" />+ <span class="flex h-3 items-center rounded-md bg-(--pv-accent-soft) px-1 dark:bg-(--pv-accent-soft-dark)">+ <span class="h-1 w-2/3 rounded-full bg-(--pv-accent) dark:bg-(--pv-accent-dark)" />+ </span>+ <span class="h-1.5 w-1/2 rounded-full bg-(--pv-line) dark:bg-(--pv-line-dark)" />+ <span class="h-1.5 w-2/3 rounded-full bg-(--pv-line) dark:bg-(--pv-line-dark)" />+ </span>+ <span class="flex flex-1 flex-col gap-1.5 p-2">+ <span+ v-for="(done, row) in TASK_ROWS"+ :key="row"+ class="flex items-center gap-1.5"+ >+ <span+ class="size-2 shrink-0 rounded-full border border-(--pv-line) dark:border-(--pv-line-dark)"+ :class="done ? 'border-(--pv-accent) bg-(--pv-accent) dark:border-(--pv-accent-dark) dark:bg-(--pv-accent-dark)' : ''"+ />+ <span class="h-1.5 flex-1 rounded-full bg-(--pv-faint) dark:bg-(--pv-faint-dark)" />+ </span>+ <span class="mt-auto h-3 w-1/2 self-end rounded-md bg-(--pv-accent) dark:bg-(--pv-accent-dark)" />+ </span>+ </span>+ <span class="flex items-center justify-between gap-2 px-1 text-sm">+ <span :class="active ? 'font-medium text-highlighted' : 'text-default'">{{ t(preset.labelKey) }}</span>+ <UIcon+ v-if="active"+ name="i-lucide-check"+ class="size-4 text-primary"+ />+ </span>+ </button>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { paletteVar } from './theme-palette'+import type { ThemePreset } from './theme-presets.types'++const props = defineProps<{+ preset: ThemePreset+ active: boolean+}>()++const emit = defineEmits<{ select: [] }>()++const { t } = useI18n()++const TASK_ROWS = [true, false, false]++const vars = computed(() => {+ const { primary, neutral } = props.preset+ return {+ '--pv-accent': paletteVar(primary, 500),+ '--pv-accent-dark': paletteVar(primary, 400),+ '--pv-accent-soft': `color-mix(in oklab, ${paletteVar(primary, 500)} 14%, transparent)`,+ '--pv-accent-soft-dark': `color-mix(in oklab, ${paletteVar(primary, 400)} 18%, transparent)`,+ '--pv-surface': paletteVar(neutral, 50),+ '--pv-surface-dark': paletteVar(neutral, 950),+ '--pv-sidebar': paletteVar(neutral, 100),+ '--pv-sidebar-dark': paletteVar(neutral, 900),+ '--pv-border': paletteVar(neutral, 200),+ '--pv-border-dark': paletteVar(neutral, 800),+ '--pv-line': paletteVar(neutral, 300),+ '--pv-line-dark': paletteVar(neutral, 700),+ '--pv-faint': paletteVar(neutral, 200),+ '--pv-faint-dark': paletteVar(neutral, 800),+ }+})+</script>diff --git a/web/src/components/features/ui-customization/parts/UiCustomizationThemeSwatches.vue b/web/src/components/features/ui-customization/parts/UiCustomizationThemeSwatches.vuenew file mode 100644index 0000000..0c8bc39--- /dev/null+++ b/web/src/components/features/ui-customization/parts/UiCustomizationThemeSwatches.vue@@ -0,0 +1,57 @@+<template>+ <div+ role="radiogroup"+ :aria-label="label"+ class="flex flex-wrap gap-2"+ >+ <UTooltip+ v-for="color in colors"+ :key="color"+ :text="t(`uiCustomization.theme.colorNames.${color}`)"+ >+ <button+ type="button"+ role="radio"+ :aria-checked="model === color"+ :aria-label="t(`uiCustomization.theme.colorNames.${color}`)"+ :data-testid="`theme-swatch-${color}`"+ class="relative flex items-center justify-center rounded-full outline-none ring-offset-2 ring-offset-(--ui-bg) transition focus-visible:ring-2 focus-visible:ring-(--ui-border-inverted)"+ :class="[+ kind === 'primary' ? 'size-8' : 'h-8 w-14',+ model === color ? 'ring-2 ring-(--ui-border-inverted)' : 'hover:scale-105',+ ]"+ :style="swatchStyle(color)"+ @click="model = color"+ >+ <UIcon+ v-if="model === color"+ name="i-lucide-check"+ class="size-4 text-white drop-shadow"+ />+ </button>+ </UTooltip>+ </div>+</template>++<script setup lang="ts" generic="T extends ThemePrimaryColor | ThemeNeutralColor">+import { useI18n } from 'vue-i18n'+import type { ThemeNeutralColor, ThemePrimaryColor } from 'taskview-api'+import { paletteVar } from './theme-palette'++const props = defineProps<{+ colors: readonly T[]+ kind: 'primary' | 'neutral'+ label: string+}>()++const model = defineModel<T | null>({ required: true })++const { t } = useI18n()++function swatchStyle(color: T) {+ if (props.kind === 'primary') return { background: paletteVar(color, 500) }+ return {+ background: `linear-gradient(90deg, ${paletteVar(color, 200)} 0 33%, ${paletteVar(color, 500)} 33% 66%, ${paletteVar(color, 800)} 66%)`,+ }+}+</script>diff --git a/web/src/components/features/ui-customization/parts/theme-palette.ts b/web/src/components/features/ui-customization/parts/theme-palette.tsnew file mode 100644index 0000000..b1c72dc--- /dev/null+++ b/web/src/components/features/ui-customization/parts/theme-palette.ts@@ -0,0 +1,11 @@+import type { ThemeNeutralColor, ThemePrimaryColor } from 'taskview-api'+import type { PaletteShade } from './theme-palette.types'++/** Nuxt UI aliases `neutral` to the active neutral color and keeps Tailwind's own neutral as `old-neutral`. */+export function paletteVarName(color: ThemePrimaryColor | ThemeNeutralColor, shade: PaletteShade): string {+ return `--color-${color === 'neutral' ? 'old-neutral' : color}-${shade}`+}++export function paletteVar(color: ThemePrimaryColor | ThemeNeutralColor, shade: PaletteShade): string {+ return `var(${paletteVarName(color, shade)})`+}diff --git a/web/src/components/features/ui-customization/parts/theme-palette.types.ts b/web/src/components/features/ui-customization/parts/theme-palette.types.tsnew file mode 100644index 0000000..b9a873a--- /dev/null+++ b/web/src/components/features/ui-customization/parts/theme-palette.types.ts@@ -0,0 +1 @@+export type PaletteShade = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 950diff --git a/web/src/components/features/ui-customization/parts/theme-presets.ts b/web/src/components/features/ui-customization/parts/theme-presets.tsnew file mode 100644index 0000000..e03d559--- /dev/null+++ b/web/src/components/features/ui-customization/parts/theme-presets.ts@@ -0,0 +1,13 @@+import type { ThemePreset } from './theme-presets.types'++export const THEME_PRESETS: ThemePreset[] = [+ { id: 'taskview', labelKey: 'uiCustomization.theme.presets.taskview', primary: 'green', neutral: 'zinc' },+ { id: 'forest', labelKey: 'uiCustomization.theme.presets.forest', primary: 'green', neutral: 'moss' },+ { id: 'lagoon', labelKey: 'uiCustomization.theme.presets.lagoon', primary: 'teal', neutral: 'tide' },+ { id: 'ocean', labelKey: 'uiCustomization.theme.presets.ocean', primary: 'sky', neutral: 'ink' },+ { id: 'dusk', labelKey: 'uiCustomization.theme.presets.dusk', primary: 'indigo', neutral: 'ink' },+ { id: 'lavender', labelKey: 'uiCustomization.theme.presets.lavender', primary: 'violet', neutral: 'plum' },+ { id: 'raspberry', labelKey: 'uiCustomization.theme.presets.raspberry', primary: 'rose', neutral: 'wine' },+ { id: 'sunset', labelKey: 'uiCustomization.theme.presets.sunset', primary: 'orange', neutral: 'sand' },+ { id: 'honey', labelKey: 'uiCustomization.theme.presets.honey', primary: 'amber', neutral: 'sand' },+]diff --git a/web/src/components/features/ui-customization/parts/theme-presets.types.ts b/web/src/components/features/ui-customization/parts/theme-presets.types.tsnew file mode 100644index 0000000..867ef00--- /dev/null+++ b/web/src/components/features/ui-customization/parts/theme-presets.types.ts@@ -0,0 +1,6 @@+import type { ThemeColors } from '@/composables/useThemeColors.types'++export type ThemePreset = ThemeColors & {+ id: string+ labelKey: string+}diff --git a/web/src/components/features/webhooks/WebhooksPanel.vue b/web/src/components/features/webhooks/WebhooksPanel.vueindex ee5dd60..a359976 100644--- a/web/src/components/features/webhooks/WebhooksPanel.vue+++ b/web/src/components/features/webhooks/WebhooksPanel.vue@@ -11,13 +11,24 @@<p>{{ t('webhooks.selectProject') }}</p></div>+ <div+ v-else-if="!canViewWebhooks"+ class="flex flex-col items-center justify-center h-64 text-muted"+ >+ <UIcon+ name="i-lucide-lock"+ class="size-12 mb-4"+ />+ <p>{{ t('webhooks.noAccess') }}</p>+ </div>+<template v-else><div class="flex items-center justify-between mb-4"><h2 class="text-lg font-semibold">{{ projectName }}</h2><UButton- v-if="canManageIntegrations"+ v-if="canManageWebhooks":label="t('webhooks.add')"icon="i-lucide-plus"color="primary"@@ -51,7 +62,7 @@v-for="item in webhooksStore.webhooks":key="item.id":webhook="item"- :can-manage="canManageIntegrations"+ :can-manage="canManageWebhooks"@toggle="handleToggle"@delete="handleDelete"@show-deliveries="openDeliveries"@@ -75,6 +86,7 @@<WebhookDeliveriesv-model:open="isDeliveriesOpen":webhook-id="selectedWebhookId"+ :can-manage="canManageWebhooks"/></div></template>@@ -96,7 +108,7 @@ const { t } = useI18n()const { projectId } = useAppRouteInfo()const goalsStore = useGoalsStore()const webhooksStore = useWebhooksStore()-const { canManageIntegrations } = useGoalPermissions()+const { canViewWebhooks, canManageWebhooks } = useGoalPermissions()const loading = ref(false)const isAddModalOpen = ref(false)@@ -109,13 +121,13 @@ const hasGoalSelected = computed(() => projectId.value > 0)const projectName = computed(() => goalsStore.goalMap.get(projectId.value)?.name ?? '')async function fetchData() {- if (!hasGoalSelected.value) return+ if (!hasGoalSelected.value || !canViewWebhooks.value) returnloading.value = trueawait webhooksStore.fetchWebhooks(projectId.value)loading.value = false}-watch(projectId, fetchData, { immediate: true })+watch([projectId, canViewWebhooks], fetchData, { immediate: true })async function handleToggle(id: number, isActive: boolean) {await webhooksStore.updateWebhook({ id, isActive })diff --git a/web/src/components/features/webhooks/parts/WebhookDeliveries.vue b/web/src/components/features/webhooks/parts/WebhookDeliveries.vueindex ac6021b..0665b18 100644--- a/web/src/components/features/webhooks/parts/WebhookDeliveries.vue+++ b/web/src/components/features/webhooks/parts/WebhookDeliveries.vue@@ -74,7 +74,7 @@@click="openPayload(row.original)"/><UButton- v-if="row.original.status === 'failed'"+ v-if="canManage && row.original.status === 'failed'"icon="i-lucide-refresh-cw"variant="ghost"size="xs"@@ -115,6 +115,7 @@ import type { WebhookDeliveryItem } from 'taskview-api'const props = defineProps<{webhookId: number+ canManage: boolean}>()const isOpen = defineModel<boolean>('open', { default: false })diff --git a/web/src/components/features/webhooks/parts/WebhookItem.vue b/web/src/components/features/webhooks/parts/WebhookItem.vueindex 9fcd135..292da19 100644--- a/web/src/components/features/webhooks/parts/WebhookItem.vue+++ b/web/src/components/features/webhooks/parts/WebhookItem.vue@@ -22,25 +22,7 @@</div></div></div>- <div- v-if="canManage"- class="flex items-center gap-2 shrink-0 ml-2"- >- <UButton- icon="i-lucide-pencil"- variant="ghost"- size="md"- :title="t('webhooks.edit')"- @click="emit('edit', webhook)"- />- <UButton- icon="i-lucide-send"- variant="ghost"- size="md"- :loading="testing"- :title="t('webhooks.test')"- @click="handleTest"- />+ <div class="flex items-center gap-2 shrink-0 ml-2"><UButtonicon="i-lucide-history"variant="ghost"@@ -48,25 +30,42 @@:title="t('webhooks.deliveries')"@click="emit('showDeliveries', webhook.id)"/>- <UButton- icon="i-lucide-key-round"- variant="ghost"- size="md"- :title="t('webhooks.rotateSecret')"- @click="showRotateConfirm = true"- />- <USwitch- :model-value="webhook.isActive"- size="md"- @update:model-value="handleToggle"- />- <UButton- icon="i-lucide-trash-2"- variant="ghost"- color="error"- size="md"- @click="emit('delete', webhook.id)"- />+ <template v-if="canManage">+ <UButton+ icon="i-lucide-pencil"+ variant="ghost"+ size="md"+ :title="t('webhooks.edit')"+ @click="emit('edit', webhook)"+ />+ <UButton+ icon="i-lucide-send"+ variant="ghost"+ size="md"+ :loading="testing"+ :title="t('webhooks.test')"+ @click="handleTest"+ />+ <UButton+ icon="i-lucide-key-round"+ variant="ghost"+ size="md"+ :title="t('webhooks.rotateSecret')"+ @click="showRotateConfirm = true"+ />+ <USwitch+ :model-value="webhook.isActive"+ size="md"+ @update:model-value="handleToggle"+ />+ <UButton+ icon="i-lucide-trash-2"+ variant="ghost"+ color="error"+ size="md"+ @click="emit('delete', webhook.id)"+ />+ </template></div></div>diff --git a/web/src/components/sidebars/SidebarDefaultProjectLink.vue b/web/src/components/sidebars/SidebarDefaultProjectLink.vueindex b4d6892..306d218 100644--- a/web/src/components/sidebars/SidebarDefaultProjectLink.vue+++ b/web/src/components/sidebars/SidebarDefaultProjectLink.vue@@ -24,6 +24,7 @@ import { useUiPreferencesStore } from '@/stores/uiPreferences.store'import { useGoalsStore } from '@/stores/goals.store'const { t } = useI18n()+const toast = useToast()const route = useRoute()const router = useRouter()const uiPrefs = useUiPreferencesStore()@@ -44,6 +45,10 @@ const label = computed(() => {async function openDefaultProject() {const target = await resolveDefaultRoute()- if (target) await router.push(target)+ if (!target) {+ toast.add({ title: t('uiCustomization.others.defaultProjectUnavailable'), color: 'warning' })+ return+ }+ await router.push(target)}</script>diff --git a/web/src/components/sidebars/SidebarInboxLink.vue b/web/src/components/sidebars/SidebarInboxLink.vueindex d6c9020..92be400 100644--- a/web/src/components/sidebars/SidebarInboxLink.vue+++ b/web/src/components/sidebars/SidebarInboxLink.vue@@ -1,9 +1,9 @@<template><TvGoalLikeItem- v-if="inbox"+ v-if="link"variant="taskview"- :to="{ name: 'user', params: { projectId: inbox.id, listId: ALL_TASKS_LIST_ID } }"- :active="currentProjectId === inbox.id"+ :to="link"+ :active="currentProjectId === inboxId"><divclass="flex items-center gap-2 w-full"@@ -22,13 +22,12 @@import { computed } from 'vue'import { useRoute } from 'vue-router'import { useI18n } from 'vue-i18n'-import { ALL_TASKS_LIST_ID } from 'taskview-api'-import { useInbox } from '@/composables/useInbox'+import { useSidebarInboxLink } from '@/composables/useSidebarInboxLink'import TvGoalLikeItem from '@/components/features/base/TvGoalLikeItem.vue'const { t } = useI18n()const route = useRoute()-const { inbox } = useInbox()+const { link, inboxId } = useSidebarInboxLink()const currentProjectId = computed(() => Number(route.params.projectId) || null)</script>diff --git a/web/src/components/sidebars/dashboard-second/SidebarProjectSelect.vue b/web/src/components/sidebars/dashboard-second/SidebarProjectSelect.vueindex 4f65b7e..7b53ac6 100644--- a/web/src/components/sidebars/dashboard-second/SidebarProjectSelect.vue+++ b/web/src/components/sidebars/dashboard-second/SidebarProjectSelect.vue@@ -10,7 +10,7 @@variant="soft"size="xl"block- :icon="currentProject?.isInbox ? 'i-lucide-inbox' : 'i-lucide-folder'"+ :icon="currentProject && isOwnInbox(currentProject) ? 'i-lucide-inbox' : 'i-lucide-folder'"trailing-icon="i-lucide-chevron-down":ui="{ base: 'rounded-xl', trailingIcon: 'ms-auto' }"data-testid="project-select-trigger"@@ -153,6 +153,7 @@ import { storeToRefs } from 'pinia'import { useGoalsStore } from '@/stores/goals.store'import { useGoalPermissionsFor } from '@/composables/useGoalPermissions'import { useProjectRoute } from '@/composables/useProjectRoute'+import { useInbox } from '@/composables/useInbox'import type { Project, ProjectSaveData } from '@/components/features/projects/types'import ProjectEditModal from '@/components/features/projects/parts/ProjectEditModal.vue'import ProjectDeleteDialog from '@/components/features/projects/parts/ProjectDeleteDialog.vue'@@ -161,6 +162,7 @@ const { t } = useI18n()const route = useRoute()const router = useRouter()const { projectRoute } = useProjectRoute()+const { isOwnInbox } = useInbox()const goalsStore = useGoalsStore()const { goals } = storeToRefs(goalsStore)@@ -170,8 +172,8 @@ const isEditOpen = ref(false)const isDeleteOpen = ref(false)const currentProjectId = computed(() => Number(route.params.projectId) || null)-const activeProjects = computed(() => goals.value.filter(p => p.archive === 0 && !p.isInbox))-const archivedProjects = computed(() => goals.value.filter(p => p.archive === 1 && !p.isInbox))+const activeProjects = computed(() => goals.value.filter(p => p.archive === 0 && !isOwnInbox(p)))+const archivedProjects = computed(() => goals.value.filter(p => p.archive === 1 && !isOwnInbox(p)))const currentProject = computed<Project | null>(() =>currentProjectId.value ? goalsStore.goalMap.get(currentProjectId.value) ?? null : null,)@@ -179,7 +181,7 @@ const isArchived = computed(() => currentProject.value?.archive === 1)const isInbox = computed(() => currentProject.value?.isInbox === true)const currentProjectLabel = computed(() =>currentProject.value- ? (currentProject.value.isInbox ? t('projects.inbox') : currentProject.value.name)+ ? (isOwnInbox(currentProject.value) ? t('projects.inbox') : currentProject.value.name): t('projects.selectProject'),)diff --git a/web/src/components/sidebars/dashboard-second/SidebarTools.vue b/web/src/components/sidebars/dashboard-second/SidebarTools.vueindex 591f77f..c5f4bf6 100644--- a/web/src/components/sidebars/dashboard-second/SidebarTools.vue+++ b/web/src/components/sidebars/dashboard-second/SidebarTools.vue@@ -71,6 +71,7 @@ const {canViewAutomations,canManageUsers,canViewIntegrations,+ canViewWebhooks,canViewTimeTracking,} = useGoalPermissionsFor(currentProject)@@ -107,8 +108,10 @@ const tools = computed<Tool[]>(() => {if (canManageUsers.value) {list.push({ key: 'collaboration', label: t('contextMenu.collaboration'), icon: 'i-lucide-users', to: { name: 'collaboration', params: { projectId: id } }, active: () => route.name === 'collaboration' })}- if (canViewIntegrations.value) {+ if (canViewWebhooks.value) {list.push({ key: 'webhooks', label: t('contextMenu.webhooks'), icon: 'i-lucide-webhook', to: { name: 'webhooks', params: { projectId: id } }, active: () => route.name === 'webhooks' })+ }+ if (canViewIntegrations.value) {list.push({ key: 'integrations', label: t('contextMenu.integrations'), icon: 'i-lucide-plug', to: { name: 'integrations', params: { projectId: id } }, active: () => route.name === 'integrations' })list.push({ key: 'messaging', label: t('contextMenu.messaging'), icon: 'i-lucide-send', to: { name: 'messaging', params: { projectId: id } }, active: () => route.name === 'messaging' })}diff --git a/web/src/composables/useGoalPermissions.ts b/web/src/composables/useGoalPermissions.tsindex 9e70394..523fbc2 100644--- a/web/src/composables/useGoalPermissions.ts+++ b/web/src/composables/useGoalPermissions.ts@@ -22,19 +22,21 @@ export function useGoalPermissionsFor(goalRef: Ref<GoalItem | null>) {canDeleteGoal: can('GOAL_CAN_DELETE'),canEditGoal: can('GOAL_CAN_EDIT'),canManageUsers: can('GOAL_CAN_MANAGE_USERS'),- canViewKanban: computed(() => hasPermission(goalRef.value, 'KANBAN_CAN_VIEW') || hasPermission(goalRef.value, 'KANBAN_CAN_MANAGE')),- canViewGraph: computed(() => hasPermission(goalRef.value, 'GRAPH_CAN_VIEW') || hasPermission(goalRef.value, 'GRAPH_CAN_MANAGE')),- canViewIntegrations: computed(() => hasPermission(goalRef.value, 'INTEGRATIONS_CAN_VIEW') || hasPermission(goalRef.value, 'INTEGRATIONS_CAN_MANAGE')),+ canViewKanban: can('KANBAN_CAN_VIEW'),+ canViewGraph: can('GRAPH_CAN_VIEW'),+ canViewIntegrations: can('INTEGRATIONS_CAN_VIEW'),canManageIntegrations: computed(() => hasPermission(goalRef.value, 'INTEGRATIONS_CAN_MANAGE')),- canViewTimeTracking: computed(() => hasPermission(goalRef.value, 'TIMETRACKING_CAN_VIEW') || hasPermission(goalRef.value, 'TIMETRACKING_CAN_MANAGE_ALL')),+ canViewTimeTracking: can('TIMETRACKING_CAN_VIEW'),canViewSprints: can('SPRINT_CAN_VIEW'),canManageSprints: can('SPRINT_CAN_MANAGE'),canAssignSprintTasks: can('SPRINT_CAN_ASSIGN_TASKS'),canViewSprintAnalytics: can('SPRINT_CAN_VIEW_ANALYTICS'),- canViewFiles: computed(() => hasPermission(goalRef.value, 'FILE_CAN_VIEW') || hasPermission(goalRef.value, 'FILE_CAN_MANAGE')),+ canViewFiles: can('FILE_CAN_VIEW'),canManageFiles: can('FILE_CAN_MANAGE'),- canViewAutomations: computed(() => hasPermission(goalRef.value, 'AUTOMATION_CAN_VIEW') || hasPermission(goalRef.value, 'AUTOMATION_CAN_MANAGE')),+ canViewAutomations: can('AUTOMATION_CAN_VIEW'),canManageAutomations: can('AUTOMATION_CAN_MANAGE'),+ canViewWebhooks: can('WEBHOOKS_CAN_VIEW'),+ canManageWebhooks: can('WEBHOOKS_CAN_MANAGE'),}}@@ -82,15 +84,15 @@ export const useGoalPermissions = () => {const canRecoveryTaskHistory = computed(() => permissions.TASK_CAN_RECOVERY_HISTORY)const canAssignUsersToTask = computed(() => permissions.TASK_CAN_ASSIGN_USERS)const canViewAssignedUsersToTask = computed(() => permissions.TASK_CAN_WATCH_ASSIGNED_USERS)- const canViewKanban = computed(() => permissions.KANBAN_CAN_VIEW || permissions.KANBAN_CAN_MANAGE)+ const canViewKanban = computed(() => permissions.KANBAN_CAN_VIEW)const canManageKanban = computed(() => permissions.KANBAN_CAN_MANAGE)- const canViewGraph = computed(() => permissions.GRAPH_CAN_VIEW || permissions.GRAPH_CAN_MANAGE)+ const canViewGraph = computed(() => permissions.GRAPH_CAN_VIEW)const canManageGraph = computed(() => permissions.GRAPH_CAN_MANAGE)- const canViewIntegrations = computed(() => permissions.INTEGRATIONS_CAN_VIEW || permissions.INTEGRATIONS_CAN_MANAGE)+ const canViewIntegrations = computed(() => permissions.INTEGRATIONS_CAN_VIEW)const canManageIntegrations = computed(() => permissions.INTEGRATIONS_CAN_MANAGE)- const canViewTimeTracking = computed(() => permissions.TIMETRACKING_CAN_VIEW || permissions.TIMETRACKING_CAN_MANAGE_ALL)- const canLogTime = computed(() => permissions.TIMETRACKING_CAN_LOG || permissions.TIMETRACKING_CAN_MANAGE_ALL)+ const canViewTimeTracking = computed(() => permissions.TIMETRACKING_CAN_VIEW)+ const canLogTime = computed(() => permissions.TIMETRACKING_CAN_LOG)const canManageAllTime = computed(() => permissions.TIMETRACKING_CAN_MANAGE_ALL)const canViewSprints = computed(() => permissions.SPRINT_CAN_VIEW)@@ -98,10 +100,12 @@ export const useGoalPermissions = () => {const canAssignSprintTasks = computed(() => permissions.SPRINT_CAN_ASSIGN_TASKS)const canViewSprintAnalytics = computed(() => permissions.SPRINT_CAN_VIEW_ANALYTICS)- const canViewFiles = computed(() => permissions.FILE_CAN_VIEW || permissions.FILE_CAN_MANAGE)+ const canViewFiles = computed(() => permissions.FILE_CAN_VIEW)const canManageFiles = computed(() => permissions.FILE_CAN_MANAGE)- const canViewAutomations = computed(() => permissions.AUTOMATION_CAN_VIEW || permissions.AUTOMATION_CAN_MANAGE)+ const canViewAutomations = computed(() => permissions.AUTOMATION_CAN_VIEW)const canManageAutomations = computed(() => permissions.AUTOMATION_CAN_MANAGE)+ const canViewWebhooks = computed(() => permissions.WEBHOOKS_CAN_VIEW)+ const canManageWebhooks = computed(() => permissions.WEBHOOKS_CAN_MANAGE)return {permissions,@@ -148,5 +152,7 @@ export const useGoalPermissions = () => {canManageFiles,canViewAutomations,canManageAutomations,+ canViewWebhooks,+ canManageWebhooks,}}diff --git a/web/src/composables/useInbox.ts b/web/src/composables/useInbox.tsindex 6e1a271..e61282a 100644--- a/web/src/composables/useInbox.ts+++ b/web/src/composables/useInbox.ts@@ -1,13 +1,17 @@import { computed } from 'vue'import { storeToRefs } from 'pinia'import { useGoalsStore } from '@/stores/goals.store'+import { useOrganizationStore } from '@/stores/organization.store'import type { Project } from '@/components/features/projects/types'export const useInbox = () => {const goalsStore = useGoalsStore()+ const orgStore = useOrganizationStore()const { goals } = storeToRefs(goalsStore)- const inbox = computed<Project | null>(() => goals.value.find(g => g.isInbox) ?? null)+ const isOwnInbox = (goal: Project) => goal.isInbox && goal.organizationId === orgStore.personalOrg?.id- return { inbox }+ const inbox = computed<Project | null>(() => goals.value.find(isOwnInbox) ?? null)++ return { inbox, isOwnInbox }}diff --git a/web/src/composables/useOrgSwitcher.ts b/web/src/composables/useOrgSwitcher.tsindex e9e2fd0..f2c1262 100644--- a/web/src/composables/useOrgSwitcher.ts+++ b/web/src/composables/useOrgSwitcher.ts@@ -8,13 +8,17 @@ export function useOrgSwitcher() {const orgStore = useOrganizationStore()const goalsStore = useGoalsStore()- function switchOrg(org: Organization) {+ function activateOrg(org: Organization) {if (org.id === orgStore.currentOrg?.id) returnorgStore.setCurrentOrg(org)- // Projects are org-scoped — drop the previous org's list and refetch for the- // new one. `initialized = false` keeps the route guard from acting on stale goals.+ // `initialized = false` keeps the route guard from acting on the previous org's goals.goalsStore.initialized = falsegoalsStore.fetchGoals()+ }++ function switchOrg(org: Organization) {+ if (org.id === orgStore.currentOrg?.id) return+ activateOrg(org)router.push({ name: 'user', params: { orgSlug: org.slug } })}@@ -22,5 +26,5 @@ export function useOrgSwitcher() {return orgStore.currentOrg?.id === orgId}- return { switchOrg, isCurrentOrg }+ return { switchOrg, activateOrg, isCurrentOrg }}diff --git a/web/src/composables/useProjectRoute.ts b/web/src/composables/useProjectRoute.tsindex 16ef649..5b7e2de 100644--- a/web/src/composables/useProjectRoute.ts+++ b/web/src/composables/useProjectRoute.ts@@ -11,8 +11,8 @@ export const VIEW_ROUTES: Record<DefaultView, string> = {}const VIEW_PERMISSIONS: Record<Exclude<DefaultView, 'tasks'>, (keyof GoalPermissions)[]> = {- kanban: [AllGoalPermissions.KANBAN_CAN_VIEW, AllGoalPermissions.KANBAN_CAN_MANAGE],- graph: [AllGoalPermissions.GRAPH_CAN_VIEW, AllGoalPermissions.GRAPH_CAN_MANAGE],+ kanban: [AllGoalPermissions.KANBAN_CAN_VIEW],+ graph: [AllGoalPermissions.GRAPH_CAN_VIEW],sprints: [AllGoalPermissions.SPRINT_CAN_VIEW],}diff --git a/web/src/composables/useSelectedTaskSync.ts b/web/src/composables/useSelectedTaskSync.tsindex 82b4a41..231196b 100644--- a/web/src/composables/useSelectedTaskSync.ts+++ b/web/src/composables/useSelectedTaskSync.ts@@ -5,6 +5,22 @@ import { useGraphStore } from '@/stores/graph.store'import { useBaseScreenStore } from '@/stores/base-screen.store'import { useCalendarStore } from '@/stores/calendar.store'+export function useTaskRemovalBroadcast() {+ const kanbanStore = useKanbanStore()+ const graphStore = useGraphStore()+ const baseScreenStore = useBaseScreenStore()+ const calendarStore = useCalendarStore()++ function broadcastRemoval(taskId: number) {+ kanbanStore.removeTask(taskId)+ graphStore.removeTask(taskId)+ baseScreenStore.removeTask(taskId)+ calendarStore.removeTask(taskId)+ }++ return { broadcastRemoval }+}+// If you use it in more than one component, you need to use a shared composable// using import { createSharedComposable } from '@vueuse/core'export function useSelectedTaskSync() {@@ -26,12 +42,5 @@ export function useSelectedTaskSync() {{ deep: true },)- function broadcastRemoval(taskId: number) {- kanbanStore.removeTask(taskId)- graphStore.removeTask(taskId)- baseScreenStore.removeTask(taskId)- calendarStore.removeTask(taskId)- }-- return { broadcastRemoval }+ return useTaskRemovalBroadcast()}diff --git a/web/src/composables/useSidebarInboxLink.ts b/web/src/composables/useSidebarInboxLink.tsnew file mode 100644index 0000000..003d25c--- /dev/null+++ b/web/src/composables/useSidebarInboxLink.ts@@ -0,0 +1,44 @@+import { computed, watch } from 'vue'+import { storeToRefs } from 'pinia'+import type { RouteLocationRaw } from 'vue-router'+import { ALL_TASKS_LIST_ID } from 'taskview-api'+import { useGoalsStore } from '@/stores/goals.store'+import { useOrganizationStore } from '@/stores/organization.store'+import { useInbox } from '@/composables/useInbox'++/**+ * The Inbox lives in the personal organization only. While another organization is open+ * the sidebar still offers it and the link leads into the personal organization.+ */+export function useSidebarInboxLink() {+ const goalsStore = useGoalsStore()+ const orgStore = useOrganizationStore()+ const { inbox: currentOrgInbox } = useInbox()++ const { personalOrg } = storeToRefs(orgStore)++ watch(+ () => [goalsStore.initialized, currentOrgInbox.value, personalOrg.value] as const,+ ([initialized, inbox, personal]) => {+ if (initialized && !inbox && personal) goalsStore.fetchPersonalInbox()+ },+ { immediate: true },+ )++ const inboxId = computed(() => currentOrgInbox.value?.id ?? goalsStore.personalInbox?.id ?? null)++ const link = computed<RouteLocationRaw | null>(() => {+ if (currentOrgInbox.value) {+ return { name: 'user', params: { projectId: currentOrgInbox.value.id, listId: ALL_TASKS_LIST_ID } }+ }+ if (goalsStore.personalInbox && personalOrg.value) {+ return {+ name: 'user',+ params: { orgSlug: personalOrg.value.slug, projectId: goalsStore.personalInbox.id, listId: ALL_TASKS_LIST_ID },+ }+ }+ return null+ })++ return { link, inboxId }+}diff --git a/web/src/composables/useTaskActions.ts b/web/src/composables/useTaskActions.tsnew file mode 100644index 0000000..b22cf06--- /dev/null+++ b/web/src/composables/useTaskActions.ts@@ -0,0 +1,58 @@+import { ref } from 'vue'+import { createSharedComposable } from '@vueuse/core'+import type { Task } from 'taskview-api'+import { useGoalsStore } from '@/stores/goals.store'+import { AllGoalPermissions } from '@/types/goals.types'+import type { TaskActionsMenuRequest, TaskActionsOpenMenuArgs } from './useTaskActions.types'++const _useTaskActions = () => {+ const goalsStore = useGoalsStore()++ const actionTask = ref<Task | null>(null)+ const menuRequest = ref<TaskActionsMenuRequest | null>(null)+ const isMoveDialogOpen = ref(false)+ const isDeleteDialogOpen = ref(false)++ function canDelete(task: Task) {+ return !!goalsStore.goalMap.get(task.goalId)?.permissions[AllGoalPermissions.TASK_CAN_DELETE]+ }++ // Subtasks move only together with their parent task+ function canMove(task: Task) {+ return !task.parentId+ }++ function hasActions(task: Task) {+ return canDelete(task) || canMove(task)+ }++ function openMenu(args: TaskActionsOpenMenuArgs) {+ actionTask.value = args.task+ menuRequest.value = { point: args.point }+ }++ function requestMove(task: Task) {+ actionTask.value = task+ isMoveDialogOpen.value = true+ }++ function requestDelete(task: Task) {+ actionTask.value = task+ isDeleteDialogOpen.value = true+ }++ return {+ actionTask,+ menuRequest,+ isMoveDialogOpen,+ isDeleteDialogOpen,+ canDelete,+ canMove,+ hasActions,+ openMenu,+ requestMove,+ requestDelete,+ }+}++export const useTaskActions = createSharedComposable(_useTaskActions)diff --git a/web/src/composables/useTaskActions.types.ts b/web/src/composables/useTaskActions.types.tsnew file mode 100644index 0000000..c886ec9--- /dev/null+++ b/web/src/composables/useTaskActions.types.ts@@ -0,0 +1,11 @@+import type { Task } from 'taskview-api'+import type { TvContextMenuPoint } from '@/components/features/base/TvContextMenu.types'++export type TaskActionsOpenMenuArgs = {+ task: Task+ point: TvContextMenuPoint+}++export type TaskActionsMenuRequest = {+ point: TvContextMenuPoint+}diff --git a/web/src/composables/useThemeColors.ts b/web/src/composables/useThemeColors.tsnew file mode 100644index 0000000..98f1a5b--- /dev/null+++ b/web/src/composables/useThemeColors.ts@@ -0,0 +1,166 @@+import { computed, watch } from 'vue'+import {+ DEFAULT_THEME_NEUTRAL_COLOR,+ DEFAULT_THEME_PRIMARY_COLOR,+ THEME_NEUTRAL_COLORS,+ THEME_PRIMARY_COLORS,+ type CustomTheme,+ CUSTOM_THEME_COLOR_KEYS,+ type CustomThemePalette,+} from 'taskview-api'+import { useUiPreferencesStore } from '@/stores/uiPreferences.store'+import { buildCustomThemeCss, cssColorToHex } from '@/helpers/custom-theme'+import { paletteVarName } from '@/components/features/ui-customization/parts/theme-palette'+import type { PaletteShade } from '@/components/features/ui-customization/parts/theme-palette.types'+import type { ThemeColors, ThemeSnapshot } from '@/composables/useThemeColors.types'++const CACHE_KEY = 'tv_theme_colors'+const CUSTOM_STYLE_ID = 'tv-custom-theme'++const DEFAULT_COLORS: ThemeColors = {+ primary: DEFAULT_THEME_PRIMARY_COLOR,+ neutral: DEFAULT_THEME_NEUTRAL_COLOR,+}++const HEX_COLOR = /^#[0-9a-fA-F]{6}$/++function isCustomTheme(value: unknown): value is CustomTheme {+ const theme = value as CustomTheme | null+ return !!theme && [theme.light, theme.dark].every(+ (palette) => !!palette && CUSTOM_THEME_COLOR_KEYS.every((key) => HEX_COLOR.test(palette[key] ?? '')),+ )+}++function readCache(): ThemeSnapshot | null {+ try {+ const parsed = JSON.parse(localStorage.getItem(CACHE_KEY) ?? 'null')+ if (THEME_PRIMARY_COLORS.includes(parsed?.primary) && THEME_NEUTRAL_COLORS.includes(parsed?.neutral)) {+ return { primary: parsed.primary, neutral: parsed.neutral, customTheme: isCustomTheme(parsed.customTheme) ? parsed.customTheme : null }+ }+ } catch {+ return null+ }+ return null+}++function writeCache(snapshot: ThemeSnapshot) {+ try {+ localStorage.setItem(CACHE_KEY, JSON.stringify(snapshot))+ } catch {+ return+ }+}++function resolveShade(colors: ThemeColors, shade: PaletteShade, kind: keyof ThemeColors): string {+ const value = getComputedStyle(document.documentElement).getPropertyValue(paletteVarName(colors[kind], shade))+ return cssColorToHex(value.trim())+}++/** The palette theme expressed as custom colors, a starting point for editing a custom theme. */+function customThemeFrom(colors: ThemeColors): CustomTheme {+ const light: CustomThemePalette = {+ background: '#ffffff',+ surface: resolveShade(colors, 50, 'neutral'),+ border: resolveShade(colors, 200, 'neutral'),+ text: resolveShade(colors, 700, 'neutral'),+ accent: resolveShade(colors, 500, 'primary'),+ }+ const dark: CustomThemePalette = {+ background: resolveShade(colors, 900, 'neutral'),+ surface: resolveShade(colors, 800, 'neutral'),+ border: resolveShade(colors, 700, 'neutral'),+ text: resolveShade(colors, 200, 'neutral'),+ accent: resolveShade(colors, 400, 'primary'),+ }+ return { light, dark }+}++export function useThemeColors() {+ const store = useUiPreferencesStore()++ const colors = computed<ThemeColors>(() => ({+ primary: store.settings.primaryColor ?? DEFAULT_COLORS.primary,+ neutral: store.settings.neutralColor ?? DEFAULT_COLORS.neutral,+ }))++ const customActive = computed(() => store.settings.customThemeActive === 1 && !!store.settings.customTheme)++ const customTheme = computed(() => store.settings.customTheme ?? null)++ const isDefault = computed(+ () => !customActive.value+ && colors.value.primary === DEFAULT_COLORS.primary+ && colors.value.neutral === DEFAULT_COLORS.neutral,+ )++ function setColors(next: ThemeColors) {+ store.setSetting('primaryColor', next.primary === DEFAULT_COLORS.primary ? undefined : next.primary)+ store.setSetting('neutralColor', next.neutral === DEFAULT_COLORS.neutral ? undefined : next.neutral)+ store.setSetting('customThemeActive', undefined)+ }++ function setCustomActive(active: boolean) {+ if (active && !store.settings.customTheme) {+ store.setSetting('customTheme', customThemeFrom(colors.value))+ }+ store.setSetting('customThemeActive', active ? 1 : undefined)+ }++ function setCustomTheme(theme: CustomTheme) {+ store.setSetting('customTheme', theme)+ }++ function refillCustomTheme() {+ store.setSetting('customTheme', customThemeFrom(colors.value))+ }++ function reset() {+ setColors(DEFAULT_COLORS)+ }++ return { colors, customActive, customTheme, isDefault, setColors, setCustomActive, setCustomTheme, refillCustomTheme, reset }+}++/**+ * Applies the user's theme app-wide. The last choice is cached locally so the app+ * starts in the right colors before preferences arrive from the server.+ */+export function useThemeColorsSync() {+ const appConfig = useAppConfig()+ const store = useUiPreferencesStore()+ const { colors, customActive, customTheme } = useThemeColors()++ function applyCustom(theme: CustomTheme | null) {+ let style = document.getElementById(CUSTOM_STYLE_ID)+ if (!theme) {+ style?.remove()+ return+ }+ if (!style) {+ style = document.createElement('style')+ style.id = CUSTOM_STYLE_ID+ document.head.appendChild(style)+ }+ style.textContent = buildCustomThemeCss(theme)+ }++ function apply(snapshot: ThemeSnapshot) {+ appConfig.ui.colors.primary = snapshot.primary+ appConfig.ui.colors.neutral = snapshot.neutral+ applyCustom(snapshot.customTheme)+ }++ const cached = readCache()+ if (cached) apply(cached)++ watch(+ () => [store.loaded, colors.value, customActive.value, customTheme.value] as const,+ ([loaded, next, active, theme]) => {+ if (!loaded) return+ const snapshot: ThemeSnapshot = { ...next, customTheme: active ? theme : null }+ apply(snapshot)+ writeCache(snapshot)+ },+ { immediate: true, deep: true },+ )+}diff --git a/web/src/composables/useThemeColors.types.ts b/web/src/composables/useThemeColors.types.tsnew file mode 100644index 0000000..8946a5f--- /dev/null+++ b/web/src/composables/useThemeColors.types.ts@@ -0,0 +1,10 @@+import type { CustomTheme, ThemeNeutralColor, ThemePrimaryColor } from 'taskview-api'++export type ThemeColors = {+ primary: ThemePrimaryColor+ neutral: ThemeNeutralColor+}++export type ThemeSnapshot = ThemeColors & {+ customTheme: CustomTheme | null+}diff --git a/web/src/helpers/custom-theme.ts b/web/src/helpers/custom-theme.tsnew file mode 100644index 0000000..b27a543--- /dev/null+++ b/web/src/helpers/custom-theme.ts@@ -0,0 +1,81 @@+import type { CustomTheme, CustomThemePalette } from 'taskview-api'++const NEUTRAL_SHADES = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950] as const++const INK_SHARE: Record<(typeof NEUTRAL_SHADES)[number], number> = {+ 50: 3, 100: 7, 200: 15, 300: 28, 400: 45, 500: 58, 600: 70, 700: 80, 800: 88, 900: 95, 950: 100,+}++const PRIMARY_MIX: Record<(typeof NEUTRAL_SHADES)[number], string> = {+ 50: 'white 90%', 100: 'white 80%', 200: 'white 60%', 300: 'white 40%', 400: 'white 20%', 500: 'white 0%',+ 600: 'black 15%', 700: 'black 30%', 800: 'black 45%', 900: 'black 60%', 950: 'black 75%',+}++function mix(a: string, b: string, aShare: number): string {+ return `color-mix(in oklab, ${a} ${aShare}%, ${b})`+}++function paletteDeclarations(palette: CustomThemePalette, dark: boolean): string[] {+ const { background, surface, border, text, accent } = palette+ const paper = dark ? text : background+ const ink = dark ? background : text+ const strong = dark ? 'white' : 'black'+ const highlighted = mix(text, strong, 50)++ return [+ ...NEUTRAL_SHADES.map((shade) => `--ui-color-neutral-${shade}: ${mix(ink, paper, INK_SHARE[shade])};`),+ ...NEUTRAL_SHADES.map((shade) => `--ui-color-primary-${shade}: color-mix(in oklab, ${accent}, ${PRIMARY_MIX[shade]});`),+ `--ui-primary: ${accent};`,+ `--ui-bg: ${background};`,+ `--ui-bg-muted: ${surface};`,+ `--ui-bg-elevated: ${surface};`,+ `--tv-ui-bg-elevated: ${surface};`,+ `--ui-bg-accented: ${mix(surface, text, 88)};`,+ `--ui-bg-inverted: ${highlighted};`,+ `--ui-border: ${border};`,+ `--ui-border-muted: ${border};`,+ `--ui-border-accented: ${mix(border, text, 85)};`,+ `--ui-border-inverted: ${highlighted};`,+ `--ui-text: ${text};`,+ `--ui-text-highlighted: ${highlighted};`,+ `--ui-text-toned: ${mix(text, background, 85)};`,+ `--ui-text-muted: ${mix(text, background, 62)};`,+ `--ui-text-dimmed: ${mix(text, background, 45)};`,+ `--ui-text-inverted: ${background};`,+ ]+}++/** Unlayered rules, so they win over Nuxt UI's layered tokens in both color modes. */+export function buildCustomThemeCss(theme: CustomTheme): string {+ return [+ `:root:not(.dark) {\n ${paletteDeclarations(theme.light, false).join('\n ')}\n}`,+ `:root.dark {\n ${paletteDeclarations(theme.dark, true).join('\n ')}\n}`,+ ].join('\n')+}++export function cssColorToHex(color: string): string {+ const canvas = document.createElement('canvas')+ canvas.width = 1+ canvas.height = 1+ const ctx = canvas.getContext('2d', { willReadFrequently: true })+ if (!ctx) return '#000000'+ ctx.fillStyle = '#000000'+ ctx.fillStyle = color+ ctx.fillRect(0, 0, 1, 1)+ const [r, g, b] = ctx.getImageData(0, 0, 1, 1).data+ return `#${[r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('')}`+}++function relativeLuminance(hex: string): number {+ const [r, g, b] = [1, 3, 5].map((i) => {+ const c = parseInt(hex.slice(i, i + 2), 16) / 255+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4+ })+ return 0.2126 * r + 0.7152 * g + 0.0722 * b+}++/** WCAG contrast ratio between two #rrggbb colors, 1..21. */+export function contrastRatio(a: string, b: string): number {+ const [hi, lo] = [relativeLuminance(a), relativeLuminance(b)].sort((x, y) => y - x)+ return (hi + 0.05) / (lo + 0.05)+}diff --git a/web/src/layouts/UserLayout.vue b/web/src/layouts/UserLayout.vueindex 08931d3..97a0884 100644--- a/web/src/layouts/UserLayout.vue+++ b/web/src/layouts/UserLayout.vue@@ -13,6 +13,8 @@<!-- Single global search palette; activators (SearchActivator) trigger it. --><SearchAll />++ <AppShortcuts /></UDashboardGroup><TvMobileBottomNav />@@ -33,12 +35,14 @@ import DashboardSidebarFirst from '@/components/sidebars/DashboardSidebarFirst.vimport DashboardSidebarSecond from '@/components/sidebars/DashboardSidebarSecond.vue'import TvMobileBottomNav from '@/components/features/base/TvMobileBottomNav.vue'import SearchAll from '@/components/features/main/screen-main/parts/SearchAll.vue'+import AppShortcuts from '@/components/features/shortcuts/AppShortcuts.vue'import { useCentrifugo } from '@/composables/useCentrifugo'import { usePushNotifications } from '@/composables/usePushNotifications'import { useWidgetSnapshot } from '@/composables/useWidgetSnapshot'import { useWidgetDeepLink } from '@/composables/useWidgetDeepLink'import { useGoalsStore } from '@/stores/goals.store'import { useOrganizationStore } from '@/stores/organization.store'+import { useOrgSwitcher } from '@/composables/useOrgSwitcher'import { useTimeTrackingStore } from '@/stores/time-tracking.store'import { useUiPreferencesStore } from '@/stores/uiPreferences.store'@@ -64,6 +68,16 @@ watch()const route = useRoute()const router = useRouter()+const { activateOrg } = useOrgSwitcher()++watch(+ () => route.params.orgSlug as string | undefined,+ (slug) => {+ if (!slug || !orgStore.initialized) return+ const org = orgStore.findOrgBySlug(slug)+ if (org) activateOrg(org)+ },+)watch(() => [goalsStore.initialized, goalsStore.goals, route.params.projectId] as const,diff --git a/web/src/locales/de.ts b/web/src/locales/de.tsindex 468eb02..95c2ae8 100644--- a/web/src/locales/de.ts+++ b/web/src/locales/de.ts@@ -49,6 +49,7 @@ export default {passwordResetSuccess: 'Ihr Passwort wurde erfolgreich geändert. Sie können sich jetzt anmelden.',invalidResetLink: 'Ungültiger Link',invalidResetLinkDescription: 'Der Link zum Zurücksetzen des Passworts ist ungültig oder abgelaufen.',+ requestNewResetLink: 'Neuen Link anfordern',canNotResetPassword: 'Passwort konnte nicht zurückgesetzt werden. Bitte versuchen Sie es erneut.',passwordTooShort: 'Das Passwort muss mindestens 6 Zeichen lang sein',passwordsDoNotMatch: 'Passwörter stimmen nicht überein',@@ -154,6 +155,9 @@ export default {editColumn: 'Spalte bearbeiten',columnName: 'Spaltenname',loadMore: 'Mehr laden',+ moveLeft: 'Nach links verschieben',+ moveRight: 'Nach rechts verschieben',+ moveFailed: 'Die Reihenfolge der Spalten konnte nicht geändert werden',sprintFilter: {all: 'Alle Aufgaben',current: 'Aktueller Sprint',@@ -484,6 +488,7 @@ export default {webhooks: {title: 'Webhooks',selectProject: 'Wählen Sie ein Projekt, um Webhooks zu verwalten',+ noAccess: 'Sie haben keine Berechtigung, die Webhooks dieses Projekts anzusehen.',add: 'Webhook hinzufügen',empty: 'Noch keine Webhooks. Fügen Sie einen Webhook hinzu, um Ereignisbenachrichtigungen zu erhalten.',url: 'URL',@@ -586,6 +591,7 @@ export default {addTag: 'Tag hinzufügen',subtasks: 'Unteraufgaben',addSubtask: 'Unteraufgabe hinzufügen',+ subtasksProgress: 'Unteraufgaben: {done} von {total} erledigt',notFound: 'Aufgabe nicht gefunden',copyId: 'Aufgaben-ID kopieren',idCopied: 'Aufgaben-ID kopiert',@@ -601,6 +607,7 @@ export default {sortLowestFirst: 'Niedrigste zuerst',deleteConfirm: 'Aufgabe löschen',deleteMessage: 'Sind Sie sicher, dass Sie "{name}" löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.',+ actions: 'Aufgabenaktionen',move: {button: 'Verschieben',title: 'Aufgabe in ein anderes Projekt verschieben',@@ -691,7 +698,23 @@ export default {reset: 'Zurücksetzen',apply: 'Anwenden',},+ shortcuts: {+ title: 'Tastenkürzel',+ description: 'Kürzel funktionieren am Computer und werden beim Tippen ignoriert.',+ turnedOff: 'Tastenkürzel sind ausgeschaltet',+ openSettings: 'Einschalten',+ scope: {+ global: 'Überall',+ task: 'Geöffnete Aufgabe',+ },+ addTask: 'Neue Aufgabe',+ search: 'Suche',+ showShortcuts: 'Tastenkürzel anzeigen',+ close: 'Dialog oder geöffnete Aufgabe schließen',+ toggleComplete: 'Erledigen oder wieder öffnen',+ },userMenu: {+ shortcuts: 'Tastenkürzel',profile: 'Profil',appearance: 'Erscheinungsbild',light: 'Hell',@@ -806,6 +829,8 @@ export default {cancel: 'Abbrechen',deleted: 'Konto gelöscht',codeSendError: 'Code konnte nicht gesendet werden. Bitte wenden Sie sich an den Support, um Ihr Konto zu löschen.',+ deletionDisabled: 'Das Löschen von Konten ist auf diesem Server deaktiviert. Wenden Sie sich an Ihren Administrator, um Ihr Konto zu entfernen.',+ deleteCodeInvalid: 'Der Code ist falsch oder abgelaufen. Fordern Sie einen neuen an.',password: 'Passwort',passwordDescription: 'Legen Sie das Passwort für die Anmeldung per E-Mail fest oder ändern Sie es. Wir senden einen Bestätigungscode an Ihre E-Mail.',passwordDescriptionByPassword: 'Ändern Sie Ihr Anmeldepasswort. Bestätigen Sie die Änderung mit Ihrem aktuellen Passwort.',@@ -880,8 +905,83 @@ export default {analyticsIndicators: 'Analyse – Kennzahlen',analyticsCharts: 'Analyse – Diagramme',tasks: 'Aufgaben',+ theme: 'Farben',others: 'Sonstiges',},+ theme: {+ navTitle: 'Oberflächenfarben',+ presetsTitle: 'Fertige Themes',+ presetsHint: 'Akzent- und Neutralfarbe mit einem Klick.',+ primaryTitle: 'Akzentfarbe',+ primaryHint: 'Schaltflächen, Links, ausgewählte Elemente und Schalter.',+ neutralTitle: 'Neutralfarbe',+ neutralHint: 'Hintergründe, Rahmen und sekundärer Text.',+ reset: 'Standardfarben wiederherstellen',+ presets: {+ taskview: 'TaskView',+ forest: 'Wald',+ ocean: 'Ozean',+ lagoon: 'Lagune',+ dusk: 'Dämmerung',+ lavender: 'Lavendel',+ raspberry: 'Himbeere',+ sunset: 'Sonnenuntergang',+ honey: 'Honig',+ },+ custom: {+ title: 'Eigenes Theme',+ hint: 'Hintergrund, Karten, Rahmen, Text und Akzent selbst festlegen — getrennt für hellen und dunklen Modus.',+ light: 'Hell',+ dark: 'Dunkel',+ refill: 'Farben des aktuellen Themes übernehmen',+ otherModeLight: 'Der dunkle Modus ist aktiv: Änderungen am hellen Theme sind nach dem Umschalten sichtbar.',+ otherModeDark: 'Der helle Modus ist aktiv: Änderungen am dunklen Theme sind nach dem Umschalten sichtbar.',+ pickColor: 'Farbe wählen: {name}',+ lowContrast: 'Text ist schwer lesbar: Kontrast {ratio}:1, mindestens 4.5:1 ist nötig. Erhöhe den Kontrast zwischen Text und Hintergrund.',+ fields: {+ background: 'Hintergrund',+ backgroundHint: 'Haupthintergrund der Seiten',+ surface: 'Karten',+ surfaceHint: 'Karten, Seitenleiste und Eingabefelder',+ border: 'Rahmen',+ borderHint: 'Trennlinien und Umrandungen',+ text: 'Text',+ textHint: 'Haupttext; sekundärer Text wird daraus abgeleitet',+ accent: 'Akzent',+ accentHint: 'Schaltflächen, Links und ausgewählte Elemente',+ },+ },+ colorNames: {+ red: 'Rot',+ orange: 'Orange',+ amber: 'Bernstein',+ yellow: 'Gelb',+ lime: 'Limette',+ green: 'Grün',+ emerald: 'Smaragd',+ teal: 'Blaugrün',+ cyan: 'Cyan',+ sky: 'Himmelblau',+ blue: 'Blau',+ indigo: 'Indigo',+ violet: 'Violett',+ purple: 'Lila',+ fuchsia: 'Fuchsia',+ pink: 'Pink',+ rose: 'Rosé',+ slate: 'Schiefer',+ gray: 'Grau',+ zinc: 'Zink',+ neutral: 'Neutral',+ stone: 'Stein',+ moss: 'Moos',+ tide: 'Brandung',+ ink: 'Tinte',+ plum: 'Pflaume',+ wine: 'Wein',+ sand: 'Sand',+ },+ },others: {weekStart: 'Erster Wochentag',weekStartHint: 'Gilt für alle Kalender-Datumsauswahlen.',@@ -894,12 +994,15 @@ export default {saturday: 'Samstag',sunday: 'Sonntag',defaultProject: 'Standardprojekt',+ defaultProjectUnavailable: 'Das Standardprojekt ist nicht mehr verfügbar',defaultProjectHint: 'Dieses Projekt direkt nach der Anmeldung öffnen.',defaultProjectNone: 'Startbildschirm (Standard)',defaultView: 'Standardansicht',defaultViewHint: 'Welche Ansicht beim Öffnen eines Projekts angezeigt wird.',showTaskId: 'Aufgaben-ID anzeigen',showTaskIdHint: 'Zeigt die Aufgabennummer (#163) auf Karten und in Listen; Klick kopiert sie.',+ keyboardShortcuts: 'Tastenkürzel',+ keyboardShortcutsHint: 'C fügt eine Aufgabe hinzu, X erledigt die geöffnete, ? zeigt alle Kürzel. Nur am Computer.',viewTasks: 'Aufgaben',viewKanban: 'Kanban',viewGraph: 'Graph',@@ -1026,6 +1129,7 @@ export default {6: 'Organisation',7: 'Dateien',8: 'Automatisierungen',+ 9: 'Webhooks',},oauth: {consent: {diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 5f18b87..fbb3417 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -57,6 +57,7 @@ export default {passwordResetSuccess: 'Your password has been changed successfully. You can now sign in.',invalidResetLink: 'Invalid link',invalidResetLinkDescription: 'The password reset link is invalid or has expired.',+ requestNewResetLink: 'Request a new link',canNotResetPassword: 'Could not reset password. Please try again.',passwordTooShort: 'Password must be at least 6 characters',passwordsDoNotMatch: 'Passwords do not match',@@ -168,6 +169,9 @@ export default {editColumn: 'Edit column',columnName: 'Column name',loadMore: 'Load more',+ moveLeft: 'Move left',+ moveRight: 'Move right',+ moveFailed: 'Could not change the column order',sprintFilter: {all: 'All tasks',current: 'Current sprint',@@ -498,6 +502,7 @@ export default {webhooks: {title: 'Webhooks',selectProject: 'Select a project to manage webhooks',+ noAccess: 'You do not have permission to view webhooks of this project.',add: 'Add Webhook',empty: 'No webhooks yet. Add a webhook to receive event notifications.',url: 'URL',@@ -600,6 +605,7 @@ export default {addTag: 'Add tag',subtasks: 'Subtasks',addSubtask: 'Add subtask',+ subtasksProgress: 'Subtasks: {done} of {total} done',notFound: 'Task not found',copyId: 'Copy task ID',idCopied: 'Task ID copied',@@ -615,6 +621,7 @@ export default {sortLowestFirst: 'Lowest first',deleteConfirm: 'Delete Task',deleteMessage: 'Are you sure you want to delete "{name}"? This action cannot be undone.',+ actions: 'Task actions',move: {button: 'Move',title: 'Move task to another project',@@ -705,7 +712,23 @@ export default {reset: 'Reset',apply: 'Apply',},+ shortcuts: {+ title: 'Keyboard shortcuts',+ description: 'Shortcuts work on a desktop screen and are ignored while you type.',+ turnedOff: 'Keyboard shortcuts are turned off',+ openSettings: 'Turn on',+ scope: {+ global: 'Everywhere',+ task: 'Open task',+ },+ addTask: 'New task',+ search: 'Search',+ showShortcuts: 'Show keyboard shortcuts',+ close: 'Close a dialog or the open task',+ toggleComplete: 'Mark complete or reopen',+ },userMenu: {+ shortcuts: 'Keyboard shortcuts',profile: 'Profile',appearance: 'Appearance',light: 'Light',@@ -820,6 +843,8 @@ export default {cancel: 'Cancel',deleted: 'Account deleted',codeSendError: 'Unable to send the code. Please contact support to delete your account.',+ deletionDisabled: 'Account deletion is turned off on this server. Contact your administrator to remove your account.',+ deleteCodeInvalid: 'The code is wrong or has expired. Request a new one.',password: 'Password',passwordDescription: 'Set or change the password you use to sign in with your email. We will send a confirmation code to your email.',passwordDescriptionByPassword: 'Change the password you use to sign in. Confirm the change with your current password.',@@ -894,8 +919,83 @@ export default {analyticsIndicators: 'Analytics — Indicators',analyticsCharts: 'Analytics — Charts',tasks: 'Tasks',+ theme: 'Colors',others: 'Others',},+ theme: {+ navTitle: 'Interface colors',+ presetsTitle: 'Ready-made themes',+ presetsHint: 'Accent and neutral color in one click.',+ primaryTitle: 'Accent color',+ primaryHint: 'Buttons, links, selected items and switches.',+ neutralTitle: 'Neutral color',+ neutralHint: 'Backgrounds, borders and secondary text.',+ reset: 'Restore default colors',+ presets: {+ taskview: 'TaskView',+ forest: 'Forest',+ ocean: 'Ocean',+ lagoon: 'Lagoon',+ dusk: 'Dusk',+ lavender: 'Lavender',+ raspberry: 'Raspberry',+ sunset: 'Sunset',+ honey: 'Honey',+ },+ custom: {+ title: 'Custom theme',+ hint: 'Set the background, cards, borders, text and accent yourself — separately for light and dark mode.',+ light: 'Light',+ dark: 'Dark',+ refill: 'Use current theme colors',+ otherModeLight: 'Dark mode is on: changes to the light theme show up after you switch.',+ otherModeDark: 'Light mode is on: changes to the dark theme show up after you switch.',+ pickColor: 'Pick color: {name}',+ lowContrast: 'Text is hard to read: contrast is {ratio}:1, at least 4.5:1 is needed. Increase the contrast between text and background.',+ fields: {+ background: 'Background',+ backgroundHint: 'Main page background',+ surface: 'Cards',+ surfaceHint: 'Cards, sidebar and inputs',+ border: 'Borders',+ borderHint: 'Dividers and outlines',+ text: 'Text',+ textHint: 'Main text; secondary text is derived from it',+ accent: 'Accent',+ accentHint: 'Buttons, links and selected items',+ },+ },+ colorNames: {+ red: 'Red',+ orange: 'Orange',+ amber: 'Amber',+ yellow: 'Yellow',+ lime: 'Lime',+ green: 'Green',+ emerald: 'Emerald',+ teal: 'Teal',+ cyan: 'Cyan',+ sky: 'Sky',+ blue: 'Blue',+ indigo: 'Indigo',+ violet: 'Violet',+ purple: 'Purple',+ fuchsia: 'Fuchsia',+ pink: 'Pink',+ rose: 'Rose',+ slate: 'Slate',+ gray: 'Gray',+ zinc: 'Zinc',+ neutral: 'Neutral',+ stone: 'Stone',+ moss: 'Moss',+ tide: 'Tide',+ ink: 'Ink',+ plum: 'Plum',+ wine: 'Wine',+ sand: 'Sand',+ },+ },others: {weekStart: 'First day of week',weekStartHint: 'Applies to all calendar date pickers.',@@ -908,12 +1008,15 @@ export default {saturday: 'Saturday',sunday: 'Sunday',defaultProject: 'Default project',+ defaultProjectUnavailable: 'The default project is no longer available',defaultProjectHint: 'Open this project right after signing in.',defaultProjectNone: 'Home screen (default)',defaultView: 'Default view',defaultViewHint: 'Which view to open when you enter a project.',showTaskId: 'Show task ID',showTaskIdHint: 'Show the task number (#163) on cards and list rows; click to copy.',+ keyboardShortcuts: 'Keyboard shortcuts',+ keyboardShortcutsHint: 'Press C to add a task, X to complete the open one, ? for the full list. Desktop only.',viewTasks: 'Tasks',viewKanban: 'Kanban',viewGraph: 'Graph',@@ -1040,6 +1143,7 @@ export default {6: 'Organization',7: 'Files',8: 'Automations',+ 9: 'Webhooks',},oauth: {consent: {diff --git a/web/src/locales/es.ts b/web/src/locales/es.tsindex 9d235ec..5364c33 100644--- a/web/src/locales/es.ts+++ b/web/src/locales/es.ts@@ -49,6 +49,7 @@ export default {passwordResetSuccess: 'Tu contraseña se ha cambiado correctamente. Ya puedes iniciar sesión.',invalidResetLink: 'Enlace inválido',invalidResetLinkDescription: 'El enlace para restablecer la contraseña es inválido o ha caducado.',+ requestNewResetLink: 'Solicitar un nuevo enlace',canNotResetPassword: 'No se pudo restablecer la contraseña. Inténtalo de nuevo.',passwordTooShort: 'La contraseña debe tener al menos 6 caracteres',passwordsDoNotMatch: 'Las contraseñas no coinciden',@@ -154,6 +155,9 @@ export default {editColumn: 'Editar columna',columnName: 'Nombre de la columna',loadMore: 'Cargar más',+ moveLeft: 'Mover a la izquierda',+ moveRight: 'Mover a la derecha',+ moveFailed: 'No se pudo cambiar el orden de las columnas',sprintFilter: {all: 'Todas las tareas',current: 'Sprint actual',@@ -484,6 +488,7 @@ export default {webhooks: {title: 'Webhooks',selectProject: 'Selecciona un proyecto para gestionar los Webhooks',+ noAccess: 'No tienes permiso para ver los webhooks de este proyecto.',add: 'Añadir Webhook',empty: 'Aún no hay Webhooks. Añade un Webhook para recibir notificaciones de eventos.',url: 'URL',@@ -586,6 +591,7 @@ export default {addTag: 'Añadir etiqueta',subtasks: 'Subtareas',addSubtask: 'Añadir subtarea',+ subtasksProgress: 'Subtareas: {done} de {total} completadas',notFound: 'Tarea no encontrada',copyId: 'Copiar ID de la tarea',idCopied: 'ID de la tarea copiado',@@ -601,6 +607,7 @@ export default {sortLowestFirst: 'Menor primero',deleteConfirm: 'Eliminar tarea',deleteMessage: '¿Seguro que quieres eliminar "{name}"? Esta acción no se puede deshacer.',+ actions: 'Acciones de la tarea',move: {button: 'Mover',title: 'Mover la tarea a otro proyecto',@@ -691,7 +698,23 @@ export default {reset: 'Restablecer',apply: 'Aplicar',},+ shortcuts: {+ title: 'Atajos de teclado',+ description: 'Los atajos funcionan en el ordenador y se ignoran mientras escribes.',+ turnedOff: 'Los atajos de teclado están desactivados',+ openSettings: 'Activar',+ scope: {+ global: 'En todas partes',+ task: 'Tarea abierta',+ },+ addTask: 'Nueva tarea',+ search: 'Buscar',+ showShortcuts: 'Mostrar atajos de teclado',+ close: 'Cerrar un diálogo o la tarea abierta',+ toggleComplete: 'Completar o reabrir',+ },userMenu: {+ shortcuts: 'Atajos de teclado',profile: 'Perfil',appearance: 'Apariencia',light: 'Claro',@@ -806,6 +829,8 @@ export default {cancel: 'Cancelar',deleted: 'Cuenta eliminada',codeSendError: 'No se pudo enviar el código. Ponte en contacto con soporte para eliminar tu cuenta.',+ deletionDisabled: 'La eliminación de cuentas está desactivada en este servidor. Contacta con tu administrador para eliminar tu cuenta.',+ deleteCodeInvalid: 'El código es incorrecto o ha caducado. Solicita uno nuevo.',password: 'Contraseña',passwordDescription: 'Establece o cambia la contraseña para iniciar sesión con tu email. Enviaremos un código de confirmación a tu correo.',passwordDescriptionByPassword: 'Cambia la contraseña que usas para iniciar sesión. Confirma el cambio con tu contraseña actual.',@@ -880,8 +905,83 @@ export default {analyticsIndicators: 'Analíticas — Indicadores',analyticsCharts: 'Analíticas — Gráficos',tasks: 'Tareas',+ theme: 'Colores',others: 'Otros',},+ theme: {+ navTitle: 'Colores de la interfaz',+ presetsTitle: 'Temas predefinidos',+ presetsHint: 'Color de acento y neutro con un clic.',+ primaryTitle: 'Color de acento',+ primaryHint: 'Botones, enlaces, elementos seleccionados e interruptores.',+ neutralTitle: 'Color neutro',+ neutralHint: 'Fondos, bordes y texto secundario.',+ reset: 'Restaurar colores predeterminados',+ presets: {+ taskview: 'TaskView',+ forest: 'Bosque',+ ocean: 'Océano',+ lagoon: 'Laguna',+ dusk: 'Crepúsculo',+ lavender: 'Lavanda',+ raspberry: 'Frambuesa',+ sunset: 'Atardecer',+ honey: 'Miel',+ },+ custom: {+ title: 'Tema propio',+ hint: 'Define tú mismo el fondo, las tarjetas, los bordes, el texto y el acento, por separado para el modo claro y el oscuro.',+ light: 'Claro',+ dark: 'Oscuro',+ refill: 'Usar colores del tema actual',+ otherModeLight: 'El modo oscuro está activo: los cambios del tema claro se verán al cambiar de modo.',+ otherModeDark: 'El modo claro está activo: los cambios del tema oscuro se verán al cambiar de modo.',+ pickColor: 'Elegir color: {name}',+ lowContrast: 'El texto se lee mal: el contraste es {ratio}:1 y se necesita al menos 4.5:1. Aumenta el contraste entre texto y fondo.',+ fields: {+ background: 'Fondo',+ backgroundHint: 'Fondo principal de las páginas',+ surface: 'Tarjetas',+ surfaceHint: 'Tarjetas, barra lateral y campos',+ border: 'Bordes',+ borderHint: 'Separadores y contornos',+ text: 'Texto',+ textHint: 'Texto principal; el secundario se calcula a partir de él',+ accent: 'Acento',+ accentHint: 'Botones, enlaces y elementos seleccionados',+ },+ },+ colorNames: {+ red: 'Rojo',+ orange: 'Naranja',+ amber: 'Ámbar',+ yellow: 'Amarillo',+ lime: 'Lima',+ green: 'Verde',+ emerald: 'Esmeralda',+ teal: 'Verde azulado',+ cyan: 'Cian',+ sky: 'Celeste',+ blue: 'Azul',+ indigo: 'Índigo',+ violet: 'Violeta',+ purple: 'Púrpura',+ fuchsia: 'Fucsia',+ pink: 'Rosa',+ rose: 'Rosado',+ slate: 'Pizarra',+ gray: 'Gris',+ zinc: 'Zinc',+ neutral: 'Neutro',+ stone: 'Piedra',+ moss: 'Musgo',+ tide: 'Marea',+ ink: 'Tinta',+ plum: 'Ciruela',+ wine: 'Vino',+ sand: 'Arena',+ },+ },others: {weekStart: 'Primer día de la semana',weekStartHint: 'Se aplica a todos los selectores de fecha del calendario.',@@ -894,12 +994,15 @@ export default {saturday: 'Sábado',sunday: 'Domingo',defaultProject: 'Proyecto predeterminado',+ defaultProjectUnavailable: 'El proyecto predeterminado ya no está disponible',defaultProjectHint: 'Abrir este proyecto justo después de iniciar sesión.',defaultProjectNone: 'Pantalla de inicio (predeterminado)',defaultView: 'Vista predeterminada',defaultViewHint: 'Qué vista abrir al entrar en un proyecto.',showTaskId: 'Mostrar ID de la tarea',showTaskIdHint: 'Muestra el número de la tarea (#163) en tarjetas y listas; haz clic para copiarlo.',+ keyboardShortcuts: 'Atajos de teclado',+ keyboardShortcutsHint: 'C añade una tarea, X completa la abierta, ? muestra todos los atajos. Solo en ordenador.',viewTasks: 'Tareas',viewKanban: 'Kanban',viewGraph: 'Grafo',@@ -1026,6 +1129,7 @@ export default {6: 'Organización',7: 'Archivos',8: 'Automatizaciones',+ 9: 'Webhooks',},oauth: {consent: {diff --git a/web/src/locales/pt-br.ts b/web/src/locales/pt-br.tsindex 0fddd54..f357cc2 100644--- a/web/src/locales/pt-br.ts+++ b/web/src/locales/pt-br.ts@@ -57,6 +57,7 @@ export default {passwordResetSuccess: 'Sua senha foi alterada com sucesso. Agora você pode entrar.',invalidResetLink: 'Link inválido',invalidResetLinkDescription: 'O link de redefinição de senha é inválido ou expirou.',+ requestNewResetLink: 'Solicitar um novo link',canNotResetPassword: 'Não foi possível redefinir a senha. Tente novamente.',passwordTooShort: 'A senha deve ter pelo menos 6 caracteres',passwordsDoNotMatch: 'As senhas não coincidem',@@ -167,6 +168,9 @@ export default {editColumn: 'Editar coluna',columnName: 'Nome da Coluna',loadMore: 'Carregar mais',+ moveLeft: 'Mover para a esquerda',+ moveRight: 'Mover para a direita',+ moveFailed: 'Não foi possível alterar a ordem das colunas',sprintFilter: {all: 'Todas as tarefas',current: 'Sprint atual',@@ -497,6 +501,7 @@ export default {webhooks: {title: 'Webhooks',selectProject: 'Selecione um projeto para gerenciar webhooks',+ noAccess: 'Você não tem permissão para ver os webhooks deste projeto.',add: 'Adicionar Webhook',empty: 'Nenhum webhook ainda. Adicione um webhook para receber notificações de eventos.',url: 'URL',@@ -599,6 +604,7 @@ export default {addTag: 'Adicionar tag',subtasks: 'Subtarefas',addSubtask: 'Adicionar subtarefa',+ subtasksProgress: 'Subtarefas: {done} de {total} concluídas',notFound: 'Tarefa não encontrada',copyId: 'Copiar ID da tarefa',idCopied: 'ID da tarefa copiado',@@ -614,6 +620,7 @@ export default {sortLowestFirst: 'Menor primeiro',deleteConfirm: 'Excluir tarefa',deleteMessage: 'Tem certeza de que deseja excluir "{name}"? Esta ação não pode ser desfeita.',+ actions: 'Ações da tarefa',move: {button: 'Mover',title: 'Mover tarefa para outro projeto',@@ -704,7 +711,23 @@ export default {reset: 'Redefinir',apply: 'Aplicar',},+ shortcuts: {+ title: 'Atalhos de teclado',+ description: 'Os atalhos funcionam no computador e são ignorados enquanto você digita.',+ turnedOff: 'Os atalhos de teclado estão desativados',+ openSettings: 'Ativar',+ scope: {+ global: 'Em qualquer lugar',+ task: 'Tarefa aberta',+ },+ addTask: 'Nova tarefa',+ search: 'Pesquisar',+ showShortcuts: 'Mostrar atalhos de teclado',+ close: 'Fechar um diálogo ou a tarefa aberta',+ toggleComplete: 'Concluir ou reabrir',+ },userMenu: {+ shortcuts: 'Atalhos de teclado',profile: 'Perfil',appearance: 'Aparência',light: 'Claro',@@ -819,6 +842,8 @@ export default {cancel: 'Cancelar',deleted: 'Conta excluída',codeSendError: 'Não foi possível enviar o código. Entre em contato com o suporte para excluir sua conta.',+ deletionDisabled: 'A exclusão de contas está desativada neste servidor. Fale com o administrador para remover sua conta.',+ deleteCodeInvalid: 'O código está incorreto ou expirou. Solicite um novo.',password: 'Senha',passwordDescription: 'Defina ou altere a senha que você usa para fazer login com seu e-mail. Enviaremos um código de confirmação para seu e-mail.',passwordDescriptionByPassword: 'Altere a senha que você usa para fazer login. Confirme a alteração com sua senha atual.',@@ -893,8 +918,83 @@ export default {analyticsIndicators: 'Analytics — Indicadores',analyticsCharts: 'Analytics — Gráficos',tasks: 'Tarefas',+ theme: 'Cores',others: 'Others',},+ theme: {+ navTitle: 'Cores da interface',+ presetsTitle: 'Temas prontos',+ presetsHint: 'Cor de destaque e neutra com um clique.',+ primaryTitle: 'Cor de destaque',+ primaryHint: 'Botões, links, itens selecionados e interruptores.',+ neutralTitle: 'Cor neutra',+ neutralHint: 'Fundos, bordas e texto secundário.',+ reset: 'Restaurar cores padrão',+ presets: {+ taskview: 'TaskView',+ forest: 'Floresta',+ ocean: 'Oceano',+ lagoon: 'Lagoa',+ dusk: 'Crepúsculo',+ lavender: 'Lavanda',+ raspberry: 'Framboesa',+ sunset: 'Pôr do sol',+ honey: 'Mel',+ },+ custom: {+ title: 'Tema personalizado',+ hint: 'Defina você mesmo o fundo, os cartões, as bordas, o texto e o destaque, separadamente para o modo claro e o escuro.',+ light: 'Claro',+ dark: 'Escuro',+ refill: 'Usar cores do tema atual',+ otherModeLight: 'O modo escuro está ativo: as mudanças no tema claro aparecem depois de trocar o modo.',+ otherModeDark: 'O modo claro está ativo: as mudanças no tema escuro aparecem depois de trocar o modo.',+ pickColor: 'Escolher cor: {name}',+ lowContrast: 'O texto está difícil de ler: contraste de {ratio}:1, é preciso pelo menos 4.5:1. Aumente o contraste entre texto e fundo.',+ fields: {+ background: 'Fundo',+ backgroundHint: 'Fundo principal das páginas',+ surface: 'Cartões',+ surfaceHint: 'Cartões, barra lateral e campos',+ border: 'Bordas',+ borderHint: 'Divisores e contornos',+ text: 'Texto',+ textHint: 'Texto principal; o secundário é calculado a partir dele',+ accent: 'Destaque',+ accentHint: 'Botões, links e itens selecionados',+ },+ },+ colorNames: {+ red: 'Vermelho',+ orange: 'Laranja',+ amber: 'Âmbar',+ yellow: 'Amarelo',+ lime: 'Lima',+ green: 'Verde',+ emerald: 'Esmeralda',+ teal: 'Verde-azulado',+ cyan: 'Ciano',+ sky: 'Céu',+ blue: 'Azul',+ indigo: 'Índigo',+ violet: 'Violeta',+ purple: 'Roxo',+ fuchsia: 'Fúcsia',+ pink: 'Rosa',+ rose: 'Rosado',+ slate: 'Ardósia',+ gray: 'Cinza',+ zinc: 'Zinco',+ neutral: 'Neutro',+ stone: 'Pedra',+ moss: 'Musgo',+ tide: 'Maré',+ ink: 'Tinta',+ plum: 'Ameixa',+ wine: 'Vinho',+ sand: 'Areia',+ },+ },others: {weekStart: 'Primeiro dia da semana',weekStartHint: 'Aplica-se a todos os seletores de data do calendário.',@@ -907,12 +1007,15 @@ export default {saturday: 'Sábado',sunday: 'Domingo',defaultProject: 'Projeto padrão',+ defaultProjectUnavailable: 'O projeto padrão não está mais disponível',defaultProjectHint: 'Abra este projeto logo após fazer login.',defaultProjectNone: 'Tela inicial (padrão)',defaultView: 'Visualização padrão',defaultViewHint: 'Qual visualização do projeto padrão abrir.',showTaskId: 'Mostrar ID da tarefa',showTaskIdHint: 'Mostra o número da tarefa (#163) nos cartões e listas; clique para copiar.',+ keyboardShortcuts: 'Atalhos de teclado',+ keyboardShortcutsHint: 'C adiciona uma tarefa, X conclui a aberta, ? mostra todos os atalhos. Só no computador.',viewTasks: 'Tarefas',viewKanban: 'Kanban',viewGraph: 'Gráfico',@@ -1037,6 +1140,7 @@ export default {6: 'Organização',7: 'Arquivos',8: 'Automações',+ 9: 'Webhooks',},oauth: {consent: {diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.tsindex 9680b1b..be79dc2 100644--- a/web/src/locales/ru.ts+++ b/web/src/locales/ru.ts@@ -57,6 +57,7 @@ export default {passwordResetSuccess: 'Ваш пароль успешно изменён. Теперь вы можете войти.',invalidResetLink: 'Недействительная ссылка',invalidResetLinkDescription: 'Ссылка для сброса пароля недействительна или истекла.',+ requestNewResetLink: 'Запросить новую ссылку',canNotResetPassword: 'Не удалось сбросить пароль. Попробуйте снова.',passwordTooShort: 'Пароль должен содержать минимум 6 символов',passwordsDoNotMatch: 'Пароли не совпадают',@@ -168,6 +169,9 @@ export default {editColumn: 'Редактировать колонку',columnName: 'Название колонки',loadMore: 'Загрузить ещё',+ moveLeft: 'Сдвинуть влево',+ moveRight: 'Сдвинуть вправо',+ moveFailed: 'Не удалось изменить порядок колонок',sprintFilter: {all: 'Все задачи',current: 'Текущий спринт',@@ -567,6 +571,7 @@ export default {addTag: 'Добавить тег',subtasks: 'Подзадачи',addSubtask: 'Добавить подзадачу',+ subtasksProgress: 'Подзадачи: выполнено {done} из {total}',notFound: 'Задача не найдена',copyId: 'Скопировать ID задачи',idCopied: 'ID задачи скопирован',@@ -582,6 +587,7 @@ export default {sortLowestFirst: 'Сначала низкий',deleteConfirm: 'Удалить задачу',deleteMessage: 'Вы уверены, что хотите удалить "{name}"? Это действие нельзя отменить.',+ actions: 'Действия с задачей',move: {button: 'Перенести',title: 'Перенести задачу в другой проект',@@ -672,7 +678,23 @@ export default {reset: 'Сбросить',apply: 'Применить',},+ shortcuts: {+ title: 'Горячие клавиши',+ description: 'Работают на компьютере и не срабатывают, пока вы печатаете.',+ turnedOff: 'Горячие клавиши выключены',+ openSettings: 'Включить',+ scope: {+ global: 'Везде',+ task: 'Открытая задача',+ },+ addTask: 'Новая задача',+ search: 'Поиск',+ showShortcuts: 'Показать горячие клавиши',+ close: 'Закрыть окно или открытую задачу',+ toggleComplete: 'Выполнить или вернуть в работу',+ },userMenu: {+ shortcuts: 'Горячие клавиши',profile: 'Профиль',appearance: 'Оформление',light: 'Светлая',@@ -787,6 +809,8 @@ export default {cancel: 'Отмена',deleted: 'Аккаунт удалён',codeSendError: 'Не удалось отправить код. Обратитесь в поддержку для удаления аккаунта.',+ deletionDisabled: 'Удаление аккаунта отключено на этом сервере. Чтобы удалить аккаунт, обратитесь к администратору.',+ deleteCodeInvalid: 'Код неверный или истёк. Запросите новый.',password: 'Пароль',passwordDescription: 'Задайте или измените пароль для входа по email. Мы отправим код подтверждения на вашу почту.',passwordDescriptionByPassword: 'Измените пароль для входа. Подтвердите изменение текущим паролем.',@@ -861,8 +885,83 @@ export default {analyticsIndicators: 'Аналитика — показатели',analyticsCharts: 'Аналитика — графики',tasks: 'Задачи',+ theme: 'Цвета',others: 'Прочее',},+ theme: {+ navTitle: 'Цвета интерфейса',+ presetsTitle: 'Готовые темы',+ presetsHint: 'Акцентный и нейтральный цвет одним нажатием.',+ primaryTitle: 'Акцентный цвет',+ primaryHint: 'Кнопки, ссылки, выбранные пункты и переключатели.',+ neutralTitle: 'Нейтральный цвет',+ neutralHint: 'Фон, рамки и второстепенный текст.',+ reset: 'Вернуть стандартные цвета',+ presets: {+ taskview: 'TaskView',+ forest: 'Лес',+ ocean: 'Океан',+ lagoon: 'Лагуна',+ dusk: 'Сумерки',+ lavender: 'Лаванда',+ raspberry: 'Малина',+ sunset: 'Закат',+ honey: 'Мёд',+ },+ custom: {+ title: 'Своя тема',+ hint: 'Задайте фон, карточки, рамки, текст и акцент вручную — отдельно для светлого и тёмного режима.',+ light: 'Светлая',+ dark: 'Тёмная',+ refill: 'Взять цвета текущей темы',+ otherModeLight: 'Сейчас включён тёмный режим: изменения светлой темы будут видны после переключения.',+ otherModeDark: 'Сейчас включён светлый режим: изменения тёмной темы будут видны после переключения.',+ pickColor: 'Выбрать цвет: {name}',+ lowContrast: 'Текст плохо читается: контраст {ratio}:1, нужно хотя бы 4.5:1. Сделайте текст и фон контрастнее.',+ fields: {+ background: 'Фон',+ backgroundHint: 'Основной фон страниц',+ surface: 'Карточки',+ surfaceHint: 'Карточки, сайдбар и поля ввода',+ border: 'Рамки',+ borderHint: 'Разделители и обводки',+ text: 'Текст',+ textHint: 'Основной текст; второстепенный рассчитывается из него',+ accent: 'Акцент',+ accentHint: 'Кнопки, ссылки и выбранные пункты',+ },+ },+ colorNames: {+ red: 'Красный',+ orange: 'Оранжевый',+ amber: 'Янтарный',+ yellow: 'Жёлтый',+ lime: 'Лайм',+ green: 'Зелёный',+ emerald: 'Изумрудный',+ teal: 'Бирюзовый',+ cyan: 'Циан',+ sky: 'Голубой',+ blue: 'Синий',+ indigo: 'Индиго',+ violet: 'Фиолетовый',+ purple: 'Пурпурный',+ fuchsia: 'Фуксия',+ pink: 'Розовый',+ rose: 'Малиновый',+ slate: 'Сланцевый',+ gray: 'Серый',+ zinc: 'Цинковый',+ neutral: 'Нейтральный',+ stone: 'Каменный',+ moss: 'Мох',+ tide: 'Прибой',+ ink: 'Чернила',+ plum: 'Слива',+ wine: 'Вино',+ sand: 'Песок',+ },+ },others: {weekStart: 'Первый день недели',weekStartHint: 'Применяется во всех календарях выбора даты.',@@ -875,12 +974,15 @@ export default {saturday: 'Суббота',sunday: 'Воскресенье',defaultProject: 'Проект по умолчанию',+ defaultProjectUnavailable: 'Проект по умолчанию больше недоступен',defaultProjectHint: 'Открывать этот проект сразу после входа.',defaultProjectNone: 'Главный экран (по умолчанию)',defaultView: 'Вид по умолчанию',defaultViewHint: 'Какой вид открывать при переходе в проект.',showTaskId: 'Показывать ID задачи',showTaskIdHint: 'Номер задачи (#163) на карточках и в списках, по клику копируется.',+ keyboardShortcuts: 'Горячие клавиши',+ keyboardShortcutsHint: 'C — новая задача, X — выполнить открытую, ? — список всех клавиш. Только на компьютере.',viewTasks: 'Задачи',viewKanban: 'Канбан',viewGraph: 'Граф',@@ -905,6 +1007,7 @@ export default {},},webhooks: {+ noAccess: 'У вас нет прав на просмотр вебхуков этого проекта.',urlErrors: {invalid: 'Введите корректный URL',scheme: 'Поддерживаются только http и https URL',@@ -1021,6 +1124,7 @@ export default {6: 'Организация',7: 'Файлы',8: 'Автоматизации',+ 9: 'Вебхуки',},oauth: {consent: {diff --git a/web/src/shortcuts/registry.ts b/web/src/shortcuts/registry.tsnew file mode 100644index 0000000..23da3a8--- /dev/null+++ b/web/src/shortcuts/registry.ts@@ -0,0 +1,19 @@+import type { ShortcutDefinition, ShortcutScope } from './shortcuts.types'++export const SHORTCUTS = {+ addTask: { kbds: ['c'], scope: 'global', labelKey: 'shortcuts.addTask' },+ search: { kbds: ['meta', 'k'], scope: 'global', labelKey: 'shortcuts.search' },+ showShortcuts: { kbds: ['?'], scope: 'global', labelKey: 'shortcuts.showShortcuts' },+ close: { kbds: ['escape'], scope: 'global', labelKey: 'shortcuts.close' },+ toggleComplete: { kbds: ['x'], scope: 'task', labelKey: 'shortcuts.toggleComplete' },+} as const satisfies Record<string, ShortcutDefinition>++export const SHORTCUT_SCOPES: ShortcutScope[] = ['global', 'task']++export function shortcutsOfScope(scope: ShortcutScope): ShortcutDefinition[] {+ return Object.values(SHORTCUTS).filter(shortcut => shortcut.scope === scope)+}++export function shortcutBinding(shortcut: ShortcutDefinition): string {+ return shortcut.kbds.join('_')+}diff --git a/web/src/shortcuts/shortcut-guards.ts b/web/src/shortcuts/shortcut-guards.tsnew file mode 100644index 0000000..e2a57dc--- /dev/null+++ b/web/src/shortcuts/shortcut-guards.ts@@ -0,0 +1,9 @@+export const SHORTCUT_OPTIONS = { layoutIndependent: true }++export function openDialogCount(): number {+ return document.querySelectorAll('[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]').length+}++export function isPlainKeyPress(event: KeyboardEvent): boolean {+ return !event.altKey && !event.repeat+}diff --git a/web/src/shortcuts/shortcuts.types.ts b/web/src/shortcuts/shortcuts.types.tsnew file mode 100644index 0000000..dbfd539--- /dev/null+++ b/web/src/shortcuts/shortcuts.types.ts@@ -0,0 +1,14 @@+import type { Ref } from 'vue'++export type TaskShortcutsArgs = {+ canToggleComplete: Ref<boolean>+ toggleComplete: () => void+}++export type ShortcutScope = 'global' | 'task'++export type ShortcutDefinition = {+ kbds: string[]+ scope: ShortcutScope+ labelKey: string+}diff --git a/web/src/shortcuts/useShortcutsEnabled.ts b/web/src/shortcuts/useShortcutsEnabled.tsnew file mode 100644index 0000000..e631edf--- /dev/null+++ b/web/src/shortcuts/useShortcutsEnabled.ts@@ -0,0 +1,10 @@+import { computed } from 'vue'+import { useTaskView } from '@/composables/useTaskView'+import { useUiPreferencesStore } from '@/stores/uiPreferences.store'++export function useShortcutsEnabled() {+ const { isDesktop } = useTaskView()+ const uiPreferencesStore = useUiPreferencesStore()++ return computed(() => isDesktop.value && uiPreferencesStore.settings.keyboardShortcuts !== 0)+}diff --git a/web/src/shortcuts/useShortcutsHelp.ts b/web/src/shortcuts/useShortcutsHelp.tsnew file mode 100644index 0000000..170d3af--- /dev/null+++ b/web/src/shortcuts/useShortcutsHelp.ts@@ -0,0 +1,13 @@+import { ref } from 'vue'+import { createSharedComposable } from '@vueuse/core'++export const useShortcutsHelp = createSharedComposable(() => {+ const isOpen = ref(false)++ return {+ isOpen,+ open: () => {+ isOpen.value = true+ },+ }+})diff --git a/web/src/shortcuts/useTaskShortcuts.ts b/web/src/shortcuts/useTaskShortcuts.tsnew file mode 100644index 0000000..f117bfc--- /dev/null+++ b/web/src/shortcuts/useTaskShortcuts.ts@@ -0,0 +1,16 @@+import { SHORTCUT_OPTIONS, isPlainKeyPress, openDialogCount } from './shortcut-guards'+import { SHORTCUTS, shortcutBinding } from './registry'+import { useShortcutsEnabled } from './useShortcutsEnabled'+import type { TaskShortcutsArgs } from './shortcuts.types'++export function useTaskShortcuts(args: TaskShortcutsArgs) {+ const enabled = useShortcutsEnabled()++ function toggleComplete(event: KeyboardEvent) {+ if (!enabled.value || !isPlainKeyPress(event) || !args.canToggleComplete.value) return+ if (openDialogCount() > 1) return+ args.toggleComplete()+ }++ defineShortcuts({ [shortcutBinding(SHORTCUTS.toggleComplete)]: toggleComplete }, SHORTCUT_OPTIONS)+}diff --git a/web/src/stores/goals.store.ts b/web/src/stores/goals.store.tsindex 060cddd..fa04bec 100644--- a/web/src/stores/goals.store.ts+++ b/web/src/stores/goals.store.ts@@ -11,6 +11,7 @@ export const useGoalsStore = defineStore('goals', {loading: false,selectedItemId: -1,goals: [],+ personalInbox: null,}),getters: {goalMap: (state) => {@@ -33,11 +34,26 @@ export const useGoalsStore = defineStore('goals', {},},actions: {+ async fetchPersonalInbox(): Promise<void> {+ const orgStore = useOrganizationStore()+ const personal = orgStore.personalOrg+ if (!personal || this.personalInbox?.organizationId === personal.id) return++ const goals = await $tvApi.goals.fetchGoals(personal.id)+ this.personalInbox = goals?.find((goal) => goal.isInbox && goal.organizationId === personal.id) ?? null+ },+async fetchGoals(): Promise<void> {if (this.loading) returnthis.loading = trueconst orgStore = useOrganizationStore()- const result = await $tvApi.goals.fetchGoals(orgStore.currentOrg?.id)+ const orgId = orgStore.currentOrg?.id+ const result = await $tvApi.goals.fetchGoals(orgId)+ if (orgStore.currentOrg?.id !== orgId) {+ // The organization changed while loading — this answer belongs to the previous one.+ this.loading = false+ return this.fetchGoals()+ }if (!result) {this.loading = falsereturndiff --git a/web/src/stores/kanban.store.ts b/web/src/stores/kanban.store.tsindex 2c1e546..c69d113 100644--- a/web/src/stores/kanban.store.ts+++ b/web/src/stores/kanban.store.ts@@ -1,7 +1,7 @@import { defineStore } from 'pinia'import type { GoalItem, KanbanArgDeleteColumn, KanbanArgUpdateColumn, KanbanArgUpdateTasksOrder, KanbanColumnItem, KanbanFilters, TaskArgAdd, KanbanArgAddColumn } from 'taskview-api'import { DEFAULT_ID } from '@/types/app.types'-import type { KanbanStoreState } from '@/types/kanban.types'+import type { KanbanMoveStatusArgs, KanbanStoreState } from '@/types/kanban.types'import { $tvApi } from '@/plugins/axios'import { TaskItem } from '@/types/tasks.types'import { hasActiveFilters } from '@/helpers/Helper'@@ -125,6 +125,31 @@ export const useKanbanStore = defineStore('kanban', {}},+ async moveStatus(args: KanbanMoveStatusArgs): Promise<boolean> {+ const backlog = this.statuses.filter((stat) => stat.id === DEFAULT_ID)+ const columns = this.statuses.filter((stat) => stat.id !== DEFAULT_ID)+ const index = columns.findIndex((stat) => stat.id === args.statusId)+ const target = args.direction === 'left' ? index - 1 : index + 1+ if (index === -1 || target < 0 || target >= columns.length) return false++ const previous = [...this.statuses]+ const [moved] = columns.splice(index, 1)+ columns.splice(target, 0, moved)+ this.statuses = [...backlog, ...columns]++ try {+ const saved = await $tvApi.kanban.reorderColumns({+ goalId: this.goalId,+ statusIds: columns.map((stat) => stat.id),+ })+ this.statuses = [...backlog, ...saved]+ return true+ } catch {+ this.statuses = previous+ return false+ }+ },+async updateStatus(data: KanbanArgUpdateColumn) {const result = await $tvApi.kanban.updateColumn(data)if (!result) {diff --git a/web/src/stores/organization.store.ts b/web/src/stores/organization.store.tsindex 1b55c2c..b922a7e 100644--- a/web/src/stores/organization.store.ts+++ b/web/src/stores/organization.store.ts@@ -2,6 +2,7 @@ import { defineStore } from 'pinia'import { ref, computed } from 'vue'import type { Organization, OrgMember } from 'taskview-api'import { $tvApi } from '@/plugins/axios'+import { useUserStore } from '@/stores/user.store'export const useOrganizationStore = defineStore('organization', () => {const organizations = ref<Organization[]>([])@@ -10,7 +11,12 @@ export const useOrganizationStore = defineStore('organization', () => {const loading = ref(false)const initialized = ref(false)+ const userStore = useUserStore()+const currentOrgSlug = computed(() => currentOrg.value?.slug ?? '')+ const personalOrg = computed(() =>+ organizations.value.find(o => o.isPersonal && o.ownerId === userStore.payloadData?.id) ?? null,+ )function findOrgBySlug(slug: string) {return organizations.value.find(o => o.slug === slug) ?? null@@ -139,6 +145,7 @@ export const useOrganizationStore = defineStore('organization', () => {organizations,currentOrg,currentOrgSlug,+ personalOrg,members,loading,initialized,diff --git a/web/src/stores/tag.store.ts b/web/src/stores/tag.store.tsindex 7cebf33..ab9a7f0 100644--- a/web/src/stores/tag.store.ts+++ b/web/src/stores/tag.store.ts@@ -39,10 +39,7 @@ export const useTagsStore = defineStore('tags', {return}this.tags = tags-- this.tags.forEach((tag) => {- this.tagsMap.set(tag.id, tag)- })+ this.tagsMap = new Map(tags.map((tag) => [tag.id, tag]))},async addTag(tagData: TagItemArgAdd): Promise<boolean> {diff --git a/web/src/stores/uiPreferences.store.ts b/web/src/stores/uiPreferences.store.tsindex f841d25..7aca0f0 100644--- a/web/src/stores/uiPreferences.store.ts+++ b/web/src/stores/uiPreferences.store.ts@@ -49,15 +49,19 @@ export const useUiPreferencesStore = defineStore('uiPreferences', () => {await fetch().catch(() => undefined)}- const flush = useDebounceFn(async () => {+ let revision = 0+ let saveChain: Promise<void> = Promise.resolve()++ async function save() {saving.value = true+ const sentRevision = revisiontry {const payload: UiPreferences = { ...prefs.value }if (Object.keys(settings.value).length > 0) {payload[UI_SETTINGS_KEY] = settings.value}const result = await $tvApi.uiPreferences.update(payload)- if (result) {+ if (result && sentRevision === revision) {const { sections, settings: s } = split(result)prefs.value = sectionssettings.value = s@@ -65,10 +69,16 @@ export const useUiPreferencesStore = defineStore('uiPreferences', () => {} finally {saving.value = false}+ }++ const flush = useDebounceFn(() => {+ saveChain = saveChain.then(save, save)+ return saveChain}, SAVE_DEBOUNCE_MS)function setSection(section: string, items: UiPreferencesItem[]) {prefs.value = { ...prefs.value, [section]: items }+ revision++flush()}@@ -78,6 +88,7 @@ export const useUiPreferencesStore = defineStore('uiPreferences', () => {function setSetting<K extends keyof UiSettings>(key: K, value: UiSettings[K]) {settings.value = { ...settings.value, [key]: value }+ revision++flush()}diff --git a/web/src/types/collaboration-permissions.types.ts b/web/src/types/collaboration-permissions.types.tsindex 36bd214..6cc0dc5 100644--- a/web/src/types/collaboration-permissions.types.ts+++ b/web/src/types/collaboration-permissions.types.ts@@ -1,7 +1,7 @@import type { CollaborationPermission } from 'taskview-api'import type { TI18nLocalesInApp } from './app.types'-export type PermissioinGroupsIds = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;+export type PermissioinGroupsIds = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;export const PermissionGroups: Record<PermissioinGroupsIds, Record<keyof TI18nLocalesInApp, string>> = {1: { en: 'Applicarion level', ru: 'Уровня приложения' },@@ -12,6 +12,7 @@ export const PermissionGroups: Record<PermissioinGroupsIds, Record<keyof TI18nLo6: { en: 'Organization', ru: 'Организация' },7: { en: 'Files', ru: 'Файлы' },8: { en: 'Automations', ru: 'Автоматизации' },+ 9: { en: 'Webhooks', ru: 'Вебхуки' },}export type CollaborationPermissionsState = {diff --git a/web/src/types/goals.types.ts b/web/src/types/goals.types.tsindex 99ec21a..eb250fb 100644--- a/web/src/types/goals.types.ts+++ b/web/src/types/goals.types.ts@@ -22,6 +22,8 @@ export type GoalsStoreState = {loading: boolean;selectedItemId: GoalItem['id'];goals: GoalItem[];+ /** Inbox of the user's personal organization, loaded while another organization is open */+ personalInbox: GoalItem | null;};export type GoalEventMoreMenu = {diff --git a/web/src/types/graph.types.ts b/web/src/types/graph.types.tsindex a6ab10f..78a0a3d 100644--- a/web/src/types/graph.types.ts+++ b/web/src/types/graph.types.ts@@ -26,6 +26,13 @@ export type GraphPositionNearArgs = {side: GraphPlacementSide;};+export type GraphPlaceNodeFreeArgs = {+ /** wanted top-left corner of the new node */+ target: XYPosition;+ node: Pick<Node, 'data'>;+ obstacles: Node[];+};+export type GraphPlaceNodeNearArgs = {anchor: Node;node: Pick<Node, 'data'>;diff --git a/web/src/types/kanban.types.ts b/web/src/types/kanban.types.tsindex 0b4bcce..0979228 100644--- a/web/src/types/kanban.types.ts+++ b/web/src/types/kanban.types.ts@@ -8,4 +8,8 @@ export type KanbanStoreState = {statuses: KanbanColumnItem[];goalId: GoalItem['id'];filters: KanbanFilters;-};\ No newline at end of file+};+export type KanbanMoveStatusArgs = {+ statusId: KanbanColumnItem['id'];+ direction: 'left' | 'right';+};diff --git a/web/src/uiCustomization/registry.ts b/web/src/uiCustomization/registry.tsindex 7c0808c..b47efc2 100644--- a/web/src/uiCustomization/registry.ts+++ b/web/src/uiCustomization/registry.ts@@ -1,11 +1,13 @@import { analyticsIndicatorsSection, analyticsChartsSection } from './sections/analytics'import { tasksSection } from './sections/tasks'import { othersSection } from './sections/others'+import { themeSection } from './sections/theme'import type { UiCustomizationSectionDef } from './types'export const uiCustomizationSections: UiCustomizationSectionDef[] = [analyticsIndicatorsSection,analyticsChartsSection,tasksSection,+ themeSection,othersSection,]diff --git a/web/src/uiCustomization/sections/theme.ts b/web/src/uiCustomization/sections/theme.tsnew file mode 100644index 0000000..fea8812--- /dev/null+++ b/web/src/uiCustomization/sections/theme.ts@@ -0,0 +1,10 @@+import { markRaw } from 'vue'+import UiCustomizationTheme from '@/components/features/ui-customization/UiCustomizationTheme.vue'+import type { UiCustomizationSectionDef } from '../types'++export const themeSection: UiCustomizationSectionDef = {+ kind: 'custom',+ id: 'theme',+ labelKey: 'uiCustomization.sections.theme',+ component: markRaw(UiCustomizationTheme),+}