Skip to content

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.

fix: org permissions

Nikolai Gimane9fb4f6f1e88
diff --git a/api/src/middlewares/__tests__/require-token-permission.test.ts b/api/src/middlewares/__tests__/require-token-permission.test.ts
new file mode 100644
index 0000000..2612edb
--- /dev/null
+++ b/api/src/middlewares/__tests__/require-token-permission.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect, vi } from 'vitest';
+import type { Request, Response } from 'express';
+import { RequireTokenPermission } from '../require-token-permission';
+import { GoalPermissions } from '../../types/auth.types';
+
+const runWith = (tokenPermissions: string[] | undefined) => {
+ const next = vi.fn();
+ const end = vi.fn();
+ const res = { status: vi.fn(() => ({ end })), end } as unknown as Response;
+ const req = { appUser: { getTokenPermissions: () => tokenPermissions } } as unknown as Request;
+
+ RequireTokenPermission(GoalPermissions.ORG_CAN_MANAGE)(req, res, next);
+ return { next, res };
+};
+
+describe('RequireTokenPermission', () => {
+ it('lets a browser session through — it carries no token permissions', () => {
+ const { next, res } = runWith(undefined);
+ expect(next).toHaveBeenCalled();
+ expect(res.status).not.toHaveBeenCalled();
+ });
+
+ it('lets an unrestricted token through, keeping existing integrations working', () => {
+ const { next } = runWith([]);
+ expect(next).toHaveBeenCalled();
+ });
+
+ it('lets a token holding the permission through', () => {
+ const { next } = runWith([GoalPermissions.ORG_CAN_MANAGE]);
+ expect(next).toHaveBeenCalled();
+ });
+
+ it('blocks a restricted token that was not given the permission', () => {
+ const { next, res } = runWith([GoalPermissions.TIMETRACKING_CAN_VIEW]);
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(403);
+ });
+
+ it('does not accept a neighbouring permission from the same group', () => {
+ const { next, res } = runWith([GoalPermissions.ORG_CAN_MANAGE_MEMBERS]);
+ expect(next).not.toHaveBeenCalled();
+ expect(res.status).toHaveBeenCalledWith(403);
+ });
+});
diff --git a/api/src/middlewares/require-token-permission.ts b/api/src/middlewares/require-token-permission.ts
new file mode 100644
index 0000000..68ec920
--- /dev/null
+++ b/api/src/middlewares/require-token-permission.ts
@@ -0,0 +1,34 @@
+import type { NextFunction, Request, Response } from 'express';
+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
+ * GoalPermissionsFetcher, so without this the scope chosen when the token was
+ * issued would simply not apply to them.
+ *
+ * It only ever removes access. Put it AFTER the role or ownership guard, so that
+ * guard still has the final say on what the human behind the token may do:
+ *
+ * [IsLoggedIn, IsOrgAdmin, RequireTokenPermission(GoalPermissions.ORG_CAN_MANAGE)]
+ *
+ * A browser session has no token permissions and passes. A token issued with an
+ * empty permission list is unrestricted by design — the same meaning it carries
+ * everywhere else — and also passes, which keeps existing integrations working.
+ */
+export const RequireTokenPermission = (permission: GoalPermissionType) => {
+ return (req: Request, res: Response, next: NextFunction) => {
+ const tokenPermissions = req.appUser.getTokenPermissions();
+
+ if (!tokenPermissions || tokenPermissions.length === 0) {
+ return next();
+ }
+
+ if (tokenPermissions.includes(permission)) {
+ return next();
+ }
+
+ return res.status(403).end();
+ };
+};
diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.json
index c4070b0..6c83865 100644
--- a/api/src/migrations/taskview/migrate.json
+++ b/api/src/migrations/taskview/migrate.json
@@ -767,5 +767,18 @@
"tv_auth.oauth_auth_codes holds single-use 60-second authorization codes; tv_auth.oauth_grants is one row per connected app and owns the rotating refresh token, with the previous hash kept to detect replay.",
"Access tokens reuse tv_auth.api_tokens (new grant_id column) so validation, permission intersection and RejectApiTokenAuth all keep working unchanged; revoking a grant cascades to its live access tokens."
]
+ },
+ "60": {
+ "version": "1.65.0",
+ "name": "Organization-level permissions",
+ "releaseDate": "20260830",
+ "scripts": [
+ "/1.65.0/0.organization-permissions.sql"
+ ],
+ "description": [
+ "New permission group 'organization' with org_can_view, org_can_manage, org_can_manage_members, sso_can_manage and webhooks_can_manage.",
+ "These surfaces were guarded only by an organization role or by project ownership, so they ignored the scope of an API or OAuth token: a token issued with a single permission could still create organizations, add admins, change SSO settings and create webhooks. The new keys make those actions narrowable like every other permission.",
+ "Backwards compatible: a token with an empty permission list stays unrestricted, so existing integrations keep working."
+ ]
}
}
diff --git a/api/src/migrations/taskview/sql/1.65.0/0.organization-permissions.sql b/api/src/migrations/taskview/sql/1.65.0/0.organization-permissions.sql
new file mode 100644
index 0000000..84ecf63
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.65.0/0.organization-permissions.sql
@@ -0,0 +1,86 @@
+-- Permissions for the surfaces that were previously guarded only by an
+-- organization role or by project ownership, and therefore ignored the scope of
+-- an API / OAuth token entirely: a token issued with a single permission could
+-- still create organizations, add admins, configure SSO and create webhooks.
+--
+-- These keys let a token be narrowed on those actions too. They never grant
+-- anything: the role and ownership checks still run first, and RequireTokenPermission
+-- only removes what the token was not given.
+INSERT INTO tv_auth.permissions_group (id, name)
+VALUES (6, 'organization')
+ON CONFLICT (id) DO NOTHING;
+
+INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
+VALUES (
+ 'org_can_view',
+ 'View the organization and its members',
+ 6,
+ '{
+ "en": "View organization. See the organization and the list of its members.",
+ "ru": "Просмотр организации. Видеть организацию и список её участников.",
+ "de": "Organisation ansehen. Die Organisation und ihre Mitglieder sehen.",
+ "es": "Ver la organización. Ver la organización y la lista de sus miembros.",
+ "pt-BR": "Ver a organização. Ver a organização e a lista de seus membros."
+ }'::jsonb
+)
+ON CONFLICT (name) DO NOTHING;
+
+INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
+VALUES (
+ 'org_can_manage',
+ 'Create, rename and delete organizations',
+ 6,
+ '{
+ "en": "Manage organizations. Create, rename and delete organizations.",
+ "ru": "Управление организациями. Создавать, переименовывать и удалять организации.",
+ "de": "Organisationen verwalten. Organisationen erstellen, umbenennen und löschen.",
+ "es": "Gestionar organizaciones. Crear, renombrar y eliminar organizaciones.",
+ "pt-BR": "Gerenciar organizações. Criar, renomear e excluir organizações."
+ }'::jsonb
+)
+ON CONFLICT (name) DO NOTHING;
+
+INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
+VALUES (
+ 'org_can_manage_members',
+ 'Add and remove organization members and change their roles',
+ 6,
+ '{
+ "en": "Manage members. Add and remove organization members and change their roles.",
+ "ru": "Управление участниками. Добавлять и удалять участников организации, менять их роли.",
+ "de": "Mitglieder verwalten. Mitglieder hinzufügen, entfernen und deren Rollen ändern.",
+ "es": "Gestionar miembros. Añadir y quitar miembros de la organización y cambiar sus roles.",
+ "pt-BR": "Gerenciar membros. Adicionar e remover membros da organização e alterar seus papéis."
+ }'::jsonb
+)
+ON CONFLICT (name) DO NOTHING;
+
+INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
+VALUES (
+ 'sso_can_manage',
+ 'Create and change the single sign-on configuration',
+ 6,
+ '{
+ "en": "Manage SSO. Create and change the single sign-on configuration of the organization.",
+ "ru": "Управление SSO. Создавать и изменять настройки единого входа организации.",
+ "de": "SSO verwalten. Die Single-Sign-on-Konfiguration der Organisation erstellen und ändern.",
+ "es": "Gestionar SSO. Crear y cambiar la configuración de inicio de sesión único de la organización.",
+ "pt-BR": "Gerenciar SSO. Criar e alterar a configuração de login único da organização."
+ }'::jsonb
+)
+ON CONFLICT (name) DO NOTHING;
+
+INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)
+VALUES (
+ 'webhooks_can_manage',
+ 'Create, edit and delete project webhooks',
+ 6,
+ '{
+ "en": "Manage webhooks. Create, edit and delete webhooks of a project.",
+ "ru": "Управление вебхуками. Создавать, изменять и удалять вебхуки проекта.",
+ "de": "Webhooks verwalten. Webhooks eines Projekts erstellen, bearbeiten und löschen.",
+ "es": "Gestionar webhooks. Crear, editar y eliminar webhooks de un proyecto.",
+ "pt-BR": "Gerenciar webhooks. Criar, editar e excluir webhooks de um projeto."
+ }'::jsonb
+)
+ON CONFLICT (name) DO NOTHING;
diff --git a/api/src/tv-modules/api-tokens/ApiTokensController.ts b/api/src/tv-modules/api-tokens/ApiTokensController.ts
index d8dc20c..3eb213d 100644
--- a/api/src/tv-modules/api-tokens/ApiTokensController.ts
+++ b/api/src/tv-modules/api-tokens/ApiTokensController.ts
@@ -2,7 +2,6 @@ import type { Request, Response } from 'express';
import { ArkErrors } from 'arktype';
import { getApiTokensManager } from './ApiTokensManager';
import { ApiTokenArkTypeCreate, ApiTokenArkTypeDelete } from './types';
-import { Database } from '../../modules/db';
export class ApiTokensController {
private get manager() { return getApiTokensManager(); }
@@ -44,10 +43,7 @@ export class ApiTokensController {
};
fetchPermissions = async (_req: Request, res: Response) => {
- const db = Database.getInstance();
- const result = await db.query<{ id: number; name: string; description: string; permissionGroup: number }>(
- `SELECT id, name, description, permission_group as "permissionGroup" FROM tv_auth.permissions WHERE permission_group <> 1 ORDER BY permission_group, id`
- );
- return res.tvJson(result?.rows ?? []);
+ const result = await this.manager.fetchSelectablePermissions();
+ return res.tvJson(result);
};
}
diff --git a/api/src/tv-modules/api-tokens/ApiTokensManager.ts b/api/src/tv-modules/api-tokens/ApiTokensManager.ts
index 65ff6e1..2cf8595 100644
--- a/api/src/tv-modules/api-tokens/ApiTokensManager.ts
+++ b/api/src/tv-modules/api-tokens/ApiTokensManager.ts
@@ -1,7 +1,7 @@
import { randomBytes, createHash } from 'crypto';
import { ApiTokensRepository } from './ApiTokensRepository';
import { TOKEN_PREFIX, type ApiTokenArgCreate } from './types';
-import type { ApiTokensSchemaTypeForSelect } from 'taskview-db-schemas';
+import type { ApiTokensSchemaTypeForSelect, PermissionsSchemaTypeForSelect } from 'taskview-db-schemas';
export type ApiTokenForClient = Omit<ApiTokensSchemaTypeForSelect, 'tokenHash'>;
@@ -42,6 +42,10 @@ export class ApiTokensManager {
return tokens.map((t) => this.toClient(t));
}
+ async fetchSelectablePermissions(): Promise<PermissionsSchemaTypeForSelect[]> {
+ return this.repository.fetchSelectablePermissions();
+ }
+
async validateToken(fullToken: string): Promise<ApiTokensSchemaTypeForSelect | null> {
const tokenHash = createHash('sha256').update(fullToken).digest('hex');
const record = await this.repository.findByTokenHash(tokenHash);
diff --git a/api/src/tv-modules/api-tokens/ApiTokensRepository.ts b/api/src/tv-modules/api-tokens/ApiTokensRepository.ts
index fbbd758..f9b1be2 100644
--- a/api/src/tv-modules/api-tokens/ApiTokensRepository.ts
+++ b/api/src/tv-modules/api-tokens/ApiTokensRepository.ts
@@ -1,5 +1,10 @@
-import { and, eq, isNull } from 'drizzle-orm';
-import { ApiTokensSchema, type ApiTokensSchemaTypeForSelect } from 'taskview-db-schemas';
+import { and, asc, eq, isNull, ne } from 'drizzle-orm';
+import {
+ ApiTokensSchema,
+ PermissionsSchema,
+ type ApiTokensSchemaTypeForSelect,
+ type PermissionsSchemaTypeForSelect,
+} from 'taskview-db-schemas';
import { Database } from '../../modules/db';
import { callWithCatch } from '../../utils/helpers';
@@ -46,6 +51,21 @@ export class ApiTokensRepository {
return result?.[0] ?? null;
}
+ /**
+ * Permissions offered when scoping a token. Group 1 is excluded: those keys
+ * exist in the table but are enforced nowhere in the code, so offering them
+ * would promise a restriction that never happens.
+ */
+ async fetchSelectablePermissions(): Promise<PermissionsSchemaTypeForSelect[]> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle.select()
+ .from(PermissionsSchema)
+ .where(ne(PermissionsSchema.permissionGroup, 1))
+ .orderBy(asc(PermissionsSchema.permissionGroup), asc(PermissionsSchema.id))
+ );
+ return result ?? [];
+ }
+
async updateLastUsedAt(id: number): Promise<void> {
await callWithCatch(() =>
this.db.dbDrizzle.update(ApiTokensSchema)
diff --git a/api/src/tv-modules/oauth/OAuthManager.ts b/api/src/tv-modules/oauth/OAuthManager.ts
index 9b153d1..4975b36 100644
--- a/api/src/tv-modules/oauth/OAuthManager.ts
+++ b/api/src/tv-modules/oauth/OAuthManager.ts
@@ -227,6 +227,7 @@ export class OAuthManager {
refreshTokenHash: sha256Hex(refreshToken),
prevHash: args.prevRefreshHash ?? null,
refreshExpiresAt: new Date(now + OAUTH_REFRESH_TOKEN_TTL_SECONDS * 1000),
+ presentedHash: args.prevRefreshHash ?? null,
})
if (!rotated) {
return { ok: false, error: 'invalid_grant', description: 'This authorization has been revoked' }
diff --git a/api/src/tv-modules/oauth/OAuthRepository.ts b/api/src/tv-modules/oauth/OAuthRepository.ts
index 6d6d273..37a4add 100644
--- a/api/src/tv-modules/oauth/OAuthRepository.ts
+++ b/api/src/tv-modules/oauth/OAuthRepository.ts
@@ -92,13 +92,6 @@ export class OAuthRepository {
return result?.[0] ?? null
}
- async findGrantById(id: number): Promise<OAuthGrantsSchemaTypeForSelect | null> {
- const result = await callWithCatch(() =>
- this.db.dbDrizzle.select().from(OAuthGrantsSchema).where(eq(OAuthGrantsSchema.id, id)),
- )
- return result?.[0] ?? null
- }
-
/** Matches the current refresh token or the previous one, so replay is detectable. */
async findGrantByRefreshHash(refreshTokenHash: string): Promise<OAuthGrantsSchemaTypeForSelect | null> {
const result = await callWithCatch(() =>
@@ -121,7 +114,16 @@ export class OAuthRepository {
refreshExpiresAt: args.refreshExpiresAt,
lastUsedAt: new Date(),
})
- .where(and(eq(OAuthGrantsSchema.id, args.grantId), isNull(OAuthGrantsSchema.revokedAt))),
+ .where(and(
+ eq(OAuthGrantsSchema.id, args.grantId),
+ isNull(OAuthGrantsSchema.revokedAt),
+ // The presented token must still be the current one. Without this,
+ // two concurrent refreshes both succeed and the second overwrites
+ // the first, silently orphaning the refresh token it just handed out.
+ args.presentedHash
+ ? eq(OAuthGrantsSchema.refreshTokenHash, args.presentedHash)
+ : isNull(OAuthGrantsSchema.refreshTokenHash),
+ )),
)
return !!result?.rowCount
}
@@ -172,12 +174,6 @@ export class OAuthRepository {
return !!result?.length
}
- async deleteAccessTokensForGrant(grantId: number): Promise<void> {
- await callWithCatch(() =>
- this.db.dbDrizzle.delete(ApiTokensSchema).where(eq(ApiTokensSchema.grantId, grantId)),
- )
- }
-
async findGrantIdByAccessTokenHash(tokenHash: string): Promise<number | null> {
const result = await callWithCatch(() =>
this.db.dbDrizzle.select({ grantId: ApiTokensSchema.grantId })
diff --git a/api/src/tv-modules/oauth/__tests__/OAuth.integration.spec.ts b/api/src/tv-modules/oauth/__tests__/OAuth.integration.spec.ts
index eac5029..965d6ff 100644
--- a/api/src/tv-modules/oauth/__tests__/OAuth.integration.spec.ts
+++ b/api/src/tv-modules/oauth/__tests__/OAuth.integration.spec.ts
@@ -207,6 +207,73 @@ describe('OAuth 2.1 authorization server', () => {
});
});
+ describe('rejecting malformed requests', () => {
+ it('refuses an unknown grant_type', async () => {
+ const response = await api.post('/module/oauth/token', {
+ grant_type: 'password',
+ client_id: 'anything',
+ });
+
+ expect(response.status).toBe(400);
+ expect(response.data.error).toBe('invalid_request');
+ });
+
+ it('refuses a token request with no client_id at all', async () => {
+ const response = await api.post('/module/oauth/token', {
+ grant_type: 'authorization_code',
+ code: 'x',
+ code_verifier: 'y',
+ redirect_uri: REDIRECT_URI,
+ });
+
+ expect(response.status).toBe(401);
+ expect(response.data.error).toBe('invalid_client');
+ });
+
+ it('refuses registration with an empty redirect_uris list', async () => {
+ const response = await api.post('/module/oauth/register', {
+ client_name: 'No redirects',
+ redirect_uris: [],
+ });
+
+ expect(response.status).toBe(400);
+ });
+
+ it('refuses an authorize request missing the PKCE challenge', async () => {
+ const registered = await registerClient();
+
+ const response = await api.get('/module/oauth/authorize', {
+ params: {
+ response_type: 'code',
+ client_id: registered.data.client_id,
+ redirect_uri: REDIRECT_URI,
+ code_challenge_method: 'S256',
+ },
+ maxRedirects: 0,
+ });
+
+ expect(response.status).toBe(400);
+ expect(response.headers.location).toBeUndefined();
+ });
+
+ it('refuses a response_type other than code', async () => {
+ const registered = await registerClient();
+
+ const response = await api.get('/module/oauth/authorize', {
+ params: {
+ response_type: 'token',
+ client_id: registered.data.client_id,
+ redirect_uri: REDIRECT_URI,
+ code_challenge: challengeFor(verifier()),
+ code_challenge_method: 'S256',
+ },
+ maxRedirects: 0,
+ });
+
+ expect(response.status).toBe(400);
+ });
+ });
+
describe('/authorize', () => {
it('redirects a valid request to the consent screen with its parameters intact', async () => {
const registered = await registerClient();
@@ -298,6 +365,41 @@ describe('OAuth 2.1 authorization server', () => {
expect(response.status).toBe(401);
});
+ it('refuses a redirect_uri the client never registered', async () => {
+ const registered = await registerClient();
+
+ const response = await api.post(
+ '/module/oauth/consent',
+ {
+ client_id: registered.data.client_id,
+ redirect_uri: 'https://attacker.example.com/steal',
+ code_challenge: challengeFor(verifier()),
+ code_challenge_method: 'S256',
+ allowedPermissions: [],
+ },
+ { headers: { Authorization: `Bearer ${jwt}` } },
+ );
+
+ expect(response.status).toBe(400);
+ });
+
+ it('refuses a deny request pointing at an unregistered redirect_uri', async () => {
+ const registered = await registerClient();
+
+ const response = await api.post(
+ '/module/oauth/consent/deny',
+ {
+ client_id: registered.data.client_id,
+ redirect_uri: 'https://attacker.example.com/steal',
+ code_challenge: challengeFor(verifier()),
+ code_challenge_method: 'S256',
+ },
+ { headers: { Authorization: `Bearer ${jwt}` } },
+ );
+
+ expect(response.status).toBe(400);
+ });
+
it('returns a redirect carrying access_denied when the user declines', async () => {
const registered = await registerClient();
const response = await api.post(
@@ -415,6 +517,108 @@ describe('OAuth 2.1 authorization server', () => {
});
});
+ describe('separation from manually issued tokens', () => {
+ const apiTokenIdFor = async (accessToken: string) => {
+ const db = Database.getInstance();
+ const result = await db.query<{ id: number }>(
+ 'SELECT id FROM tv_auth.api_tokens WHERE token_hash = $1',
+ [sha256(accessToken)],
+ );
+ return result?.rows[0]?.id;
+ };
+
+ it('hides OAuth access tokens from the API token list', async () => {
+ const { access_token } = await connect();
+ const id = await apiTokenIdFor(access_token);
+ expect(id).toBeTruthy();
+
+ const list = await api.get('/module/api-tokens', {
+ headers: { Authorization: `Bearer ${jwt}` },
+ });
+
+ expect(list.status).toBe(200);
+ expect(list.data.response.some((token: { id: number }) => token.id === id)).toBe(false);
+ });
+
+ it('refuses to delete an OAuth access token through the API token endpoint', async () => {
+ const { access_token } = await connect();
+ const id = await apiTokenIdFor(access_token);
+
+ const deleted = await api.delete('/module/api-tokens', {
+ headers: { Authorization: `Bearer ${jwt}` },
+ data: { id },
+ });
+
+ expect(deleted.data.response).toBe(false);
+
+ // Deleting from the wrong place must not silently look like it worked:
+ // the connection is still alive.
+ const stillWorks = await api.get('/module/goals', {
+ headers: { Authorization: `Bearer ${access_token}` },
+ });
+ expect(stillWorks.status).toBe(200);
+ });
+ });
+
+ describe('grants limited to selected projects', () => {
+ it('sees only the project the user picked on the consent screen', async () => {
+ const second = await api.post(
+ '/module/goals',
+ { name: `oauth-it-second-${Date.now()}` },
+ { headers: { Authorization: `Bearer ${jwt}` } },
+ );
+ const secondGoalId = second.data.response.id;
+
+ const registered = await registerClient();
+ const clientId = registered.data.client_id;
+ const codeVerifier = verifier();
+ const code = await authorizeAndConsent({
+ clientId,
+ codeChallenge: challengeFor(codeVerifier),
+ allowedGoalIds: [goalId],
+ });
+ const tokens = await exchange({ clientId, code, codeVerifier });
+ expect(tokens.status).toBe(200);
+
+ const goals = await api.get('/module/goals', {
+ headers: { Authorization: `Bearer ${tokens.data.access_token}` },
+ });
+
+ const visible = goals.data.response.map((goal: { id: number }) => goal.id);
+ expect(visible).toContain(goalId);
+ expect(visible).not.toContain(secondGoalId);
+
+ await api.delete('/module/goals', {
+ headers: { Authorization: `Bearer ${jwt}` },
+ data: { goalId: secondGoalId },
+ });
+ });
+
+ it('records the choice on the connected app', async () => {
+ const registered = await registerClient();
+ const clientId = registered.data.client_id;
+ const codeVerifier = verifier();
+ const code = await authorizeAndConsent({
+ clientId,
+ codeChallenge: challengeFor(codeVerifier),
+ allowedPermissions: ['timetracking_can_view'],
+ allowedGoalIds: [goalId],
+ });
+ await exchange({ clientId, code, codeVerifier });
+
+ const apps = await api.get('/module/oauth/connected-apps', {
+ headers: { Authorization: `Bearer ${jwt}` },
+ });
+ const app = apps.data.response.find(
+ (item: { clientId: string }) => item.clientId === clientId,
+ );
+
+ expect(app.clientName).toBe('Integration Client');
+ expect(app.allowedPermissions).toEqual(['timetracking_can_view']);
+ expect(app.allowedGoalIds).toEqual([goalId]);
+ });
+ });
+
describe('authorization code hardening', () => {
it('refuses a wrong code_verifier', async () => {
const registered = await registerClient();
@@ -493,6 +697,157 @@ describe('OAuth 2.1 authorization server', () => {
});
});
+ describe('confidential clients', () => {
+ // DCR only ever creates public clients, so seed one with a secret the way
+ // an operator would, and exercise both ways of presenting it.
+ const CONFIDENTIAL_ID = 'integration-confidential';
+ const CONFIDENTIAL_SECRET = 'integration-secret-value';
+
+ const seedConfidentialClient = async () => {
+ const db = Database.getInstance();
+ await db.query(
+ `INSERT INTO tv_auth.oauth_clients (client_id, client_secret_hash, name, redirect_uris, created_via)
+ VALUES ($1, $2, 'Confidential Client', ARRAY[$3], 'manual')
+ ON CONFLICT (client_id) DO NOTHING`,
+ [CONFIDENTIAL_ID, sha256(CONFIDENTIAL_SECRET), REDIRECT_URI],
+ );
+ };
+
+ const codeFor = async (codeVerifier: string) => authorizeAndConsent({
+ clientId: CONFIDENTIAL_ID,
+ codeChallenge: challengeFor(codeVerifier),
+ });
+
+ beforeAll(seedConfidentialClient);
+
+ afterAll(async () => {
+ const db = Database.getInstance();
+ await db.query('DELETE FROM tv_auth.oauth_clients WHERE client_id = $1', [CONFIDENTIAL_ID]);
+ });
+
+ it('accepts the secret in the request body', async () => {
+ const codeVerifier = verifier();
+ const code = await codeFor(codeVerifier);
+
+ const response = await api.post('/module/oauth/token', {
+ grant_type: 'authorization_code',
+ client_id: CONFIDENTIAL_ID,
+ client_secret: CONFIDENTIAL_SECRET,
+ code,
+ code_verifier: codeVerifier,
+ redirect_uri: REDIRECT_URI,
+ });
+
+ expect(response.status).toBe(200);
+ expect(response.data.access_token.startsWith('tvo_')).toBe(true);
+ });
+
+ it('accepts the secret via HTTP Basic authentication', async () => {
+ const codeVerifier = verifier();
+ const code = await codeFor(codeVerifier);
+ const basic = Buffer.from(`${CONFIDENTIAL_ID}:${CONFIDENTIAL_SECRET}`).toString('base64');
+
+ const response = await api.post(
+ '/module/oauth/token',
+ {
+ grant_type: 'authorization_code',
+ code,
+ code_verifier: codeVerifier,
+ redirect_uri: REDIRECT_URI,
+ },
+ { headers: { Authorization: `Basic ${basic}` } },
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.data.access_token.startsWith('tvo_')).toBe(true);
+ });
+
+ it('refuses a wrong secret', async () => {
+ const codeVerifier = verifier();
+ const code = await codeFor(codeVerifier);
+
+ const response = await api.post('/module/oauth/token', {
+ grant_type: 'authorization_code',
+ client_id: CONFIDENTIAL_ID,
+ client_secret: 'not-the-secret',
+ code,
+ code_verifier: codeVerifier,
+ redirect_uri: REDIRECT_URI,
+ });
+
+ expect(response.status).toBe(401);
+ expect(response.data.error).toBe('invalid_client');
+ });
+
+ it('refuses a missing secret — PKCE alone is not enough for a confidential client', async () => {
+ const codeVerifier = verifier();
+ const code = await codeFor(codeVerifier);
+
+ const response = await api.post('/module/oauth/token', {
+ grant_type: 'authorization_code',
+ client_id: CONFIDENTIAL_ID,
+ code,
+ code_verifier: codeVerifier,
+ redirect_uri: REDIRECT_URI,
+ });
+
+ expect(response.status).toBe(401);
+ });
+ });
+
+ describe('token lifetime', () => {
+ it('stops accepting an access token once it expires', async () => {
+ const { access_token } = await connect();
+
+ const before = await api.get('/module/goals', {
+ headers: { Authorization: `Bearer ${access_token}` },
+ });
+ expect(before.status).toBe(200);
+
+ const db = Database.getInstance();
+ await db.query(
+ "UPDATE tv_auth.api_tokens SET expires_at = now() - interval '1 minute' WHERE token_hash = $1",
+ [sha256(access_token)],
+ );
+
+ const after = await api.get('/module/goals', {
+ headers: { Authorization: `Bearer ${access_token}` },
+ });
+ expect(after.status).toBe(401);
+ });
+
+ it('issues access tokens with an expiry, never an endless one', async () => {
+ const { access_token } = await connect();
+
+ const db = Database.getInstance();
+ const result = await db.query<{ expires_at: Date | null }>(
+ 'SELECT expires_at FROM tv_auth.api_tokens WHERE token_hash = $1',
+ [sha256(access_token)],
+ );
+
+ expect(result?.rows[0].expires_at).toBeTruthy();
+ });
+
+ it('refuses an expired refresh token', async () => {
+ const { clientId, refresh_token } = await connect();
+
+ const db = Database.getInstance();
+ await db.query(
+ "UPDATE tv_auth.oauth_grants SET refresh_expires_at = now() - interval '1 minute' WHERE refresh_token_hash = $1",
+ [sha256(refresh_token)],
+ );
+
+ const response = await api.post('/module/oauth/token', {
+ grant_type: 'refresh_token',
+ client_id: clientId,
+ refresh_token,
+ });
+
+ expect(response.status).toBe(400);
+ expect(response.data.error).toBe('invalid_grant');
+ });
+ });
+
describe('refresh token rotation', () => {
it('rotates the refresh token and keeps the new access token working', async () => {
const { clientId, refresh_token } = await connect();
@@ -537,6 +892,64 @@ describe('OAuth 2.1 authorization server', () => {
});
});
+ describe('concurrent refresh', () => {
+ it('lets exactly one of two simultaneous refreshes win', async () => {
+ const { clientId, refresh_token } = await connect();
+
+ const refresh = () => api.post('/module/oauth/token', {
+ grant_type: 'refresh_token',
+ client_id: clientId,
+ refresh_token,
+ });
+
+ const [a, b] = await Promise.all([refresh(), refresh()]);
+
+ expect([a.status, b.status].sort()).toEqual([200, 400]);
+ });
+
+ it('keeps the winning refresh token usable afterwards', async () => {
+ const { clientId, refresh_token } = await connect();
+
+ const refresh = (token: string) => api.post('/module/oauth/token', {
+ grant_type: 'refresh_token',
+ client_id: clientId,
+ refresh_token: token,
+ });
+
+ const [a, b] = await Promise.all([refresh(refresh_token), refresh(refresh_token)]);
+ const winner = a.status === 200 ? a : b;
+
+ // Before the fix the loser overwrote the winner's rotation, orphaning
+ // the refresh token that had just been handed to the real client.
+ const next = await refresh(winner.data.refresh_token);
+
+ expect(next.status).toBe(200);
+ });
+
+ it('refuses a refresh whose resource does not match the grant', async () => {
+ const registered = await registerClient();
+ const clientId = registered.data.client_id;
+ const codeVerifier = verifier();
+ const code = await authorizeAndConsent({
+ clientId,
+ codeChallenge: challengeFor(codeVerifier),
+ resource: 'https://mcp.integration.test',
+ });
+ const tokens = await exchange({ clientId, code, codeVerifier, resource: 'https://mcp.integration.test' });
+ expect(tokens.status).toBe(200);
+
+ const response = await api.post('/module/oauth/token', {
+ grant_type: 'refresh_token',
+ client_id: clientId,
+ refresh_token: tokens.data.refresh_token,
+ resource: 'https://other.integration.test',
+ });
+
+ expect(response.status).toBe(400);
+ expect(response.data.error).toBe('invalid_target');
+ });
+ });
+
describe('revocation', () => {
it('kills the access token immediately when the user disconnects the app', async () => {
const { access_token } = await connect();
@@ -571,6 +984,86 @@ describe('OAuth 2.1 authorization server', () => {
expect(after.status).toBe(401);
});
+ it('kills a live access token presented to /revoke', async () => {
+ const { access_token } = await connect();
+
+ const revoked = await api.post('/module/oauth/revoke', { token: access_token });
+ expect(revoked.status).toBe(200);
+
+ const after = await api.get('/module/goals', {
+ headers: { Authorization: `Bearer ${access_token}` },
+ });
+ expect(after.status).toBe(401);
+ });
+
+ it('kills the grant when a refresh token is presented to /revoke', async () => {
+ const { clientId, access_token, refresh_token } = await connect();
+
+ const revoked = await api.post('/module/oauth/revoke', { token: refresh_token });
+ expect(revoked.status).toBe(200);
+
+ const refreshed = await api.post('/module/oauth/token', {
+ grant_type: 'refresh_token',
+ client_id: clientId,
+ refresh_token,
+ });
+ expect(refreshed.status).toBe(400);
+
+ // Revoking the grant takes its live access tokens with it.
+ const after = await api.get('/module/goals', {
+ headers: { Authorization: `Bearer ${access_token}` },
+ });
+ expect(after.status).toBe(401);
+ });
+
+ it('does not let one user revoke another user\'s grant', async () => {
+ const { access_token } = await connect();
+
+ const db = Database.getInstance();
+ const owning = await db.query<{ grant_id: number }>(
+ 'SELECT grant_id FROM tv_auth.api_tokens WHERE token_hash = $1',
+ [sha256(access_token)],
+ );
+ const grantId = owning?.rows[0].grant_id;
+
+ // Hand the grant to somebody else, then try to revoke it as the caller.
+ const stamp = Date.now();
+ const other = await db.query<{ id: number }>(
+ `INSERT INTO tv_auth.users (login, email, password, confirm_email_code, block)
+ VALUES ($1, $2, 'x', $3, 0) RETURNING id`,
+ [`grant-owner-${stamp}`, `grant-owner-${stamp}@test.dest`, `code-${stamp}`],
+ );
+ const otherUserId = other?.rows[0]?.id;
+ expect(otherUserId).toBeTruthy();
+
+ await db.query('UPDATE tv_auth.oauth_grants SET user_id = $1 WHERE id = $2', [otherUserId, grantId]);
+
+ const response = await api.delete('/module/oauth/connected-apps', {
+ headers: { Authorization: `Bearer ${jwt}` },
+ data: { grantId },
+ });
+
+ expect(response.data.response).toBe(false);
+
+ // The victim's access token must still work — nothing was revoked.
+ const stillWorks = await api.get('/module/goals', {
+ headers: { Authorization: `Bearer ${access_token}` },
+ });
+ expect(stillWorks.status).toBe(200);
+
+ await db.query('DELETE FROM tv_auth.oauth_grants WHERE id = $1', [grantId]);
+ await db.query('DELETE FROM tv_auth.users WHERE id = $1', [otherUserId]);
+ });
+
+ it('rejects a grantId that is not a positive integer', async () => {
+ const response = await api.delete('/module/oauth/connected-apps', {
+ headers: { Authorization: `Bearer ${jwt}` },
+ data: { grantId: 'not-a-number' },
+ });
+
+ expect(response.status).toBe(400);
+ });
+
it('answers 200 to RFC 7009 revocation of an unknown token', async () => {
const response = await api.post('/module/oauth/revoke', { token: 'tvo_nope' });
diff --git a/api/src/tv-modules/oauth/__tests__/OAuthDcrDisabled.integration.spec.ts b/api/src/tv-modules/oauth/__tests__/OAuthDcrDisabled.integration.spec.ts
new file mode 100644
index 0000000..6d131ec
--- /dev/null
+++ b/api/src/tv-modules/oauth/__tests__/OAuthDcrDisabled.integration.spec.ts
@@ -0,0 +1,52 @@
+import axios from 'axios';
+import type http from 'http';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+
+const port = 1812;
+const url = `http://localhost:${port}`;
+
+let server: http.Server;
+const api = axios.create({ baseURL: url, validateStatus: () => true });
+
+/**
+ * OAUTH_DYNAMIC_REGISTRATION=false is the lever a self-hosted operator pulls to
+ * keep the client registry closed. It has to do two things: refuse registration,
+ * and stop advertising the endpoint — a client that reads the metadata should
+ * never attempt a registration this instance will reject.
+ */
+describe('OAuth with dynamic client registration disabled', () => {
+ vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+ }));
+
+ beforeAll(() => {
+ process.env.OAUTH_DYNAMIC_REGISTRATION = 'false';
+ server = new App(port).listen();
+ });
+
+ afterAll(() => {
+ server?.close();
+ delete process.env.OAUTH_DYNAMIC_REGISTRATION;
+ });
+
+ it('refuses to register a client', async () => {
+ const response = await api.post('/module/oauth/register', {
+ client_name: 'Should be refused',
+ redirect_uris: ['https://client.test/cb'],
+ });
+
+ expect(response.status).toBe(403);
+ expect(response.data.error).toBe('access_denied');
+ });
+
+ it('stops advertising the registration endpoint in the metadata', async () => {
+ const response = await api.get('/.well-known/oauth-authorization-server');
+
+ expect(response.status).toBe(200);
+ expect(response.data.registration_endpoint).toBeUndefined();
+ // The rest of the flow stays available for manually seeded clients.
+ expect(response.data.authorization_endpoint).toContain('/module/oauth/authorize');
+ expect(response.data.token_endpoint).toContain('/module/oauth/token');
+ });
+});
diff --git a/api/src/tv-modules/oauth/types.ts b/api/src/tv-modules/oauth/types.ts
index 8cd7f31..b6f8806 100644
--- a/api/src/tv-modules/oauth/types.ts
+++ b/api/src/tv-modules/oauth/types.ts
@@ -132,6 +132,8 @@ export type RotateRefreshTokenArgs = {
refreshTokenHash: string
prevHash: string | null
refreshExpiresAt: Date
+ /** Hash the caller presented; null on the first issue, when the grant has none yet. */
+ presentedHash: string | null
}
export type RevokeGrantArgs = {
diff --git a/api/src/tv-modules/organizations/OrganizationRoutes.ts b/api/src/tv-modules/organizations/OrganizationRoutes.ts
index c4da6ef..0577fc3 100644
--- a/api/src/tv-modules/organizations/OrganizationRoutes.ts
+++ b/api/src/tv-modules/organizations/OrganizationRoutes.ts
@@ -5,6 +5,8 @@ import { OrganizationController } from './OrganizationController'
import { IsOrgAdmin } from './middlewares/IsOrgAdmin'
import { IsOrgMember } from './middlewares/IsOrgMember'
import { IsOrgOwner } from './middlewares/IsOrgOwner'
+import { RequireTokenPermission } from '../../middlewares/require-token-permission'
+import { GoalPermissions } from '../../types/auth.types'
export default class OrganizationRoutes implements Routable {
private readonly router: ReturnType<typeof Router>
@@ -21,16 +23,20 @@ export default class OrganizationRoutes implements Routable {
}
initRoutes() {
- this.router.post('', [IsLoggedIn], this.controller.create)
+ const canManage = RequireTokenPermission(GoalPermissions.ORG_CAN_MANAGE)
+ const canManageMembers = RequireTokenPermission(GoalPermissions.ORG_CAN_MANAGE_MEMBERS)
+ const canView = RequireTokenPermission(GoalPermissions.ORG_CAN_VIEW)
+
+ this.router.post('', [IsLoggedIn, canManage], this.controller.create)
this.router.get('', [IsLoggedIn], this.controller.fetch)
- this.router.post('/members', [IsLoggedIn, IsOrgAdmin], this.controller.addMember)
- this.router.patch('/members/role', [IsLoggedIn, IsOrgAdmin], this.controller.updateMemberRole)
- this.router.delete('/members', [IsLoggedIn, IsOrgAdmin], this.controller.removeMember)
+ this.router.post('/members', [IsLoggedIn, IsOrgAdmin, canManageMembers], this.controller.addMember)
+ this.router.patch('/members/role', [IsLoggedIn, IsOrgAdmin, canManageMembers], this.controller.updateMemberRole)
+ this.router.delete('/members', [IsLoggedIn, IsOrgAdmin, canManageMembers], this.controller.removeMember)
- this.router.get('/:orgId', [IsLoggedIn, IsOrgMember], this.controller.getById)
- this.router.patch('/:orgId', [IsLoggedIn, IsOrgAdmin], this.controller.update)
- this.router.delete('/:orgId', [IsLoggedIn, IsOrgOwner], this.controller.delete)
- this.router.get('/:orgId/members', [IsLoggedIn, IsOrgAdmin], this.controller.fetchMembers)
+ this.router.get('/:orgId', [IsLoggedIn, IsOrgMember, canView], this.controller.getById)
+ this.router.patch('/:orgId', [IsLoggedIn, IsOrgAdmin, canManage], this.controller.update)
+ this.router.delete('/:orgId', [IsLoggedIn, IsOrgOwner, canManage], this.controller.delete)
+ this.router.get('/:orgId/members', [IsLoggedIn, IsOrgAdmin, canView], this.controller.fetchMembers)
}
}
diff --git a/api/src/tv-modules/organizations/__tests__/TokenScope.integration.spec.ts b/api/src/tv-modules/organizations/__tests__/TokenScope.integration.spec.ts
new file mode 100644
index 0000000..9e185cc
--- /dev/null
+++ b/api/src/tv-modules/organizations/__tests__/TokenScope.integration.spec.ts
@@ -0,0 +1,187 @@
+import axios from 'axios';
+import fs from 'fs/promises';
+import type http from 'http';
+import { join } from 'path';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { Database } from '../../../modules/db';
+import { GoalPermissions } from '../../../types/auth.types';
+
+const port = 1811;
+const url = `http://localhost:${port}`;
+const MIGRATION_DIR = join(__dirname, '../../../migrations/taskview/sql/1.65.0');
+
+const LOGIN = '[email protected]';
+const PASSWORD = 'user1!#Q';
+
+let server: http.Server;
+let jwt = '';
+const createdTokenIds: number[] = [];
+const createdOrgIds: number[] = [];
+let ownedGoalId = 0;
+
+const api = axios.create({ baseURL: url, validateStatus: () => true });
+
+const asUser = () => ({ headers: { Authorization: `Bearer ${jwt}` } });
+
+async function issueToken(allowedPermissions: string[]) {
+ const response = await api.post(
+ '/module/api-tokens',
+ { name: 'scope-probe', allowedPermissions, allowedGoalIds: [] },
+ asUser(),
+ );
+ expect(response.status).toBe(200);
+ createdTokenIds.push(response.data.response.item.id);
+ return { headers: { Authorization: `Bearer ${response.data.response.token}` } };
+}
+
+async function createOrg(auth: { headers: Record<string, string> }, name: string) {
+ const response = await api.post('/module/organizations', { name }, auth);
+ const id = response.data?.response?.id;
+ if (id) createdOrgIds.push(id);
+ return response;
+}
+
+describe('API token scope on organization-level surfaces', () => {
+ vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+ }));
+
+ beforeAll(async () => {
+ const db = Database.getInstance();
+ const client = await db.getClient();
+ for (const file of (await fs.readdir(MIGRATION_DIR)).sort()) {
+ await client.query(await fs.readFile(join(MIGRATION_DIR, file), 'utf-8'));
+ }
+ client.release();
+
+ server = new App(port).listen();
+
+ const login = await api.post('/module/auth/login', { login: LOGIN, password: PASSWORD });
+ 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.
+ const goal = await api.post('/module/goals', { name: `scope-goal-${Date.now()}` }, asUser());
+ expect(goal.status).toBe(200);
+ ownedGoalId = goal.data.response.id;
+ });
+
+ afterAll(async () => {
+ if (ownedGoalId) {
+ await api.delete('/module/goals', { ...asUser(), data: { goalId: ownedGoalId } });
+ }
+ for (const id of createdOrgIds) {
+ await api.delete(`/module/organizations/${id}`, asUser());
+ }
+ for (const id of createdTokenIds) {
+ await api.delete('/module/api-tokens', { ...asUser(), data: { id } });
+ }
+ server?.close();
+ });
+
+ it('seeds the organization permission group', async () => {
+ const db = Database.getInstance();
+ const result = await db.query<{ name: string }>(
+ 'SELECT name FROM tv_auth.permissions WHERE permission_group = 6 ORDER BY name',
+ );
+ expect(result?.rows.map((row) => row.name)).toEqual([
+ 'org_can_manage', 'org_can_manage_members', 'org_can_view', 'sso_can_manage', 'webhooks_can_manage',
+ ]);
+ });
+
+ it('offers the new permissions for selection, with localized descriptions', async () => {
+ const response = await api.get('/module/api-tokens/permissions', asUser());
+
+ expect(response.status).toBe(200);
+ const rows = response.data.response as {
+ name: string;
+ permissionGroup: number;
+ descriptionLocales: Record<string, string> | null;
+ }[];
+
+ const orgView = rows.find((row) => row.name === 'org_can_view');
+ expect(orgView?.permissionGroup).toBe(6);
+ expect(orgView?.descriptionLocales?.ru).toBeTruthy();
+
+ // Group 1 is enforced nowhere, so it must not be offered as a restriction.
+ expect(rows.some((row) => row.permissionGroup === 1)).toBe(false);
+ });
+
+ it('blocks a narrowly scoped token from creating an organization', async () => {
+ const token = await issueToken([GoalPermissions.TIMETRACKING_CAN_VIEW]);
+
+ const response = await createOrg(token, 'scope-probe-denied');
+
+ expect(response.status).toBe(403);
+ });
+
+ it('allows a token that was given org_can_manage', async () => {
+ const token = await issueToken([GoalPermissions.ORG_CAN_MANAGE]);
+
+ const response = await createOrg(token, 'scope-probe-allowed');
+
+ expect(response.status).toBe(200);
+ });
+
+ it('keeps an unrestricted token working, so existing integrations do not break', async () => {
+ const token = await issueToken([]);
+
+ const response = await createOrg(token, 'scope-probe-unrestricted');
+
+ expect(response.status).toBe(200);
+ });
+
+ it('does not restrict a browser session', async () => {
+ const response = await createOrg(asUser(), 'scope-probe-session');
+
+ expect(response.status).toBe(200);
+ });
+
+ it('separates managing the organization from managing its members', async () => {
+ const token = await issueToken([GoalPermissions.ORG_CAN_MANAGE]);
+ const org = await createOrg(token, 'scope-probe-members');
+ expect(org.status).toBe(200);
+
+ const response = await api.post(
+ '/module/organizations/members',
+ { organizationId: org.data.response.id, email: LOGIN, role: 'admin' },
+ token,
+ );
+
+ expect(response.status).toBe(403);
+ });
+
+ it('lets a token holding org_can_manage_members add one', async () => {
+ const owner = await issueToken([GoalPermissions.ORG_CAN_MANAGE]);
+ const org = await createOrg(owner, 'scope-probe-members-ok');
+ expect(org.status).toBe(200);
+
+ const member = await issueToken([GoalPermissions.ORG_CAN_MANAGE_MEMBERS]);
+ const response = await api.post(
+ '/module/organizations/members',
+ { organizationId: org.data.response.id, email: `member-${Date.now()}@test.dest`, role: 'member' },
+ member,
+ );
+
+ // A precise status, not merely "not 403" — that would also pass on a 500.
+ expect(response.status).toBe(200);
+ });
+
+ it('blocks a narrowly scoped token from reaching webhooks of a goal it owns', async () => {
+ const token = await issueToken([GoalPermissions.TIMETRACKING_CAN_VIEW]);
+
+ const response = await api.get(`/module/webhooks?goalId=${ownedGoalId}`, token);
+
+ 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]);
+
+ const response = await api.get(`/module/webhooks?goalId=${ownedGoalId}`, token);
+
+ expect(response.status).toBe(200);
+ });
+});
diff --git a/api/src/tv-modules/sso/SsoRoutes.ts b/api/src/tv-modules/sso/SsoRoutes.ts
index 56ce3ba..2fa332f 100644
--- a/api/src/tv-modules/sso/SsoRoutes.ts
+++ b/api/src/tv-modules/sso/SsoRoutes.ts
@@ -5,6 +5,8 @@ import { IsOrgAdmin } from '../organizations/middlewares/IsOrgAdmin'
import { IsSsoConfigAdmin } from './middlewares/IsSsoConfigAdmin'
import { RequireLoginMethod } from '../auth/middlewares/require-login-method'
import { SsoController } from './SsoController'
+import { RequireTokenPermission } from '../../middlewares/require-token-permission'
+import { GoalPermissions } from '../../types/auth.types'
export default class SsoRoutes implements Routable {
private readonly router: ReturnType<typeof Router>
@@ -26,15 +28,17 @@ export default class SsoRoutes implements Routable {
this.router.get('/callback/:configId', [RequireLoginMethod('sso')], this.controller.handleCallback)
this.router.post('/callback/:configId', [RequireLoginMethod('sso')], this.controller.handleCallback)
+ const canManageSso = RequireTokenPermission(GoalPermissions.SSO_CAN_MANAGE)
+
this.router.get('/admin/public-urls', [IsLoggedIn], this.controller.getPublicUrls)
- this.router.get('/admin/metadata', [IsLoggedIn, IsOrgAdmin], this.controller.parseMetadata)
- this.router.get('/admin/configs', [IsLoggedIn, IsOrgAdmin], this.controller.listConfigs)
- this.router.post('/admin/configs', [IsLoggedIn, IsOrgAdmin], this.controller.createConfig)
- this.router.patch('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin], this.controller.updateConfig)
- this.router.delete('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin], this.controller.deleteConfig)
- this.router.post('/admin/configs/:configId/verify-domain', [IsLoggedIn, IsSsoConfigAdmin], this.controller.startDomainVerification)
- this.router.post('/admin/configs/:configId/verify-domain/check', [IsLoggedIn, IsSsoConfigAdmin], this.controller.checkDomainVerification)
- this.router.post('/admin/configs/:configId/scim-token', [IsLoggedIn, IsSsoConfigAdmin], this.controller.generateScimToken)
- this.router.patch('/admin/configs/:configId/scim', [IsLoggedIn, IsSsoConfigAdmin], this.controller.toggleScim)
+ this.router.get('/admin/metadata', [IsLoggedIn, IsOrgAdmin, canManageSso], this.controller.parseMetadata)
+ this.router.get('/admin/configs', [IsLoggedIn, IsOrgAdmin, canManageSso], this.controller.listConfigs)
+ this.router.post('/admin/configs', [IsLoggedIn, IsOrgAdmin, canManageSso], this.controller.createConfig)
+ this.router.patch('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.updateConfig)
+ this.router.delete('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.deleteConfig)
+ this.router.post('/admin/configs/:configId/verify-domain', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.startDomainVerification)
+ this.router.post('/admin/configs/:configId/verify-domain/check', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.checkDomainVerification)
+ this.router.post('/admin/configs/:configId/scim-token', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.generateScimToken)
+ this.router.patch('/admin/configs/:configId/scim', [IsLoggedIn, IsSsoConfigAdmin, canManageSso], this.controller.toggleScim)
}
}
diff --git a/api/src/tv-modules/webhooks/WebhooksRoutes.ts b/api/src/tv-modules/webhooks/WebhooksRoutes.ts
index e600599..d3bdcb9 100644
--- a/api/src/tv-modules/webhooks/WebhooksRoutes.ts
+++ b/api/src/tv-modules/webhooks/WebhooksRoutes.ts
@@ -3,6 +3,8 @@ 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';
export default class WebhooksRoutes implements Routable {
private readonly router: ReturnType<typeof Router>
@@ -19,13 +21,15 @@ export default class WebhooksRoutes implements Routable {
}
initRoutes() {
- this.router.get('', [IsLoggedIn, IsGoalOwnerByGoalId], this.controller.fetch)
- this.router.post('', [IsLoggedIn, IsGoalOwnerByGoalId], this.controller.create)
- this.router.patch('', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.update)
- this.router.delete('', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.delete)
- this.router.post('/rotate-secret', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.rotateSecret)
- this.router.post('/test', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.testDelivery)
- this.router.get('/deliveries/:id', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.fetchDeliveries)
- this.router.post('/retry', [IsLoggedIn, IsGoalOwnerByWebhookId], this.controller.retryDelivery)
+ 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)
}
}
diff --git a/api/src/types/auth.types.ts b/api/src/types/auth.types.ts
index 53155c5..4ba1a08 100644
--- a/api/src/types/auth.types.ts
+++ b/api/src/types/auth.types.ts
@@ -194,6 +194,12 @@ export const GoalPermissions = {
TIMETRACKING_CAN_LOG: 'timetracking_can_log',
TIMETRACKING_CAN_MANAGE_ALL: 'timetracking_can_manage_all',
+ ORG_CAN_VIEW: 'org_can_view',
+ ORG_CAN_MANAGE: 'org_can_manage',
+ ORG_CAN_MANAGE_MEMBERS: 'org_can_manage_members',
+ SSO_CAN_MANAGE: 'sso_can_manage',
+ WEBHOOKS_CAN_MANAGE: 'webhooks_can_manage',
+
SPRINT_CAN_VIEW: 'sprint_can_view',
SPRINT_CAN_MANAGE: 'sprint_can_manage',
SPRINT_CAN_ASSIGN_TASKS: 'sprint_can_assign_tasks',
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.ts
new file mode 100644
index 0000000..3fc6819
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/__tests__/token-scope-organization.test.ts
@@ -0,0 +1,411 @@
+import { TvApi } from '@/tv';
+import axios from 'axios';
+import {
+ describe,
+ it,
+ expect,
+ beforeAll,
+ afterAll,
+} from 'vitest';
+import { initApi, API_URL } from './init-api';
+
+/**
+ * Organization, SSO and webhook endpoints are guarded by an organization role or
+ * by project ownership, not by the project RBAC, so before migration 1.65.0 they
+ * ignored the scope of an API token entirely: a token issued with a single
+ * permission could still create organizations and webhooks. These tests pin the
+ * fixed behaviour, including the deliberate escape hatch — a token with no
+ * permissions selected stays unrestricted.
+ */
+describe('API token scope on organization-level surfaces', () => {
+ let $api: TvApi;
+ const tokenIds: number[] = [];
+ const orgIds: number[] = [];
+ let goalId: number;
+
+ const clientFor = (token: string) => new TvApi(axios.create({
+ baseURL: API_URL,
+ headers: { Authorization: `Bearer ${token}` },
+ }));
+
+ const scopedClient = async (allowedPermissions: string[]) => {
+ const created = await $api.apiTokens.create({
+ name: `scope-${Date.now()}-${Math.random()}`,
+ allowedPermissions,
+ });
+ 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);
+
+ /**
+ * A permitted call must answer 200. Asserting merely "not 403" would also pass
+ * on a 500, which is how a broken endpoint gets mistaken for a working guard.
+ */
+ const expectAllowed = (status: number) => expect(status).toBe(200);
+
+ beforeAll(async () => {
+ const { $tvApi } = await initApi();
+ $api = $tvApi;
+
+ const goal = await $api.goals.createGoal({ name: `scope-goal-${Date.now()}` });
+ goalId = goal!.id!;
+ });
+
+ afterAll(async () => {
+ for (const id of orgIds) {
+ await $api.organizations.delete(id).catch(() => {});
+ }
+ for (const id of tokenIds) {
+ await $api.apiTokens.delete(id).catch(() => {});
+ }
+ await $api.goals.deleteGoal(goalId).catch(() => {});
+ });
+
+ describe('permission catalogue', () => {
+ it('offers the organization group for selection', async () => {
+ const permissions = await $api.apiTokens.fetchPermissions();
+ const names = permissions!.map((p) => p.name);
+
+ expect(names).toContain('org_can_view');
+ expect(names).toContain('org_can_manage');
+ expect(names).toContain('org_can_manage_members');
+ expect(names).toContain('sso_can_manage');
+ expect(names).toContain('webhooks_can_manage');
+ });
+
+ it('carries localized descriptions for them', async () => {
+ const permissions = await $api.apiTokens.fetchPermissions();
+ const orgManage = permissions!.find((p) => p.name === 'org_can_manage');
+
+ expect(orgManage!.permissionGroup).toBe(6);
+ expect(orgManage!.descriptionLocales?.en).toBeTruthy();
+ expect(orgManage!.descriptionLocales?.ru).toBeTruthy();
+ });
+
+ it('never offers group 1, which is enforced nowhere', async () => {
+ const permissions = await $api.apiTokens.fetchPermissions();
+
+ expect(permissions!.some((p) => p.permissionGroup === 1)).toBe(false);
+ });
+ });
+
+ describe('creating organizations', () => {
+ it('denies a token scoped to an unrelated permission', async () => {
+ const client = await scopedClient(['timetracking_can_view']);
+
+ const status = await statusOf(client.organizations.create({ name: `denied-${Date.now()}` }));
+
+ expect(status).toBe(403);
+ });
+
+ it('allows a token holding org_can_manage', async () => {
+ const client = await scopedClient(['org_can_manage']);
+
+ const org = await client.organizations.create({ name: `allowed-${Date.now()}` });
+
+ expect(org).toBeDefined();
+ orgIds.push(org!.id);
+ });
+
+ it('allows a token with no permissions selected — unrestricted by design', async () => {
+ const client = await scopedClient([]);
+
+ const org = await client.organizations.create({ name: `unrestricted-${Date.now()}` });
+
+ expect(org).toBeDefined();
+ orgIds.push(org!.id);
+ });
+
+ it('does not restrict a normal browser session', async () => {
+ const org = await $api.organizations.create({ name: `session-${Date.now()}` });
+
+ expect(org).toBeDefined();
+ orgIds.push(org!.id);
+ });
+ });
+
+ describe('managing members', () => {
+ it('separates org_can_manage from org_can_manage_members', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `members-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const status = await statusOf(owner.organizations.addMember({
+ organizationId: org!.id,
+ email: `member-${Date.now()}@test.dest`,
+ role: 'member',
+ }));
+
+ expect(status).toBe(403);
+ });
+
+ it('lets a token holding org_can_manage_members through the guard', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `members-ok-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const member = await scopedClient(['org_can_manage_members']);
+ const status = await statusOf(member.organizations.addMember({
+ organizationId: org!.id,
+ email: `member-${Date.now()}@test.dest`,
+ role: 'member',
+ }));
+
+ expectAllowed(status);
+ });
+
+ it('denies listing members without org_can_view', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `list-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const status = await statusOf(owner.organizations.fetchMembers(org!.id));
+
+ expect(status).toBe(403);
+ });
+
+ it('allows listing members with org_can_view', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `list-ok-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const viewer = await scopedClient(['org_can_view']);
+ const status = await statusOf(viewer.organizations.fetchMembers(org!.id));
+
+ expectAllowed(status);
+ });
+ });
+
+ describe('changing and deleting an organization', () => {
+ it('denies renaming without org_can_manage', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `rename-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const outsider = await scopedClient(['org_can_view']);
+ const status = await statusOf(outsider.organizations.update(org!.id, { name: 'renamed' }));
+
+ expect(status).toBe(403);
+ });
+
+ it('allows renaming with org_can_manage', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `rename-ok-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const status = await statusOf(owner.organizations.update(org!.id, { name: `renamed-${Date.now()}` }));
+
+ expectAllowed(status);
+ });
+
+ it('denies deleting without org_can_manage', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `delete-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const outsider = await scopedClient(['org_can_view']);
+ const status = await statusOf(outsider.organizations.delete(org!.id));
+
+ expect(status).toBe(403);
+ });
+ });
+
+ describe('changing and removing members', () => {
+ it('denies changing a role without org_can_manage_members', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `role-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const status = await statusOf(owner.organizations.updateMemberRole({
+ organizationId: org!.id,
+ email: `role-${Date.now()}@test.dest`,
+ role: 'admin',
+ }));
+
+ expect(status).toBe(403);
+ });
+
+ it('denies removing a member without org_can_manage_members', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `remove-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const status = await statusOf(owner.organizations.removeMember({
+ organizationId: org!.id,
+ email: `remove-${Date.now()}@test.dest`,
+ }));
+
+ expect(status).toBe(403);
+ });
+
+ it('lets org_can_manage_members past the guard on both', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `member-verbs-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const manager = await scopedClient(['org_can_manage_members']);
+ const email = `member-${Date.now()}@test.dest`;
+ await manager.organizations.addMember({ organizationId: org!.id, email, role: 'member' }).catch(() => {});
+
+ const roleStatus = await statusOf(manager.organizations.updateMemberRole({
+ organizationId: org!.id, email, role: 'admin',
+ }));
+ const removeStatus = await statusOf(manager.organizations.removeMember({
+ organizationId: org!.id, email,
+ }));
+
+ expectAllowed(roleStatus);
+ expectAllowed(removeStatus);
+ });
+ });
+
+ describe('SSO administration', () => {
+ it('denies listing configs without sso_can_manage', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `sso-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const status = await statusOf(owner.sso.listConfigs(org!.id));
+
+ expect(status).toBe(403);
+ });
+
+ it('allows listing configs with sso_can_manage', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `sso-ok-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const admin = await scopedClient(['sso_can_manage']);
+ const status = await statusOf(admin.sso.listConfigs(org!.id));
+
+ expectAllowed(status);
+ });
+
+ it('denies every other admin verb on a real config without sso_can_manage', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `sso-verbs-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ // A real config is required: IsSsoConfigAdmin runs first and would answer
+ // 404 for a made-up id, hiding whether the token check exists at all.
+ const admin = await scopedClient(['sso_can_manage']);
+ const config = await admin.sso.createConfig({
+ organizationId: org!.id,
+ protocol: 'oidc',
+ displayName: 'Scope probe',
+ emailDomainRestriction: `sso-${Date.now()}.test`,
+ });
+ expect(config).toBeDefined();
+ const configId = config!.id;
+
+ const results = await Promise.all([
+ statusOf(owner.sso.updateConfig(configId, { displayName: 'renamed' })),
+ statusOf(owner.sso.startDomainVerification(configId)),
+ statusOf(owner.sso.checkDomainVerification(configId)),
+ statusOf(owner.sso.generateScimToken(configId)),
+ statusOf(owner.sso.toggleScim(configId, true)),
+ statusOf(owner.sso.deleteConfig(configId)),
+ ]);
+
+ expect(results).toEqual([403, 403, 403, 403, 403, 403]);
+
+ await admin.sso.deleteConfig(configId).catch(() => {});
+ });
+
+ it('lets sso_can_manage change and delete a config', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `sso-admin-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const admin = await scopedClient(['sso_can_manage']);
+ const config = await admin.sso.createConfig({
+ organizationId: org!.id,
+ protocol: 'oidc',
+ displayName: 'Editable',
+ emailDomainRestriction: `sso-ok-${Date.now()}.test`,
+ });
+
+ const updateStatus = await statusOf(admin.sso.updateConfig(config!.id, { displayName: 'Renamed' }));
+ const deleteStatus = await statusOf(admin.sso.deleteConfig(config!.id));
+
+ expectAllowed(updateStatus);
+ expectAllowed(deleteStatus);
+ });
+
+ it('denies creating a config without sso_can_manage', async () => {
+ const owner = await scopedClient(['org_can_manage']);
+ const org = await owner.organizations.create({ name: `sso-create-${Date.now()}` });
+ orgIds.push(org!.id);
+
+ const status = await statusOf(owner.sso.createConfig({
+ organizationId: org!.id,
+ protocol: 'oidc',
+ displayName: 'Should not be created',
+ emailDomainRestriction: `sso-${Date.now()}.test`,
+ }));
+
+ expect(status).toBe(403);
+ });
+ });
+
+ describe('webhooks', () => {
+ it('denies a token scoped to an unrelated permission', async () => {
+ const client = await scopedClient(['timetracking_can_view']);
+
+ const status = await statusOf(client.webhooks.fetch(goalId));
+
+ expect(status).toBe(403);
+ });
+
+ it('allows a token holding webhooks_can_manage', async () => {
+ const client = await scopedClient(['webhooks_can_manage']);
+
+ const status = await statusOf(client.webhooks.fetch(goalId));
+
+ expectAllowed(status);
+ });
+
+ it('allows an unrestricted token', async () => {
+ const client = await scopedClient([]);
+
+ const status = await statusOf(client.webhooks.fetch(goalId));
+
+ expectAllowed(status);
+ });
+
+ it('denies creating a webhook without webhooks_can_manage', async () => {
+ const client = await scopedClient(['timetracking_can_view']);
+
+ const status = await statusOf(client.webhooks.create({
+ goalId,
+ url: 'https://exfiltration.test/hook',
+ events: ['task.created'],
+ }));
+
+ expect(status).toBe(403);
+ });
+
+ it('allows the full webhook lifecycle with webhooks_can_manage', async () => {
+ const client = await scopedClient(['webhooks_can_manage']);
+
+ const created = await client.webhooks.create({
+ goalId,
+ url: `https://receiver.test/${Date.now()}`,
+ events: ['task.created'],
+ });
+ expect(created).toBeDefined();
+
+ const updateStatus = await statusOf(client.webhooks.update({
+ id: created!.webhook.id,
+ events: ['task.created', 'task.updated'],
+ }));
+ const deleteStatus = await statusOf(client.webhooks.delete({ id: created!.webhook.id }));
+
+ expectAllowed(updateStatus);
+ expectAllowed(deleteStatus);
+ });
+ });
+});
diff --git a/taskview-packages/taskview-api/src/api/api-tokens.types.ts b/taskview-packages/taskview-api/src/api/api-tokens.types.ts
index 3774813..cb5d567 100644
--- a/taskview-packages/taskview-api/src/api/api-tokens.types.ts
+++ b/taskview-packages/taskview-api/src/api/api-tokens.types.ts
@@ -26,4 +26,6 @@ export type ApiTokenPermission = {
name: string;
description: string;
permissionGroup: number;
+ /** Per-locale description; keys match the app locales ('en', 'ru', 'de', 'es', 'pt-BR'). */
+ descriptionLocales?: Record<string, string> | null;
};
diff --git a/taskview-packages/taskview-db-schemas/src/schemas/users.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/users.schema.ts
index 788da35..7d831ad 100644
--- a/taskview-packages/taskview-db-schemas/src/schemas/users.schema.ts
+++ b/taskview-packages/taskview-db-schemas/src/schemas/users.schema.ts
@@ -17,7 +17,7 @@ export const PermissionsSchema = pgSchema('tv_auth').table('permissions', {
name: varchar().notNull(),
description: varchar(),
permissionGroup: integer('permission_group'),
- descriptionLocales: jsonb('description_locales'),
+ descriptionLocales: jsonb('description_locales').$type<Record<string, string> | null>(),
});
export type PermissionsSchemaTypeForSelect = typeof PermissionsSchema.$inferSelect;
diff --git a/taskview-packages/taskview-mcp/src/__tests__/integration/http-oauth-discovery.integration.test.ts b/taskview-packages/taskview-mcp/src/__tests__/integration/http-oauth-discovery.integration.test.ts
new file mode 100644
index 0000000..d46b3c4
--- /dev/null
+++ b/taskview-packages/taskview-mcp/src/__tests__/integration/http-oauth-discovery.integration.test.ts
@@ -0,0 +1,128 @@
+import { spawn, type ChildProcess } from 'node:child_process'
+import { join } from 'node:path'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+
+/**
+ * The HTTP transport is the entry point of OAuth discovery: a client knows only
+ * the /mcp URL, gets a 401, and follows WWW-Authenticate to the resource
+ * metadata. These run against the built dist/http.js as a real process, because
+ * that is what ships and what a client actually talks to.
+ */
+const PORT = 3199
+const PUBLIC_URL = `http://127.0.0.1:${PORT}`
+const TASKVIEW_URL = process.env.TASKVIEW_URL || 'http://127.0.0.1:11401'
+
+let server: ChildProcess
+
+async function waitForServer(attempts = 40) {
+ for (let i = 0; i < attempts; i++) {
+ try {
+ const response = await fetch(`${PUBLIC_URL}/health`)
+ if (response.ok) return
+ } catch {
+ // not listening yet
+ }
+ await new Promise((resolve) => setTimeout(resolve, 250))
+ }
+ throw new Error('MCP HTTP server did not start')
+}
+
+describe('MCP HTTP transport — OAuth discovery', () => {
+ beforeAll(async () => {
+ server = spawn('node', [join(__dirname, '../../../dist/http.js')], {
+ env: {
+ ...process.env,
+ TASKVIEW_URL,
+ MCP_PUBLIC_URL: PUBLIC_URL,
+ MCP_HTTP_PORT: String(PORT),
+ },
+ stdio: 'ignore',
+ })
+ await waitForServer()
+ })
+
+ afterAll(() => {
+ server?.kill()
+ })
+
+ it('answers an unauthenticated call with 401 and points at the resource metadata', async () => {
+ const response = await fetch(`${PUBLIC_URL}/mcp`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: '{}',
+ })
+
+ expect(response.status).toBe(401)
+ expect(response.headers.get('www-authenticate')).toBe(
+ `Bearer resource_metadata="${PUBLIC_URL}/.well-known/oauth-protected-resource"`,
+ )
+ })
+
+ it('publishes protected resource metadata naming the TaskView API as the authorization server', async () => {
+ const response = await fetch(`${PUBLIC_URL}/.well-known/oauth-protected-resource`)
+ const body = await response.json()
+
+ expect(response.status).toBe(200)
+ expect(body.resource).toBe(PUBLIC_URL)
+ expect(body.authorization_servers).toEqual([TASKVIEW_URL])
+ expect(body.bearer_methods_supported).toEqual(['header'])
+ })
+
+ it('uses MCP_PUBLIC_URL rather than the Host header, so a proxy cannot leak an internal address', async () => {
+ const response = await fetch(`${PUBLIC_URL}/.well-known/oauth-protected-resource`, {
+ headers: { Host: 'internal-name:9999' },
+ })
+ const body = await response.json()
+
+ expect(body.resource).toBe(PUBLIC_URL)
+ })
+
+ it('keeps /health open', async () => {
+ const response = await fetch(`${PUBLIC_URL}/health`)
+
+ expect(response.status).toBe(200)
+ expect((await response.json()).status).toBe('ok')
+ })
+
+ it('does not allow an unlisted browser origin', async () => {
+ const response = await fetch(`${PUBLIC_URL}/mcp`, {
+ method: 'OPTIONS',
+ headers: { Origin: 'https://evil.example.com' },
+ })
+
+ expect(response.headers.get('access-control-allow-origin')).toBeNull()
+ })
+
+ it('allows an origin listed in MCP_ALLOWED_ORIGINS', async () => {
+ const allowed = spawn('node', [join(__dirname, '../../../dist/http.js')], {
+ env: {
+ ...process.env,
+ TASKVIEW_URL,
+ MCP_PUBLIC_URL: `http://127.0.0.1:${PORT + 1}`,
+ MCP_HTTP_PORT: String(PORT + 1),
+ MCP_ALLOWED_ORIGINS: 'https://good.example.com',
+ },
+ stdio: 'ignore',
+ })
+
+ try {
+ for (let i = 0; i < 40; i++) {
+ try {
+ if ((await fetch(`http://127.0.0.1:${PORT + 1}/health`)).ok) break
+ } catch {
+ // not listening yet
+ }
+ await new Promise((resolve) => setTimeout(resolve, 250))
+ }
+
+ const response = await fetch(`http://127.0.0.1:${PORT + 1}/mcp`, {
+ method: 'OPTIONS',
+ headers: { Origin: 'https://good.example.com' },
+ })
+
+ expect(response.headers.get('access-control-allow-origin')).toBe('https://good.example.com')
+ } finally {
+ allowed.kill()
+ }
+ })
+})
diff --git a/web/src/components/features/base/TvPermissionPicker.vue b/web/src/components/features/base/TvPermissionPicker.vue
index f4567da..ff7068c 100644
--- a/web/src/components/features/base/TvPermissionPicker.vue
+++ b/web/src/components/features/base/TvPermissionPicker.vue
@@ -13,7 +13,7 @@
v-for="perm in group.items"
:key="perm.id"
:model-value="selected.includes(perm.name)"
- :label="perm.description || perm.name"
+ :label="describe(perm)"
@update:model-value="toggle(perm.name)"
/>
</div>
@@ -29,9 +29,17 @@ import type { ApiTokenPermission } from 'taskview-api'
const selected = defineModel<string[]>({ default: () => [] })
-const { t } = useI18n()
+const { t, locale } = useI18n()
const store = useApiTokensStore()
+// The table carries a per-locale description; fall back to the English column,
+// then to the raw key, so a permission added without translations still reads.
+function describe(permission: ApiTokenPermission): string {
+ return permission.descriptionLocales?.[locale.value]
+ || permission.description
+ || permission.name
+}
+
const groupedPermissions = computed(() => {
const groups: Record<number, { name: string; items: ApiTokenPermission[] }> = {}
for (const perm of store.permissions) {
diff --git a/web/src/locales/de.ts b/web/src/locales/de.ts
index b53e1b6..e836e7a 100644
--- a/web/src/locales/de.ts
+++ b/web/src/locales/de.ts
@@ -922,6 +922,8 @@ export default {
2: 'Projekt',
3: 'Listen',
4: 'Aufgaben',
+ 5: 'Sprints',
+ 6: 'Organisation',
},
oauth: {
consent: {
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index d90e19b..0404e4a 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -936,6 +936,8 @@ export default {
2: 'Project',
3: 'Lists',
4: 'Tasks',
+ 5: 'Sprints',
+ 6: 'Organization',
},
oauth: {
consent: {
diff --git a/web/src/locales/es.ts b/web/src/locales/es.ts
index b8484dc..f4ffcc2 100644
--- a/web/src/locales/es.ts
+++ b/web/src/locales/es.ts
@@ -922,6 +922,8 @@ export default {
2: 'Proyecto',
3: 'Listas',
4: 'Tareas',
+ 5: 'Sprints',
+ 6: 'Organización',
},
oauth: {
consent: {
diff --git a/web/src/locales/pt-br.ts b/web/src/locales/pt-br.ts
index 63451cb..da2cbff 100644
--- a/web/src/locales/pt-br.ts
+++ b/web/src/locales/pt-br.ts
@@ -933,6 +933,8 @@ export default {
2: 'Projeto',
3: 'Listas',
4: 'Tarefas',
+ 5: 'Sprints',
+ 6: 'Organização',
},
oauth: {
consent: {
diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.ts
index b4f2939..4262708 100644
--- a/web/src/locales/ru.ts
+++ b/web/src/locales/ru.ts
@@ -915,6 +915,8 @@ export default {
2: 'Проект',
3: 'Списки',
4: 'Задачи',
+ 5: 'Спринты',
+ 6: 'Организация',
},
oauth: {
consent: {