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
feat: OAuth
Nikolai Gimana173a870d76e
diff --git a/api/.env.example b/api/.env.exampleindex c82d87d..3998e78 100644--- a/api/.env.example+++ b/api/.env.example@@ -22,6 +22,15 @@ JWT_ALG=HS256# SSO: comma-separated email domains that skip DNS/HTTP ownership proof (air-gapped installs)#SSO_TRUSTED_DOMAINS=company.com,corp.local+# OAuth 2.1 for third-party MCP clients (ChatGPT, Claude connectors).+# Dynamic Client Registration is on by default; a cloud client cannot connect+# without it, since it has no way to pre-register with your instance. Turn it+# off on a private install that only uses manually seeded clients.+#OAUTH_DYNAMIC_REGISTRATION=false+# Public URL of this API. Used as the OAuth issuer in the discovery documents,+# so it must be the URL clients actually reach — set it behind a proxy.+#API_PUBLIC_URL=https://api.taskview.tech+# SMTP ConfigurationSMTP_HOST=smtp.domain.comSMTP_PORT=465diff --git a/api/src/middlewares/app-user-middleware.ts b/api/src/middlewares/app-user-middleware.tsindex dac7793..8622d91 100644--- a/api/src/middlewares/app-user-middleware.ts+++ b/api/src/middlewares/app-user-middleware.ts@@ -4,6 +4,7 @@ import { $logger } from '../modules/logget';import AuthController from '../tv-modules/auth/AuthController';import { getApiTokensManager } from '../tv-modules/api-tokens/ApiTokensManager';import { TOKEN_PREFIX } from '../tv-modules/api-tokens/types';+import { OAUTH_ACCESS_TOKEN_PREFIX } from '../tv-modules/oauth/types';export const appUserMiddleware = async (req: Request, res: Response, next: NextFunction) => {if (req.method === 'OPTIONS') {@@ -13,7 +14,7 @@ export const appUserMiddleware = async (req: Request, res: Response, next: NextFconst token = req.headers['authorization']?.split(' ')[1];- if (token && token.startsWith(TOKEN_PREFIX)) {+ if (token && (token.startsWith(TOKEN_PREFIX) || token.startsWith(OAUTH_ACCESS_TOKEN_PREFIX))) {const record = await getApiTokensManager().validateToken(token);if (record) {const authManager = new AppUser().authManager;diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.jsonindex 95aface..c4070b0 100644--- a/api/src/migrations/taskview/migrate.json+++ b/api/src/migrations/taskview/migrate.json@@ -750,5 +750,22 @@"SSO configs require proving ownership of email_domain_restriction before login is allowed: DNS TXT taskview-sso-verify=<token> or https://<domain>/.well-known/taskview-sso-verify.txt. Air-gapped installs can skip this for listed domains via SSO_TRUSTED_DOMAINS.","Replaces the plain UNIQUE(email_domain_restriction) with a partial unique index over verified configs only, so an unverified config can no longer squat a domain and block its real owner — multiple orgs may hold a pending config for the same domain, but only one can verify it (first-to-verify wins)."]+ },+ "59": {+ "version": "1.64.0",+ "name": "OAuth 2.1 authorization server",+ "releaseDate": "20260830",+ "scripts": [+ "/1.64.0/0.create-oauth-clients.sql",+ "/1.64.0/1.create-oauth-auth-codes.sql",+ "/1.64.0/2.create-oauth-grants.sql",+ "/1.64.0/3.alter-api-tokens-grant-id.sql"+ ],+ "description": [+ "OAuth 2.1 authorization server so third-party MCP clients (ChatGPT, Claude connectors) can act on a user's behalf without the user pasting a permanent tvk_ API token into them.",+ "tv_auth.oauth_clients holds the client registry (manually seeded or created via RFC 7591 Dynamic Client Registration); public clients carry no secret and are authenticated by PKCE S256 alone.",+ "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."+ ]}}diff --git a/api/src/migrations/taskview/sql/1.64.0/0.create-oauth-clients.sql b/api/src/migrations/taskview/sql/1.64.0/0.create-oauth-clients.sqlnew file mode 100644index 0000000..cb0e657--- /dev/null+++ b/api/src/migrations/taskview/sql/1.64.0/0.create-oauth-clients.sql@@ -0,0 +1,16 @@+-- OAuth 2.1 client registry. Clients are either seeded manually by an operator+-- or created through Dynamic Client Registration (RFC 7591) when it is enabled.+-- Public clients (MCP clients such as ChatGPT or Claude) hold no secret and are+-- authenticated by PKCE alone, so client_secret_hash stays NULL for them.+CREATE TABLE IF NOT EXISTS tv_auth.oauth_clients (+ id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,+ client_id VARCHAR(64) NOT NULL UNIQUE,+ client_secret_hash VARCHAR(64),+ name VARCHAR(200) NOT NULL,+ redirect_uris VARCHAR[] NOT NULL DEFAULT '{}',+ created_via VARCHAR(16) NOT NULL DEFAULT 'manual',+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ CONSTRAINT oauth_clients_created_via_check CHECK (created_via IN ('manual', 'dcr'))+);++CREATE INDEX IF NOT EXISTS idx_oauth_clients_client_id ON tv_auth.oauth_clients(client_id);diff --git a/api/src/migrations/taskview/sql/1.64.0/1.create-oauth-auth-codes.sql b/api/src/migrations/taskview/sql/1.64.0/1.create-oauth-auth-codes.sqlnew file mode 100644index 0000000..cee65f5--- /dev/null+++ b/api/src/migrations/taskview/sql/1.64.0/1.create-oauth-auth-codes.sql@@ -0,0 +1,24 @@+-- Short-lived, single-use authorization codes issued by the consent screen and+-- redeemed once at the token endpoint. Only the hash is stored, mirroring+-- tv_auth.api_tokens. used_at is set on redemption: a second redemption of the+-- same code is treated as replay and revokes the grant it produced.+CREATE TABLE IF NOT EXISTS tv_auth.oauth_auth_codes (+ id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,+ code_hash VARCHAR(64) NOT NULL UNIQUE,+ client_id VARCHAR(64) NOT NULL REFERENCES tv_auth.oauth_clients(client_id) ON DELETE CASCADE,+ user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,+ redirect_uri VARCHAR NOT NULL,+ code_challenge VARCHAR(128) NOT NULL,+ code_challenge_method VARCHAR(8) NOT NULL DEFAULT 'S256',+ allowed_permissions VARCHAR[] NOT NULL DEFAULT '{}',+ allowed_goal_ids INTEGER[] NOT NULL DEFAULT '{}',+ resource VARCHAR,+ expires_at TIMESTAMP NOT NULL,+ used_at TIMESTAMP,+ grant_id INTEGER,+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ CONSTRAINT oauth_auth_codes_challenge_method_check CHECK (code_challenge_method = 'S256')+);++CREATE INDEX IF NOT EXISTS idx_oauth_auth_codes_code_hash ON tv_auth.oauth_auth_codes(code_hash);+CREATE INDEX IF NOT EXISTS idx_oauth_auth_codes_expires_at ON tv_auth.oauth_auth_codes(expires_at);diff --git a/api/src/migrations/taskview/sql/1.64.0/2.create-oauth-grants.sql b/api/src/migrations/taskview/sql/1.64.0/2.create-oauth-grants.sqlnew file mode 100644index 0000000..e470741--- /dev/null+++ b/api/src/migrations/taskview/sql/1.64.0/2.create-oauth-grants.sql@@ -0,0 +1,33 @@+-- One row per (user, client) authorization — this is what the user sees and+-- revokes as a "connected app". The refresh token hangs off the grant and is+-- rotated on every use; refresh_token_prev_hash keeps the previous value so a+-- replayed refresh token can be detected and the whole grant revoked.+CREATE TABLE IF NOT EXISTS tv_auth.oauth_grants (+ id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,+ user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,+ client_id VARCHAR(64) NOT NULL REFERENCES tv_auth.oauth_clients(client_id) ON DELETE CASCADE,+ allowed_permissions VARCHAR[] NOT NULL DEFAULT '{}',+ allowed_goal_ids INTEGER[] NOT NULL DEFAULT '{}',+ resource VARCHAR,+ refresh_token_hash VARCHAR(64) UNIQUE,+ refresh_token_prev_hash VARCHAR(64),+ refresh_expires_at TIMESTAMP,+ last_used_at TIMESTAMP,+ revoked_at TIMESTAMP,+ created_at TIMESTAMP NOT NULL DEFAULT NOW()+);++CREATE INDEX IF NOT EXISTS idx_oauth_grants_user_id ON tv_auth.oauth_grants(user_id);+CREATE INDEX IF NOT EXISTS idx_oauth_grants_refresh_token_hash ON tv_auth.oauth_grants(refresh_token_hash);+CREATE INDEX IF NOT EXISTS idx_oauth_grants_prev_refresh_hash ON tv_auth.oauth_grants(refresh_token_prev_hash);++DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint WHERE conname = 'oauth_auth_codes_grant_id_fkey'+ ) THEN+ ALTER TABLE tv_auth.oauth_auth_codes+ ADD CONSTRAINT oauth_auth_codes_grant_id_fkey+ FOREIGN KEY (grant_id) REFERENCES tv_auth.oauth_grants(id) ON DELETE SET NULL;+ END IF;+END $$;diff --git a/api/src/migrations/taskview/sql/1.64.0/3.alter-api-tokens-grant-id.sql b/api/src/migrations/taskview/sql/1.64.0/3.alter-api-tokens-grant-id.sqlnew file mode 100644index 0000000..c979f88--- /dev/null+++ b/api/src/migrations/taskview/sql/1.64.0/3.alter-api-tokens-grant-id.sql@@ -0,0 +1,19 @@+-- OAuth access tokens live in tv_auth.api_tokens alongside manually issued+-- tvk_ tokens: same opaque-token storage, same validation path, same permission+-- intersection. grant_id ties an access token to the OAuth grant that minted it,+-- so revoking a connected app deletes its live access tokens immediately.+ALTER TABLE tv_auth.api_tokens+ ADD COLUMN IF NOT EXISTS grant_id INTEGER;++DO $$+BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint WHERE conname = 'api_tokens_grant_id_fkey'+ ) THEN+ ALTER TABLE tv_auth.api_tokens+ ADD CONSTRAINT api_tokens_grant_id_fkey+ FOREIGN KEY (grant_id) REFERENCES tv_auth.oauth_grants(id) ON DELETE CASCADE;+ END IF;+END $$;++CREATE INDEX IF NOT EXISTS idx_api_tokens_grant_id ON tv_auth.api_tokens(grant_id);diff --git a/api/src/routes/index.ts b/api/src/routes/index.tsindex fd8d287..d75993a 100644--- a/api/src/routes/index.ts+++ b/api/src/routes/index.ts@@ -8,6 +8,8 @@ import NotificationsRoutes from '../tv-modules/notifications/NotificationsRoutesimport WebhooksRoutes from '../tv-modules/webhooks/WebhooksRoutes';import MessagingRoutes from '../tv-modules/messaging/MessagingRoutes';import ApiTokensRoutes from '../tv-modules/api-tokens/ApiTokensRoutes';+import OAuthRoutes from '../tv-modules/oauth/OAuthRoutes';+import OAuthWellKnownRoutes from '../tv-modules/oauth/OAuthWellKnownRoutes';import SessionsRoutes from '../tv-modules/sessions/SessionsRoutes';import KanbanRoutes from '../tv-modules/kanban/KanbanRoutes';import GoalListRoutes from '../tv-modules/lists/GoalListRoutes';@@ -42,6 +44,7 @@ const routes: Record<string, RoutableConstructor> = {'/module/webhooks': WebhooksRoutes,'/module/messaging': MessagingRoutes,'/module/api-tokens': ApiTokensRoutes,+ '/module/oauth': OAuthRoutes,'/module/sessions': SessionsRoutes,'/module/organizations': OrganizationRoutes,'/module/sso': SsoRoutes,@@ -51,6 +54,7 @@ const routes: Record<string, RoutableConstructor> = {'/module/sprints': SprintsRoutes,'/module/recurrence': RecurrenceRoutes,'/scim/v2': ScimRoutes,+ '/.well-known': OAuthWellKnownRoutes,};export default routes;diff --git a/api/src/tv-modules/api-tokens/ApiTokensRepository.ts b/api/src/tv-modules/api-tokens/ApiTokensRepository.tsindex 9ab04c8..fbbd758 100644--- a/api/src/tv-modules/api-tokens/ApiTokensRepository.ts+++ b/api/src/tv-modules/api-tokens/ApiTokensRepository.ts@@ -1,4 +1,4 @@-import { and, eq } from 'drizzle-orm';+import { and, eq, isNull } from 'drizzle-orm';import { ApiTokensSchema, type ApiTokensSchemaTypeForSelect } from 'taskview-db-schemas';import { Database } from '../../modules/db';import { callWithCatch } from '../../utils/helpers';@@ -20,15 +20,21 @@ export class ApiTokensRepository {async delete(id: number, userId: number): Promise<boolean> {const result = await callWithCatch(() =>this.db.dbDrizzle.delete(ApiTokensSchema).where(- and(eq(ApiTokensSchema.id, id), eq(ApiTokensSchema.userId, userId))+ and(eq(ApiTokensSchema.id, id), eq(ApiTokensSchema.userId, userId), isNull(ApiTokensSchema.grantId))));return !!result?.rowCount;}+ /**+ * Only manually issued tokens. OAuth access tokens live in the same table but+ * belong to a grant - they are listed and revoked as connected apps instead.+ */async fetchByUserId(userId: number): Promise<ApiTokensSchemaTypeForSelect[]> {const result = await callWithCatch(() =>- this.db.dbDrizzle.select().from(ApiTokensSchema).where(eq(ApiTokensSchema.userId, userId))+ this.db.dbDrizzle.select().from(ApiTokensSchema).where(+ and(eq(ApiTokensSchema.userId, userId), isNull(ApiTokensSchema.grantId))+ ));return result ?? [];}diff --git a/api/src/tv-modules/oauth/OAuthController.ts b/api/src/tv-modules/oauth/OAuthController.tsnew file mode 100644index 0000000..cb4104d--- /dev/null+++ b/api/src/tv-modules/oauth/OAuthController.ts@@ -0,0 +1,294 @@+import type { Request, Response } from 'express'+import { ArkErrors } from 'arktype'+import { PublicApiUrl } from '../../modules/public-url'+import { OAuthManager } from './OAuthManager'+import {+ type SendTokenErrorArgs,+ type SendTokenSuccessArgs,+ OAuthAuthorizeArkType,+ OAuthConsentArkType,+ OAuthRegisterArkType,+ OAuthRevokeArkType,+ OAuthTokenArkType,+} from './types'+import {+ buildRedirectUrl,+ isAcceptableRedirectUri,+ isDcrEnabled,+} from './oauth.utils'++export class OAuthController {+ private get manager() { return OAuthManager.getInstance() }++ authorize = async (req: Request, res: Response) => {+ const params = OAuthAuthorizeArkType(req.query)+ if (params instanceof ArkErrors) {+ return res.status(400).send(params.summary)+ }++ const client = await this.manager.validateRedirectUri({+ clientId: params.client_id,+ redirectUri: params.redirect_uri,+ })+ if (!client.ok) {+ return res.status(400).send(client.description)+ }++ const consentUrl = buildRedirectUrl({+ redirectUri: `${process.env.APP_URL}/oauth/consent`,+ params: {+ client_id: params.client_id,+ client_name: client.value.name,+ redirect_uri: params.redirect_uri,+ code_challenge: params.code_challenge,+ code_challenge_method: params.code_challenge_method,+ state: params.state,+ resource: params.resource,+ },+ })+ return res.redirect(consentUrl)+ }++ consent = async (req: Request, res: Response) => {+ const data = OAuthConsentArkType(req.body)+ if (data instanceof ArkErrors) {+ return res.status(400).send(data.summary)+ }++ const userId = req.appUser.getUserData()?.id+ if (!userId) return res.status(401).end()++ const client = await this.manager.validateRedirectUri({+ clientId: data.client_id,+ redirectUri: data.redirect_uri,+ })+ if (!client.ok) {+ return res.status(400).send(client.description)+ }++ // Empty means "do not narrow", matching how a tvk_ token with no+ // permissions selected behaves. The user's own RBAC is still the ceiling.+ const code = await this.manager.issueAuthCode({+ clientId: data.client_id,+ userId,+ redirectUri: data.redirect_uri,+ codeChallenge: data.code_challenge,+ codeChallengeMethod: data.code_challenge_method,+ allowedPermissions: data.allowedPermissions ?? [],+ allowedGoalIds: data.allowedGoalIds ?? [],+ resource: data.resource ?? null,+ })+ if (!code) return res.status(500).end()++ return res.tvJson({+ redirectUrl: buildRedirectUrl({+ redirectUri: data.redirect_uri,+ params: { code, state: data.state },+ }),+ })+ }++ denyConsent = async (req: Request, res: Response) => {+ const data = OAuthConsentArkType(req.body)+ if (data instanceof ArkErrors) {+ return res.status(400).send(data.summary)+ }++ const client = await this.manager.validateRedirectUri({+ clientId: data.client_id,+ redirectUri: data.redirect_uri,+ })+ if (!client.ok) {+ return res.status(400).send(client.description)+ }++ return res.tvJson({+ redirectUrl: buildRedirectUrl({+ redirectUri: data.redirect_uri,+ params: { error: 'access_denied', state: data.state },+ }),+ })+ }++ token = async (req: Request, res: Response) => {+ const data = OAuthTokenArkType(req.body)+ if (data instanceof ArkErrors) {+ return this.sendTokenError({ res, status: 400, error: 'invalid_request', description: data.summary })+ }++ const basic = this.readBasicAuth(req)+ const clientId = basic?.clientId ?? data.client_id+ const clientSecret = basic?.clientSecret ?? data.client_secret+ if (!clientId) {+ return this.sendTokenError({ res, status: 401, error: 'invalid_client', description: 'client_id is required' })+ }++ const client = await this.manager.authenticateClient({ clientId, clientSecret })+ if (!client.ok) {+ return this.sendTokenError({ res, status: 401, error: client.error, description: client.description })+ }++ const resource = data.resource ?? null++ if (data.grant_type === 'authorization_code') {+ if (!data.code || !data.code_verifier || !data.redirect_uri) {+ return this.sendTokenError({+ res,+ status: 400,+ error: 'invalid_request',+ description: 'code, code_verifier and redirect_uri are required',+ })+ }+ const result = await this.manager.exchangeCode({+ code: data.code,+ codeVerifier: data.code_verifier,+ clientId,+ redirectUri: data.redirect_uri,+ resource,+ })+ if (!result.ok) {+ return this.sendTokenError({ res, status: 400, error: result.error, description: result.description })+ }+ return this.sendTokenSuccess({ res, body: result.value })+ }++ if (!data.refresh_token) {+ return this.sendTokenError({ res, status: 400, error: 'invalid_request', description: 'refresh_token is required' })+ }+ const refreshed = await this.manager.refreshTokens({+ refreshToken: data.refresh_token,+ clientId,+ resource,+ })+ if (!refreshed.ok) {+ return this.sendTokenError({ res, status: 400, error: refreshed.error, description: refreshed.description })+ }+ return this.sendTokenSuccess({ res, body: refreshed.value })+ }++ register = async (req: Request, res: Response) => {+ if (!isDcrEnabled()) {+ return res.status(403).json({+ error: 'access_denied',+ error_description: 'Dynamic client registration is disabled on this instance',+ })+ }++ const data = OAuthRegisterArkType(req.body)+ if (data instanceof ArkErrors) {+ return res.status(400).json({ error: 'invalid_client_metadata', error_description: data.summary })+ }++ const rejected = data.redirect_uris.find((uri) => !isAcceptableRedirectUri(uri))+ if (rejected) {+ return res.status(400).json({+ error: 'invalid_redirect_uri',+ error_description: `redirect_uri must be https or loopback http: ${rejected}`,+ })+ }++ const name = data.client_name?.trim() || 'Unnamed client'+ const isPublic = (data.token_endpoint_auth_method ?? 'none') === 'none'+ const result = await this.manager.registerClient({+ name,+ redirectUris: data.redirect_uris,+ isPublic,+ })+ if (!result.ok) {+ return res.status(500).json({ error: result.error, error_description: result.description })+ }++ return res.status(201).json({+ client_id: result.value.clientId,+ ...(result.value.clientSecret ? { client_secret: result.value.clientSecret } : {}),+ client_name: name,+ redirect_uris: data.redirect_uris,+ token_endpoint_auth_method: isPublic ? 'none' : 'client_secret_post',+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ })+ }++ revoke = async (req: Request, res: Response) => {+ const data = OAuthRevokeArkType(req.body)+ if (data instanceof ArkErrors) {+ return res.status(400).send(data.summary)+ }+ // RFC 7009: revocation always answers 200, even for an unknown token.+ await this.manager.revokeToken(data.token)+ return res.status(200).end()+ }++ fetchConnectedApps = async (req: Request, res: Response) => {+ const userId = req.appUser.getUserData()?.id+ if (!userId) return res.status(401).end()++ const result = await this.manager.fetchConnectedApps(userId)+ return res.tvJson(result)+ }++ revokeConnectedApp = async (req: Request, res: Response) => {+ const userId = req.appUser.getUserData()?.id+ if (!userId) return res.status(401).end()++ const grantId = Number(req.body?.grantId)+ if (!Number.isInteger(grantId) || grantId <= 0) {+ return res.status(400).send('grantId must be a positive integer')+ }++ const result = await this.manager.revokeGrant({ grantId, userId })+ return res.tvJson(result)+ }++ authorizationServerMetadata = async (req: Request, res: Response) => {+ const issuer = PublicApiUrl.base(req)+ return res.json({+ issuer,+ authorization_endpoint: `${issuer}/module/oauth/authorize`,+ token_endpoint: `${issuer}/module/oauth/token`,+ revocation_endpoint: `${issuer}/module/oauth/revoke`,+ ...(isDcrEnabled() ? { registration_endpoint: `${issuer}/module/oauth/register` } : {}),+ response_types_supported: ['code'],+ grant_types_supported: ['authorization_code', 'refresh_token'],+ code_challenge_methods_supported: ['S256'],+ token_endpoint_auth_methods_supported: ['none', 'client_secret_post', 'client_secret_basic'],+ })+ }++ protectedResourceMetadata = async (req: Request, res: Response) => {+ const issuer = PublicApiUrl.base(req)+ return res.json({+ resource: issuer,+ authorization_servers: [issuer],+ bearer_methods_supported: ['header'],+ })+ }++ private readBasicAuth(req: Request): { clientId: string; clientSecret: string } | null {+ const header = req.headers.authorization+ if (!header?.toLowerCase().startsWith('basic ')) return null++ const decoded = Buffer.from(header.slice(6).trim(), 'base64').toString('utf8')+ const separator = decoded.indexOf(':')+ if (separator < 0) return null++ return {+ clientId: decodeURIComponent(decoded.slice(0, separator)),+ clientSecret: decodeURIComponent(decoded.slice(separator + 1)),+ }+ }++ private sendTokenSuccess(args: SendTokenSuccessArgs) {+ args.res.setHeader('Cache-Control', 'no-store')+ args.res.setHeader('Pragma', 'no-cache')+ return args.res.json(args.body)+ }++ private sendTokenError(args: SendTokenErrorArgs) {+ args.res.setHeader('Cache-Control', 'no-store')+ return args.res.status(args.status).json({+ error: args.error,+ error_description: args.description,+ })+ }+}diff --git a/api/src/tv-modules/oauth/OAuthManager.ts b/api/src/tv-modules/oauth/OAuthManager.tsnew file mode 100644index 0000000..9b153d1--- /dev/null+++ b/api/src/tv-modules/oauth/OAuthManager.ts@@ -0,0 +1,258 @@+import { randomBytes } from 'crypto'+import type { OAuthClientsSchemaTypeForSelect, OAuthGrantsSchemaTypeForSelect } from 'taskview-db-schemas'+import { OAuthRepository } from './OAuthRepository'+import {+ OAUTH_ACCESS_TOKEN_PREFIX,+ OAUTH_ACCESS_TOKEN_TTL_SECONDS,+ OAUTH_CODE_TTL_SECONDS,+ OAUTH_REFRESH_TOKEN_TTL_SECONDS,+ type AuthenticateClientArgs,+ type ConnectedApp,+ type CreateAuthCodeArgs,+ type ExchangeCodeArgs,+ type IssueTokenPairArgs,+ type OAuthResult,+ type OAuthTokenResponse,+ type RefreshTokensArgs,+ type RegisterClientArgs,+ type RevokeOwnGrantArgs,+ type ValidateRedirectUriArgs,+} from './types'+import {+ matchesRegisteredRedirectUri,+ randomToken,+ resourceMatches,+ safeCompareHex,+ sha256Hex,+ verifyPkce,+} from './oauth.utils'++export class OAuthManager {+ private static instance: OAuthManager | null = null++ public readonly repository: OAuthRepository++ constructor() {+ this.repository = new OAuthRepository()+ }++ static getInstance(): OAuthManager {+ if (!OAuthManager.instance) OAuthManager.instance = new OAuthManager()+ return OAuthManager.instance+ }++ async findClient(clientId: string): Promise<OAuthClientsSchemaTypeForSelect | null> {+ return this.repository.findClientByClientId(clientId)+ }++ async validateRedirectUri(args: ValidateRedirectUriArgs): Promise<OAuthResult<OAuthClientsSchemaTypeForSelect>> {+ const client = await this.repository.findClientByClientId(args.clientId)+ if (!client) {+ return { ok: false, error: 'invalid_client', description: 'Unknown client_id' }+ }+ if (!matchesRegisteredRedirectUri({ candidate: args.redirectUri, registered: client.redirectUris })) {+ return { ok: false, error: 'invalid_request', description: 'redirect_uri does not match a registered URI' }+ }+ return { ok: true, value: client }+ }++ async issueAuthCode(args: CreateAuthCodeArgs): Promise<string | null> {+ const code = randomToken()+ const created = await this.repository.createAuthCode({+ ...args,+ codeHash: sha256Hex(code),+ expiresAt: new Date(Date.now() + OAUTH_CODE_TTL_SECONDS * 1000),+ })+ if (!created) return null++ this.repository.deleteExpiredAuthCodes().catch(() => {})+ return code+ }++ async exchangeCode(args: ExchangeCodeArgs): Promise<OAuthResult<OAuthTokenResponse>> {+ const record = await this.repository.findAuthCodeByHash(sha256Hex(args.code))+ if (!record) {+ return { ok: false, error: 'invalid_grant', description: 'Authorization code is not valid' }+ }++ // A code presented twice means it leaked. Kill the grant it already produced.+ if (record.usedAt) {+ if (record.grantId) await this.repository.revokeGrant({ grantId: record.grantId })+ return { ok: false, error: 'invalid_grant', description: 'Authorization code has already been used' }+ }+ if (record.expiresAt < new Date()) {+ return { ok: false, error: 'invalid_grant', description: 'Authorization code has expired' }+ }+ if (record.clientId !== args.clientId) {+ return { ok: false, error: 'invalid_grant', description: 'Authorization code was issued to another client' }+ }+ if (record.redirectUri !== args.redirectUri) {+ return { ok: false, error: 'invalid_grant', description: 'redirect_uri does not match the authorization request' }+ }+ if (!verifyPkce({ codeVerifier: args.codeVerifier, codeChallenge: record.codeChallenge })) {+ return { ok: false, error: 'invalid_grant', description: 'code_verifier does not match code_challenge' }+ }+ if (!resourceMatches({ granted: record.resource, requested: args.resource })) {+ return { ok: false, error: 'invalid_target', description: 'resource does not match the authorization request' }+ }++ const client = await this.repository.findClientByClientId(record.clientId)++ const grant = await this.repository.createGrant({+ userId: record.userId,+ clientId: record.clientId,+ allowedPermissions: record.allowedPermissions,+ allowedGoalIds: record.allowedGoalIds,+ resource: record.resource,+ })+ if (!grant) {+ return { ok: false, error: 'server_error', description: 'Could not create the grant' }+ }++ const consumed = await this.repository.consumeAuthCode({ id: record.id, grantId: grant.id })+ if (!consumed) {+ await this.repository.revokeGrant({ grantId: grant.id })+ return { ok: false, error: 'invalid_grant', description: 'Authorization code has already been used' }+ }++ return this.issueTokenPair({ grant, clientName: client?.name ?? record.clientId })+ }++ async refreshTokens(args: RefreshTokensArgs): Promise<OAuthResult<OAuthTokenResponse>> {+ const presentedHash = sha256Hex(args.refreshToken)+ const grant = await this.repository.findGrantByRefreshHash(presentedHash)+ if (!grant) {+ return { ok: false, error: 'invalid_grant', description: 'Refresh token is not valid' }+ }+ if (grant.revokedAt) {+ return { ok: false, error: 'invalid_grant', description: 'This authorization has been revoked' }+ }++ // The previous token in the rotation chain showing up means it leaked.+ if (grant.refreshTokenPrevHash && safeCompareHex(grant.refreshTokenPrevHash, presentedHash)) {+ await this.repository.revokeGrant({ grantId: grant.id })+ return { ok: false, error: 'invalid_grant', description: 'Refresh token was reused; the authorization has been revoked' }+ }+ if (grant.refreshExpiresAt && grant.refreshExpiresAt < new Date()) {+ return { ok: false, error: 'invalid_grant', description: 'Refresh token has expired' }+ }+ if (grant.clientId !== args.clientId) {+ return { ok: false, error: 'invalid_grant', description: 'Refresh token was issued to another client' }+ }+ if (!resourceMatches({ granted: grant.resource, requested: args.resource })) {+ return { ok: false, error: 'invalid_target', description: 'resource does not match the granted audience' }+ }++ const client = await this.repository.findClientByClientId(grant.clientId)+ return this.issueTokenPair({ grant, clientName: client?.name ?? grant.clientId, prevRefreshHash: presentedHash })+ }++ async registerClient(args: RegisterClientArgs): Promise<OAuthResult<{ clientId: string; clientSecret: string | null }>> {+ const clientId = randomBytes(16).toString('hex')+ const clientSecret = args.isPublic ? null : randomToken()++ const client = await this.repository.createClient({+ clientId,+ clientSecretHash: clientSecret ? sha256Hex(clientSecret) : null,+ name: args.name.slice(0, 200),+ redirectUris: args.redirectUris,+ createdVia: 'dcr',+ })+ if (!client) {+ return { ok: false, error: 'server_error', description: 'Could not register the client' }+ }+ return { ok: true, value: { clientId, clientSecret } }+ }++ async authenticateClient(args: AuthenticateClientArgs): Promise<OAuthResult<OAuthClientsSchemaTypeForSelect>> {+ const client = await this.repository.findClientByClientId(args.clientId)+ if (!client) {+ return { ok: false, error: 'invalid_client', description: 'Unknown client_id' }+ }+ if (client.clientSecretHash) {+ if (!args.clientSecret || !safeCompareHex(client.clientSecretHash, sha256Hex(args.clientSecret))) {+ return { ok: false, error: 'invalid_client', description: 'Client authentication failed' }+ }+ }+ return { ok: true, value: client }+ }++ async fetchConnectedApps(userId: number): Promise<ConnectedApp[]> {+ const grants = await this.repository.fetchGrantsByUserId(userId)+ if (!grants.length) return []++ const clients = await this.repository.fetchClientsByClientIds(grants.map((grant) => grant.clientId))+ const nameByClientId = new Map(clients.map((client) => [client.clientId, client.name]))++ return grants.map((grant) => ({+ grantId: grant.id,+ clientId: grant.clientId,+ clientName: nameByClientId.get(grant.clientId) ?? grant.clientId,+ allowedPermissions: grant.allowedPermissions,+ allowedGoalIds: grant.allowedGoalIds,+ createdAt: grant.createdAt,+ lastUsedAt: grant.lastUsedAt,+ }))+ }++ async revokeGrant(args: RevokeOwnGrantArgs): Promise<boolean> {+ return this.repository.revokeGrant(args)+ }++ /** RFC 7009: accepts either an access token or a refresh token. */+ async revokeToken(token: string): Promise<void> {+ const hash = sha256Hex(token)++ const grantId = await this.repository.findGrantIdByAccessTokenHash(hash)+ if (grantId) {+ await this.repository.revokeGrant({ grantId })+ return+ }++ const grant = await this.repository.findGrantByRefreshHash(hash)+ if (grant) await this.repository.revokeGrant({ grantId: grant.id })+ }++ private async issueTokenPair(args: IssueTokenPairArgs): Promise<OAuthResult<OAuthTokenResponse>> {+ // Copied straight from the grant: these are the RBAC keys the user+ // ticked. An empty list means "do not narrow anything", the same thing+ // it means for a manually issued tvk_ token.+ const allowedPermissions = args.grant.allowedPermissions+ const accessToken = OAUTH_ACCESS_TOKEN_PREFIX + randomToken()+ const refreshToken = randomToken()+ const now = Date.now()++ const rotated = await this.repository.rotateRefreshToken({+ grantId: args.grant.id,+ refreshTokenHash: sha256Hex(refreshToken),+ prevHash: args.prevRefreshHash ?? null,+ refreshExpiresAt: new Date(now + OAUTH_REFRESH_TOKEN_TTL_SECONDS * 1000),+ })+ if (!rotated) {+ return { ok: false, error: 'invalid_grant', description: 'This authorization has been revoked' }+ }++ const created = await this.repository.createAccessToken({+ userId: args.grant.userId,+ name: args.clientName.slice(0, 100),+ tokenHash: sha256Hex(accessToken),+ allowedPermissions,+ allowedGoalIds: args.grant.allowedGoalIds,+ grantId: args.grant.id,+ expiresAt: new Date(now + OAUTH_ACCESS_TOKEN_TTL_SECONDS * 1000),+ })+ if (!created) {+ return { ok: false, error: 'server_error', description: 'Could not issue the access token' }+ }++ return {+ ok: true,+ value: {+ access_token: accessToken,+ token_type: 'Bearer',+ expires_in: OAUTH_ACCESS_TOKEN_TTL_SECONDS,+ refresh_token: refreshToken,+ },+ }+ }+}diff --git a/api/src/tv-modules/oauth/OAuthRepository.ts b/api/src/tv-modules/oauth/OAuthRepository.tsnew file mode 100644index 0000000..6d6d273--- /dev/null+++ b/api/src/tv-modules/oauth/OAuthRepository.ts@@ -0,0 +1,189 @@+import { and, eq, isNull, lt, or } from 'drizzle-orm'+import {+ ApiTokensSchema,+ OAuthAuthCodesSchema,+ OAuthClientsSchema,+ OAuthGrantsSchema,+ type OAuthAuthCodesSchemaTypeForSelect,+ type OAuthClientsSchemaTypeForSelect,+ type OAuthGrantsSchemaTypeForInsert,+ type OAuthGrantsSchemaTypeForSelect,+} from 'taskview-db-schemas'+import { Database } from '../../modules/db'+import { callWithCatch } from '../../utils/helpers'+import type {+ ConsumeAuthCodeArgs,+ CreateAccessTokenArgs,+ CreateAuthCodeArgs,+ CreateOAuthClientArgs,+ RevokeGrantArgs,+ RotateRefreshTokenArgs,+} from './types'++export class OAuthRepository {+ private readonly db: Database++ constructor() {+ this.db = Database.getInstance()+ }++ async createClient(data: CreateOAuthClientArgs): Promise<OAuthClientsSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.insert(OAuthClientsSchema).values(data).returning(),+ )+ return result?.[0] ?? null+ }++ async findClientByClientId(clientId: string): Promise<OAuthClientsSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(OAuthClientsSchema).where(eq(OAuthClientsSchema.clientId, clientId)),+ )+ return result?.[0] ?? null+ }++ async createAuthCode(data: CreateAuthCodeArgs & { codeHash: string; expiresAt: Date }): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.insert(OAuthAuthCodesSchema).values({+ codeHash: data.codeHash,+ clientId: data.clientId,+ userId: data.userId,+ redirectUri: data.redirectUri,+ codeChallenge: data.codeChallenge,+ codeChallengeMethod: data.codeChallengeMethod,+ allowedPermissions: data.allowedPermissions,+ allowedGoalIds: data.allowedGoalIds,+ resource: data.resource,+ expiresAt: data.expiresAt,+ }).returning(),+ )+ return !!result?.length+ }++ async findAuthCodeByHash(codeHash: string): Promise<OAuthAuthCodesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(OAuthAuthCodesSchema).where(eq(OAuthAuthCodesSchema.codeHash, codeHash)),+ )+ return result?.[0] ?? null+ }++ /**+ * Single-use redemption. The UPDATE only matches while used_at is still NULL,+ * so two concurrent exchanges of the same code cannot both win.+ */+ async consumeAuthCode(args: ConsumeAuthCodeArgs): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.update(OAuthAuthCodesSchema)+ .set({ usedAt: new Date(), grantId: args.grantId })+ .where(and(eq(OAuthAuthCodesSchema.id, args.id), isNull(OAuthAuthCodesSchema.usedAt))),+ )+ return !!result?.rowCount+ }++ async deleteExpiredAuthCodes(): Promise<void> {+ await callWithCatch(() =>+ this.db.dbDrizzle.delete(OAuthAuthCodesSchema).where(lt(OAuthAuthCodesSchema.expiresAt, new Date())),+ )+ }++ async createGrant(data: OAuthGrantsSchemaTypeForInsert): Promise<OAuthGrantsSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.insert(OAuthGrantsSchema).values(data).returning(),+ )+ 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(() =>+ this.db.dbDrizzle.select().from(OAuthGrantsSchema).where(+ or(+ eq(OAuthGrantsSchema.refreshTokenHash, refreshTokenHash),+ eq(OAuthGrantsSchema.refreshTokenPrevHash, refreshTokenHash),+ ),+ ),+ )+ return result?.[0] ?? null+ }++ async rotateRefreshToken(args: RotateRefreshTokenArgs): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.update(OAuthGrantsSchema)+ .set({+ refreshTokenHash: args.refreshTokenHash,+ refreshTokenPrevHash: args.prevHash,+ refreshExpiresAt: args.refreshExpiresAt,+ lastUsedAt: new Date(),+ })+ .where(and(eq(OAuthGrantsSchema.id, args.grantId), isNull(OAuthGrantsSchema.revokedAt))),+ )+ return !!result?.rowCount+ }++ async fetchGrantsByUserId(userId: number): Promise<OAuthGrantsSchemaTypeForSelect[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(OAuthGrantsSchema).where(+ and(eq(OAuthGrantsSchema.userId, userId), isNull(OAuthGrantsSchema.revokedAt)),+ ),+ )+ return result ?? []+ }++ async fetchClientsByClientIds(clientIds: string[]): Promise<OAuthClientsSchemaTypeForSelect[]> {+ if (!clientIds.length) return []+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(OAuthClientsSchema),+ )+ return (result ?? []).filter((client) => clientIds.includes(client.clientId))+ }++ /**+ * Revoking a grant also deletes its live access tokens — that is the whole+ * point of storing them as opaque rows instead of self-contained JWTs.+ */+ async revokeGrant(args: RevokeGrantArgs): Promise<boolean> {+ const where = args.userId === undefined+ ? eq(OAuthGrantsSchema.id, args.grantId)+ : and(eq(OAuthGrantsSchema.id, args.grantId), eq(OAuthGrantsSchema.userId, args.userId))++ const result = await callWithCatch(() =>+ this.db.dbDrizzle.update(OAuthGrantsSchema)+ .set({ revokedAt: new Date(), refreshTokenHash: null, refreshTokenPrevHash: null })+ .where(where),+ )+ if (!result?.rowCount) return false++ await callWithCatch(() =>+ this.db.dbDrizzle.delete(ApiTokensSchema).where(eq(ApiTokensSchema.grantId, args.grantId)),+ )+ return true+ }++ async createAccessToken(data: CreateAccessTokenArgs): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.insert(ApiTokensSchema).values(data).returning(),+ )+ 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 })+ .from(ApiTokensSchema)+ .where(eq(ApiTokensSchema.tokenHash, tokenHash)),+ )+ return result?.[0]?.grantId ?? null+ }+}diff --git a/api/src/tv-modules/oauth/OAuthRoutes.ts b/api/src/tv-modules/oauth/OAuthRoutes.tsnew file mode 100644index 0000000..a4e459d--- /dev/null+++ b/api/src/tv-modules/oauth/OAuthRoutes.ts@@ -0,0 +1,35 @@+import { Router } from 'express'+import type { Routable } from '../../types/routable.type'+import { IsLoggedIn } from '../auth/middlewares/is-logged-in'+import { RejectApiTokenAuth } from '../api-tokens/middlewares/RejectApiTokenAuth'+import { OAuthController } from './OAuthController'++export default class OAuthRoutes implements Routable {+ private readonly router: ReturnType<typeof Router>+ private readonly controller: OAuthController++ constructor() {+ this.router = Router()+ this.controller = new OAuthController()+ this.initRoutes()+ }++ getRouter() {+ return this.router+ }++ initRoutes() {+ this.router.get('/authorize', this.controller.authorize)+ this.router.post('/token', this.controller.token)+ this.router.post('/revoke', this.controller.revoke)+ this.router.post('/register', this.controller.register)++ // Consent is the one place a real human decides. It must be a browser+ // session, never an API token acting on the user's behalf.+ this.router.post('/consent', [IsLoggedIn, RejectApiTokenAuth], this.controller.consent)+ this.router.post('/consent/deny', [IsLoggedIn, RejectApiTokenAuth], this.controller.denyConsent)++ this.router.get('/connected-apps', [IsLoggedIn, RejectApiTokenAuth], this.controller.fetchConnectedApps)+ this.router.delete('/connected-apps', [IsLoggedIn, RejectApiTokenAuth], this.controller.revokeConnectedApp)+ }+}diff --git a/api/src/tv-modules/oauth/OAuthWellKnownRoutes.ts b/api/src/tv-modules/oauth/OAuthWellKnownRoutes.tsnew file mode 100644index 0000000..d5bb69c--- /dev/null+++ b/api/src/tv-modules/oauth/OAuthWellKnownRoutes.ts@@ -0,0 +1,27 @@+import { Router } from 'express'+import type { Routable } from '../../types/routable.type'+import { OAuthController } from './OAuthController'++/**+ * RFC 8414 / RFC 9728 discovery. These must sit at the origin root, not under+ * /module, because that is where clients look before they have any credentials.+ */+export default class OAuthWellKnownRoutes implements Routable {+ private readonly router: ReturnType<typeof Router>+ private readonly controller: OAuthController++ constructor() {+ this.router = Router()+ this.controller = new OAuthController()+ this.initRoutes()+ }++ getRouter() {+ return this.router+ }++ initRoutes() {+ this.router.get('/oauth-authorization-server', this.controller.authorizationServerMetadata)+ this.router.get('/oauth-protected-resource', this.controller.protectedResourceMetadata)+ }+}diff --git a/api/src/tv-modules/oauth/__tests__/OAuth.integration.spec.ts b/api/src/tv-modules/oauth/__tests__/OAuth.integration.spec.tsnew file mode 100644index 0000000..eac5029--- /dev/null+++ b/api/src/tv-modules/oauth/__tests__/OAuth.integration.spec.ts@@ -0,0 +1,580 @@+import axios from 'axios';+import { createHash, randomBytes } from 'crypto';+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';++const port = 1810;+const url = `http://localhost:${port}`;+const MIGRATION_DIR = join(__dirname, '../../../migrations/taskview/sql/1.64.0');++const LOGIN = '[email protected]';+const PASSWORD = 'user1!#Q';++const REDIRECT_URI = 'https://client.integration.test/callback';++let server: http.Server;+let jwt = '';+let goalId = 0;++const verifier = () => randomBytes(40).toString('base64url');+const challengeFor = (value: string) => createHash('sha256').update(value).digest('base64url');+const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');++const api = axios.create({ baseURL: url, validateStatus: () => true });++async function registerClient(overrides: Record<string, unknown> = {}) {+ const response = await api.post('/module/oauth/register', {+ client_name: 'Integration Client',+ redirect_uris: [REDIRECT_URI],+ ...overrides,+ });+ return response;+}++/** Runs the browser half of the flow with the user's own session, returns the code. */+async function authorizeAndConsent(args: {+ clientId: string;+ codeChallenge: string;+ allowedPermissions?: string[];+ resource?: string;+ allowedGoalIds?: number[];+}) {+ const response = await api.post(+ '/module/oauth/consent',+ {+ client_id: args.clientId,+ redirect_uri: REDIRECT_URI,+ code_challenge: args.codeChallenge,+ code_challenge_method: 'S256',+ allowedPermissions: args.allowedPermissions ?? [],+ allowedGoalIds: args.allowedGoalIds ?? [],+ resource: args.resource,+ },+ { headers: { Authorization: `Bearer ${jwt}` } },+ );+ expect(response.status).toBe(200);+ return new URL(response.data.response.redirectUrl).searchParams.get('code') as string;+}++async function exchange(args: { clientId: string; code: string; codeVerifier: string; resource?: string }) {+ return api.post('/module/oauth/token', {+ grant_type: 'authorization_code',+ client_id: args.clientId,+ code: args.code,+ code_verifier: args.codeVerifier,+ redirect_uri: REDIRECT_URI,+ resource: args.resource,+ });+}++/** Full happy path, returns the issued token pair. */+async function connect(allowedPermissions: string[] = []) {+ const registered = await registerClient();+ const clientId = registered.data.client_id as string;+ const codeVerifier = verifier();+ const code = await authorizeAndConsent({ clientId, codeChallenge: challengeFor(codeVerifier), allowedPermissions });+ const tokens = await exchange({ clientId, code, codeVerifier });+ expect(tokens.status).toBe(200);+ return { clientId, ...tokens.data as { access_token: string; refresh_token: string; scope: string } };+}++describe('OAuth 2.1 authorization server', () => {+ vi.mock('emailjs', () => ({+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),+ }));++ beforeAll(async () => {+ const db = Database.getInstance();+ const client = await db.getClient();++ // Apply migration 1.64.0 for real. The scripts are idempotent, and the+ // app's own runner is not usable here: it replays from the recorded+ // version and swallows SQL errors, so it would hide a broken script.+ 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;++ const goal = await api.post(+ '/module/goals',+ { name: `oauth-it-${Date.now()}` },+ { headers: { Authorization: `Bearer ${jwt}` } },+ );+ expect(goal.status).toBe(200);+ goalId = goal.data.response.id ?? goal.data.response.goal?.id;+ });++ afterAll(async () => {+ // HTTP cleanup has to happen while the server is still listening.+ if (goalId) {+ await api.delete('/module/goals', {+ headers: { Authorization: `Bearer ${jwt}` },+ data: { goalId },+ });+ }+ server?.close();++ // Clients cascade to their grants, and grants cascade to the access+ // tokens in api_tokens, so this one delete clears everything the run made.+ const db = Database.getInstance();+ await db.query("DELETE FROM tv_auth.oauth_clients WHERE name = 'Integration Client'");+ });++ describe('migration 1.64.0', () => {+ it('creates every OAuth table it declares', async () => {+ const db = Database.getInstance();+ const result = await db.query<{ table_name: string }>(+ `SELECT table_name FROM information_schema.tables+ WHERE table_schema = 'tv_auth' AND table_name LIKE 'oauth%' ORDER BY 1`,+ );+ expect(result?.rows.map((row) => row.table_name)).toEqual([+ 'oauth_auth_codes', 'oauth_clients', 'oauth_grants',+ ]);+ });++ it('names the grant column allowed_permissions, matching api_tokens', async () => {+ const db = Database.getInstance();+ const result = await db.query<{ column_name: string }>(+ `SELECT column_name FROM information_schema.columns+ WHERE table_schema = 'tv_auth' AND table_name IN ('oauth_grants', 'oauth_auth_codes')+ AND column_name = 'allowed_permissions'`,+ );+ expect(result?.rows.length).toBe(2);+ });++ it('adds grant_id to api_tokens', async () => {+ const db = Database.getInstance();+ const result = await db.query(+ `SELECT column_name FROM information_schema.columns+ WHERE table_schema = 'tv_auth' AND table_name = 'api_tokens' AND column_name = 'grant_id'`,+ );+ expect(result?.rows.length).toBe(1);+ });+ });++ describe('discovery', () => {+ it('publishes authorization server metadata', async () => {+ const response = await api.get('/.well-known/oauth-authorization-server');++ expect(response.status).toBe(200);+ expect(response.data.code_challenge_methods_supported).toEqual(['S256']);+ expect(response.data.grant_types_supported).toContain('refresh_token');+ expect(response.data.authorization_endpoint).toContain('/module/oauth/authorize');+ expect(response.data.registration_endpoint).toContain('/module/oauth/register');+ });++ it('publishes protected resource metadata', async () => {+ const response = await api.get('/.well-known/oauth-protected-resource');++ expect(response.status).toBe(200);+ expect(response.data.authorization_servers.length).toBe(1);+ expect(response.data.bearer_methods_supported).toEqual(['header']);+ expect(response.data.resource).toBeTruthy();+ });+ });++ describe('dynamic client registration', () => {+ it('registers a public client without a secret', async () => {+ const response = await registerClient();++ expect(response.status).toBe(201);+ expect(response.data.client_id).toBeTruthy();+ expect(response.data.client_secret).toBeUndefined();+ expect(response.data.token_endpoint_auth_method).toBe('none');+ });++ it('refuses a non-https redirect_uri', async () => {+ const response = await registerClient({ redirect_uris: ['http://evil.example.com/cb'] });++ expect(response.status).toBe(400);+ expect(response.data.error).toBe('invalid_redirect_uri');+ });++ it('refuses a redirect_uri carrying a fragment', async () => {+ const response = await registerClient({ redirect_uris: ['https://client.test/cb#x'] });++ 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();+ const codeVerifier = verifier();++ const response = await api.get('/module/oauth/authorize', {+ params: {+ response_type: 'code',+ client_id: registered.data.client_id,+ redirect_uri: REDIRECT_URI,+ code_challenge: challengeFor(codeVerifier),+ code_challenge_method: 'S256',+ scope: 'tasks.read',+ state: 'xyz',+ },+ maxRedirects: 0,+ });++ expect(response.status).toBe(302);+ const location = new URL(response.headers.location);+ expect(location.pathname).toBe('/oauth/consent');+ expect(location.searchParams.get('state')).toBe('xyz');+ expect(location.searchParams.get('client_id')).toBe(registered.data.client_id);+ });++ it('refuses an unknown client without redirecting anywhere', async () => {+ const codeVerifier = verifier();+ const response = await api.get('/module/oauth/authorize', {+ params: {+ response_type: 'code',+ client_id: 'does-not-exist',+ redirect_uri: REDIRECT_URI,+ code_challenge: challengeFor(codeVerifier),+ code_challenge_method: 'S256',+ },+ maxRedirects: 0,+ });++ expect(response.status).toBe(400);+ expect(response.headers.location).toBeUndefined();+ });++ it('refuses an unregistered redirect_uri without redirecting to it', async () => {+ const registered = await registerClient();+ const codeVerifier = verifier();++ const response = await api.get('/module/oauth/authorize', {+ params: {+ response_type: 'code',+ client_id: registered.data.client_id,+ redirect_uri: 'https://attacker.example.com/steal',+ code_challenge: challengeFor(codeVerifier),+ code_challenge_method: 'S256',+ },+ maxRedirects: 0,+ });++ expect(response.status).toBe(400);+ expect(response.headers.location).toBeUndefined();+ });++ it('refuses a plain code_challenge_method', 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: 'anything',+ code_challenge_method: 'plain',+ },+ maxRedirects: 0,+ });++ expect(response.status).toBe(400);+ });+ });++ describe('/consent', () => {+ it('requires a browser session', async () => {+ const registered = await registerClient();+ const response = await api.post('/module/oauth/consent', {+ client_id: registered.data.client_id,+ redirect_uri: REDIRECT_URI,+ code_challenge: challengeFor(verifier()),+ code_challenge_method: 'S256',+ });++ expect(response.status).toBe(401);+ });++ it('returns a redirect carrying access_denied when the user declines', async () => {+ const registered = await registerClient();+ const response = await api.post(+ '/module/oauth/consent/deny',+ {+ client_id: registered.data.client_id,+ redirect_uri: REDIRECT_URI,+ code_challenge: challengeFor(verifier()),+ code_challenge_method: 'S256',+ state: 'abc',+ },+ { headers: { Authorization: `Bearer ${jwt}` } },+ );++ expect(response.status).toBe(200);+ const redirect = new URL(response.data.response.redirectUrl);+ expect(redirect.searchParams.get('error')).toBe('access_denied');+ expect(redirect.searchParams.get('state')).toBe('abc');+ expect(redirect.searchParams.get('code')).toBeNull();+ });+ });++ describe('full authorization flow', () => {+ it('issues a tvo_ token that authenticates a real API call', async () => {+ const { access_token } = await connect();++ expect(access_token.startsWith('tvo_')).toBe(true);++ const goals = await api.get('/module/goals', {+ headers: { Authorization: `Bearer ${access_token}` },+ });++ expect(goals.status).toBe(200);+ });++ it('stores exactly the permissions the user ticked', async () => {+ const picked = ['goal_can_watch_content', 'task_can_edit_status'];+ const { access_token } = await connect(picked);++ const db = Database.getInstance();+ const result = await db.query<{ allowed_permissions: string[] }>(+ 'SELECT allowed_permissions FROM tv_auth.api_tokens WHERE token_hash = $1',+ [sha256(access_token)],+ );++ expect(result?.rows[0].allowed_permissions).toEqual(picked);+ });++ it('leaves the token unrestricted when the user ticks nothing', async () => {+ const { access_token } = await connect([]);++ const db = Database.getInstance();+ const result = await db.query<{ allowed_permissions: string[] }>(+ 'SELECT allowed_permissions FROM tv_auth.api_tokens WHERE token_hash = $1',+ [sha256(access_token)],+ );++ // Empty means "do not narrow", the same thing it means for a tvk_ token.+ expect(result?.rows[0].allowed_permissions).toEqual([]);+ });++ it('reports the granted permissions back through the connected-apps list', async () => {+ const picked = ['timetracking_can_view'];+ await connect(picked);++ const apps = await api.get('/module/oauth/connected-apps', {+ headers: { Authorization: `Bearer ${jwt}` },+ });++ expect(apps.status).toBe(200);+ const latest = apps.data.response.at(-1);+ expect(latest.allowedPermissions).toEqual(picked);+ });++ it('carries the ticked permissions through a refresh', async () => {+ const picked = ['goal_can_watch_content'];+ const { clientId, refresh_token } = await connect(picked);++ const refreshed = await api.post('/module/oauth/token', {+ grant_type: 'refresh_token',+ client_id: clientId,+ refresh_token,+ });+ expect(refreshed.status).toBe(200);++ const db = Database.getInstance();+ const result = await db.query<{ allowed_permissions: string[] }>(+ 'SELECT allowed_permissions FROM tv_auth.api_tokens WHERE token_hash = $1',+ [sha256(refreshed.data.access_token)],+ );++ expect(result?.rows[0].allowed_permissions).toEqual(picked);+ });++ it('refuses to let an OAuth token reach an endpoint closed to token auth', async () => {+ const { access_token } = await connect();++ const response = await api.get('/module/api-tokens', {+ headers: { Authorization: `Bearer ${access_token}` },+ });++ expect(response.status).toBe(403);+ });++ it('denies a narrowly scoped token an operation outside its permissions', async () => {+ const { access_token } = await connect(['timetracking_can_view']);++ const response = await api.patch(+ '/module/goals',+ { id: goalId, name: 'renamed by a read-only token' },+ { headers: { Authorization: `Bearer ${access_token}` } },+ );++ expect(response.status).toBeGreaterThanOrEqual(400);+ });+ });++ describe('authorization code hardening', () => {+ it('refuses a wrong code_verifier', async () => {+ const registered = await registerClient();+ const clientId = registered.data.client_id;+ const code = await authorizeAndConsent({+ clientId,+ codeChallenge: challengeFor(verifier()),+ });++ const response = await exchange({ clientId, code, codeVerifier: verifier() });++ expect(response.status).toBe(400);+ expect(response.data.error).toBe('invalid_grant');+ });++ it('accepts a code once and revokes the grant when it is replayed', async () => {+ const registered = await registerClient();+ const clientId = registered.data.client_id;+ const codeVerifier = verifier();+ const code = await authorizeAndConsent({+ clientId,+ codeChallenge: challengeFor(codeVerifier),+ });++ const first = await exchange({ clientId, code, codeVerifier });+ expect(first.status).toBe(200);++ const replay = await exchange({ clientId, code, codeVerifier });+ expect(replay.status).toBe(400);+ expect(replay.data.error).toBe('invalid_grant');++ // The replay must also kill the token the first exchange produced.+ const afterReplay = await api.get('/module/goals', {+ headers: { Authorization: `Bearer ${first.data.access_token}` },+ });+ expect(afterReplay.status).toBe(401);+ });++ it('lets exactly one of two concurrent exchanges win', async () => {+ const registered = await registerClient();+ const clientId = registered.data.client_id;+ const codeVerifier = verifier();+ const code = await authorizeAndConsent({+ clientId,+ codeChallenge: challengeFor(codeVerifier),+ });++ const [a, b] = await Promise.all([+ exchange({ clientId, code, codeVerifier }),+ exchange({ clientId, code, codeVerifier }),+ ]);++ const statuses = [a.status, b.status].sort();+ expect(statuses).toEqual([200, 400]);+ });++ it('refuses a code presented with a mismatched resource', 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 response = await exchange({+ clientId,+ code,+ codeVerifier,+ resource: 'https://other.integration.test',+ });++ expect(response.status).toBe(400);+ expect(response.data.error).toBe('invalid_target');+ });+ });++ describe('refresh token rotation', () => {+ it('rotates the refresh token and keeps the new access token working', async () => {+ const { clientId, refresh_token } = await connect();++ const refreshed = await api.post('/module/oauth/token', {+ grant_type: 'refresh_token',+ client_id: clientId,+ refresh_token,+ });++ expect(refreshed.status).toBe(200);+ expect(refreshed.data.refresh_token).not.toBe(refresh_token);++ const goals = await api.get('/module/goals', {+ headers: { Authorization: `Bearer ${refreshed.data.access_token}` },+ });+ expect(goals.status).toBe(200);+ });++ it('revokes the whole grant when a superseded refresh token is replayed', async () => {+ const { clientId, refresh_token } = await connect();++ const refreshed = await api.post('/module/oauth/token', {+ grant_type: 'refresh_token',+ client_id: clientId,+ refresh_token,+ });+ expect(refreshed.status).toBe(200);++ const replay = await api.post('/module/oauth/token', {+ grant_type: 'refresh_token',+ client_id: clientId,+ refresh_token,+ });+ expect(replay.status).toBe(400);++ // Replay burns the grant, so the freshly rotated access token dies too.+ const goals = await api.get('/module/goals', {+ headers: { Authorization: `Bearer ${refreshed.data.access_token}` },+ });+ expect(goals.status).toBe(401);+ });+ });++ describe('revocation', () => {+ it('kills the access token immediately when the user disconnects the app', 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();+ 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;++ const apps = await api.get('/module/oauth/connected-apps', {+ headers: { Authorization: `Bearer ${jwt}` },+ });+ expect(apps.status).toBe(200);+ expect(apps.data.response.some((app: { grantId: number }) => app.grantId === grantId)).toBe(true);++ const revoked = await api.delete('/module/oauth/connected-apps', {+ headers: { Authorization: `Bearer ${jwt}` },+ data: { grantId },+ });+ expect(revoked.status).toBe(200);++ const after = await api.get('/module/goals', {+ headers: { Authorization: `Bearer ${access_token}` },+ });+ expect(after.status).toBe(401);+ });++ it('answers 200 to RFC 7009 revocation of an unknown token', async () => {+ const response = await api.post('/module/oauth/revoke', { token: 'tvo_nope' });++ expect(response.status).toBe(200);+ });+ });+});diff --git a/api/src/tv-modules/oauth/__tests__/OAuthManager.test.ts b/api/src/tv-modules/oauth/__tests__/OAuthManager.test.tsnew file mode 100644index 0000000..456911c--- /dev/null+++ b/api/src/tv-modules/oauth/__tests__/OAuthManager.test.ts@@ -0,0 +1,328 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { createHash, randomBytes } from 'crypto'++const repositoryMock = {+ findClientByClientId: vi.fn(),+ findAuthCodeByHash: vi.fn(),+ consumeAuthCode: vi.fn(),+ createGrant: vi.fn(),+ createAccessToken: vi.fn(),+ rotateRefreshToken: vi.fn(),+ revokeGrant: vi.fn(),+ findGrantByRefreshHash: vi.fn(),+ findGrantIdByAccessTokenHash: vi.fn(),+ createAuthCode: vi.fn(),+ deleteExpiredAuthCodes: vi.fn(),+}++vi.mock('../OAuthRepository', () => ({+ OAuthRepository: vi.fn(() => repositoryMock),+}))++const { OAuthManager } = await import('../OAuthManager')++const sha256 = (value: string) => createHash('sha256').update(value).digest('hex')+const VERIFIER = randomBytes(40).toString('base64url')+const CHALLENGE = createHash('sha256').update(VERIFIER).digest('base64url')++const validCode = (overrides: Record<string, unknown> = {}) => ({+ id: 1,+ codeHash: sha256('the-code'),+ clientId: 'client-a',+ userId: 7,+ redirectUri: 'https://app.example.com/cb',+ codeChallenge: CHALLENGE,+ codeChallengeMethod: 'S256',+ allowedPermissions: ['goal_can_watch_content'],+ allowedGoalIds: [],+ resource: null,+ expiresAt: new Date(Date.now() + 60_000),+ usedAt: null,+ grantId: null,+ createdAt: new Date(),+ ...overrides,+})++const validGrant = (overrides: Record<string, unknown> = {}) => ({+ id: 42,+ userId: 7,+ clientId: 'client-a',+ allowedPermissions: ['goal_can_watch_content'],+ allowedGoalIds: [],+ resource: null,+ refreshTokenHash: sha256('current-refresh'),+ refreshTokenPrevHash: null,+ refreshExpiresAt: new Date(Date.now() + 86_400_000),+ lastUsedAt: null,+ revokedAt: null,+ createdAt: new Date(),+ ...overrides,+})++const exchangeArgs = (overrides: Record<string, unknown> = {}) => ({+ code: 'the-code',+ codeVerifier: VERIFIER,+ clientId: 'client-a',+ redirectUri: 'https://app.example.com/cb',+ resource: null,+ ...overrides,+})++describe('OAuthManager.exchangeCode', () => {+ let manager: InstanceType<typeof OAuthManager>++ beforeEach(() => {+ vi.clearAllMocks()+ manager = new OAuthManager()+ repositoryMock.findClientByClientId.mockResolvedValue({ clientId: 'client-a', name: 'Client A' })+ repositoryMock.createGrant.mockResolvedValue(validGrant())+ repositoryMock.consumeAuthCode.mockResolvedValue(true)+ repositoryMock.rotateRefreshToken.mockResolvedValue(true)+ repositoryMock.createAccessToken.mockResolvedValue(true)+ repositoryMock.revokeGrant.mockResolvedValue(true)+ })++ it('issues a tvo_ access token and a refresh token on a valid exchange', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())++ const result = await manager.exchangeCode(exchangeArgs())++ expect(result.ok).toBe(true)+ if (!result.ok) return+ expect(result.value.access_token.startsWith('tvo_')).toBe(true)+ expect(result.value.refresh_token).toBeTruthy()+ expect(result.value.token_type).toBe('Bearer')+ })++ it('stores only the hash of the access token, never the token itself', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())++ const result = await manager.exchangeCode(exchangeArgs())++ expect(result.ok).toBe(true)+ if (!result.ok) return+ const stored = repositoryMock.createAccessToken.mock.calls[0][0]+ expect(stored.tokenHash).toBe(sha256(result.value.access_token))+ expect(JSON.stringify(stored)).not.toContain(result.value.access_token)+ })++ it('rejects a wrong code_verifier', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())++ const result = await manager.exchangeCode(exchangeArgs({ codeVerifier: randomBytes(40).toString('base64url') }))++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ expect(repositoryMock.createGrant).not.toHaveBeenCalled()+ })++ it('rejects a redirect_uri that differs from the authorization request', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())++ const result = await manager.exchangeCode(exchangeArgs({ redirectUri: 'https://app.example.com/other' }))++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ })++ it('rejects a code presented by a different client', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())++ const result = await manager.exchangeCode(exchangeArgs({ clientId: 'client-b' }))++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ })++ it('rejects an expired code', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode({ expiresAt: new Date(Date.now() - 1000) }))++ const result = await manager.exchangeCode(exchangeArgs())++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ })++ it('revokes the original grant when a used code is replayed', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode({ usedAt: new Date(), grantId: 42 }))++ const result = await manager.exchangeCode(exchangeArgs())++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ expect(repositoryMock.revokeGrant).toHaveBeenCalledWith({ grantId: 42 })+ })++ it('rolls back the grant when the code was consumed by a concurrent request', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode())+ repositoryMock.consumeAuthCode.mockResolvedValue(false)++ const result = await manager.exchangeCode(exchangeArgs())++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ expect(repositoryMock.revokeGrant).toHaveBeenCalledWith({ grantId: 42 })+ })++ it('rejects a resource that does not match the authorization request', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(validCode({ resource: 'https://mcp.example.com' }))++ const result = await manager.exchangeCode(exchangeArgs({ resource: 'https://other.example.com' }))++ expect(result).toMatchObject({ ok: false, error: 'invalid_target' })+ })++ it('rejects an unknown code', async () => {+ repositoryMock.findAuthCodeByHash.mockResolvedValue(null)++ const result = await manager.exchangeCode(exchangeArgs())++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ })+})++describe('OAuthManager.refreshTokens', () => {+ let manager: InstanceType<typeof OAuthManager>++ beforeEach(() => {+ vi.clearAllMocks()+ manager = new OAuthManager()+ repositoryMock.findClientByClientId.mockResolvedValue({ clientId: 'client-a', name: 'Client A' })+ repositoryMock.rotateRefreshToken.mockResolvedValue(true)+ repositoryMock.createAccessToken.mockResolvedValue(true)+ repositoryMock.revokeGrant.mockResolvedValue(true)+ })++ it('rotates the refresh token and keeps the presented one as the previous hash', async () => {+ repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant())++ const result = await manager.refreshTokens({+ refreshToken: 'current-refresh',+ clientId: 'client-a',+ resource: null,+ })++ expect(result.ok).toBe(true)+ if (!result.ok) return+ expect(result.value.refresh_token).not.toBe('current-refresh')++ const rotation = repositoryMock.rotateRefreshToken.mock.calls[0][0]+ expect(rotation.prevHash).toBe(sha256('current-refresh'))+ expect(rotation.refreshTokenHash).toBe(sha256(result.value.refresh_token))+ })++ it('revokes the whole grant when a superseded refresh token is replayed', async () => {+ repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({+ refreshTokenHash: sha256('rotated-refresh'),+ refreshTokenPrevHash: sha256('leaked-refresh'),+ }))++ const result = await manager.refreshTokens({+ refreshToken: 'leaked-refresh',+ clientId: 'client-a',+ resource: null,+ })++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ expect(repositoryMock.revokeGrant).toHaveBeenCalledWith({ grantId: 42 })+ })++ it('refuses a revoked grant', async () => {+ repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({ revokedAt: new Date() }))++ const result = await manager.refreshTokens({+ refreshToken: 'current-refresh',+ clientId: 'client-a',+ resource: null,+ })++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ })++ it('refuses an expired refresh token', async () => {+ repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({+ refreshExpiresAt: new Date(Date.now() - 1000),+ }))++ const result = await manager.refreshTokens({+ refreshToken: 'current-refresh',+ clientId: 'client-a',+ resource: null,+ })++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ })++ it('refuses a refresh token presented by another client', async () => {+ repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant())++ const result = await manager.refreshTokens({+ refreshToken: 'current-refresh',+ clientId: 'client-b',+ resource: null,+ })++ expect(result).toMatchObject({ ok: false, error: 'invalid_grant' })+ })++ it('carries the consented permission keys onto the reissued token', async () => {+ repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({+ allowedPermissions: ['timetracking_can_view', 'task_can_edit_status'],+ }))++ await manager.refreshTokens({ refreshToken: 'current-refresh', clientId: 'client-a', resource: null })++ const stored = repositoryMock.createAccessToken.mock.calls[0][0]+ expect(stored.allowedPermissions).toEqual(['timetracking_can_view', 'task_can_edit_status'])+ })++ it('keeps an unrestricted grant unrestricted, which is what "all permissions" means', async () => {+ repositoryMock.findGrantByRefreshHash.mockResolvedValue(validGrant({ allowedPermissions: [] }))++ await manager.refreshTokens({ refreshToken: 'current-refresh', clientId: 'client-a', resource: null })++ const stored = repositoryMock.createAccessToken.mock.calls[0][0]+ expect(stored.allowedPermissions).toEqual([])+ })+})++describe('OAuthManager.authenticateClient', () => {+ let manager: InstanceType<typeof OAuthManager>++ beforeEach(() => {+ vi.clearAllMocks()+ manager = new OAuthManager()+ })++ it('accepts a public client with no secret', async () => {+ repositoryMock.findClientByClientId.mockResolvedValue({ clientId: 'pub', clientSecretHash: null })++ const result = await manager.authenticateClient({ clientId: 'pub' })++ expect(result.ok).toBe(true)+ })++ it('rejects a confidential client presenting the wrong secret', async () => {+ repositoryMock.findClientByClientId.mockResolvedValue({+ clientId: 'conf',+ clientSecretHash: sha256('right'),+ })++ const result = await manager.authenticateClient({ clientId: 'conf', clientSecret: 'wrong' })++ expect(result).toMatchObject({ ok: false, error: 'invalid_client' })+ })++ it('rejects a confidential client presenting no secret at all', async () => {+ repositoryMock.findClientByClientId.mockResolvedValue({+ clientId: 'conf',+ clientSecretHash: sha256('right'),+ })++ const result = await manager.authenticateClient({ clientId: 'conf' })++ expect(result).toMatchObject({ ok: false, error: 'invalid_client' })+ })++ it('rejects an unknown client', async () => {+ repositoryMock.findClientByClientId.mockResolvedValue(null)++ const result = await manager.authenticateClient({ clientId: 'nope' })++ expect(result).toMatchObject({ ok: false, error: 'invalid_client' })+ })+})diff --git a/api/src/tv-modules/oauth/__tests__/oauth.utils.test.ts b/api/src/tv-modules/oauth/__tests__/oauth.utils.test.tsnew file mode 100644index 0000000..21c4702--- /dev/null+++ b/api/src/tv-modules/oauth/__tests__/oauth.utils.test.ts@@ -0,0 +1,136 @@+import { describe, it, expect } from 'vitest'+import { createHash, randomBytes } from 'crypto'+import {+ buildRedirectUrl,+ isAcceptableRedirectUri,+ matchesRegisteredRedirectUri,+ resourceMatches,+ verifyPkce,+} from '../oauth.utils'++const challengeFor = (verifier: string) =>+ createHash('sha256').update(verifier).digest('base64url')++describe('verifyPkce', () => {+ const verifier = randomBytes(40).toString('base64url')++ it('accepts the verifier that produced the challenge', () => {+ expect(verifyPkce({ codeVerifier: verifier, codeChallenge: challengeFor(verifier) })).toBe(true)+ })++ it('rejects a different verifier', () => {+ const other = randomBytes(40).toString('base64url')+ expect(verifyPkce({ codeVerifier: other, codeChallenge: challengeFor(verifier) })).toBe(false)+ })++ it('rejects a verifier shorter than the RFC 7636 minimum', () => {+ const short = 'abc'+ expect(verifyPkce({ codeVerifier: short, codeChallenge: challengeFor(short) })).toBe(false)+ })++ it('rejects a verifier longer than the RFC 7636 maximum', () => {+ const long = 'a'.repeat(129)+ expect(verifyPkce({ codeVerifier: long, codeChallenge: challengeFor(long) })).toBe(false)+ })+})++describe('matchesRegisteredRedirectUri', () => {+ it('accepts an exact match', () => {+ expect(matchesRegisteredRedirectUri({+ candidate: 'https://chat.example.com/callback',+ registered: ['https://chat.example.com/callback'],+ })).toBe(true)+ })++ it('rejects a different path on the same host', () => {+ expect(matchesRegisteredRedirectUri({+ candidate: 'https://chat.example.com/evil',+ registered: ['https://chat.example.com/callback'],+ })).toBe(false)+ })++ it('rejects an attacker host that merely prefixes the registered one', () => {+ expect(matchesRegisteredRedirectUri({+ candidate: 'https://chat.example.com.evil.test/callback',+ registered: ['https://chat.example.com/callback'],+ })).toBe(false)+ })++ it('allows any loopback port for the same path (RFC 8252)', () => {+ expect(matchesRegisteredRedirectUri({+ candidate: 'http://127.0.0.1:55123/callback',+ registered: ['http://127.0.0.1:8080/callback'],+ })).toBe(true)+ })++ it('does not extend the loopback port carve-out to other hosts', () => {+ expect(matchesRegisteredRedirectUri({+ candidate: 'https://example.com:9999/callback',+ registered: ['https://example.com:443/callback'],+ })).toBe(false)+ })++ it('rejects a loopback candidate whose path differs', () => {+ expect(matchesRegisteredRedirectUri({+ candidate: 'http://127.0.0.1:55123/other',+ registered: ['http://127.0.0.1:8080/callback'],+ })).toBe(false)+ })++ it('rejects an unparseable candidate', () => {+ expect(matchesRegisteredRedirectUri({+ candidate: 'not a url',+ registered: ['https://chat.example.com/callback'],+ })).toBe(false)+ })+})++describe('isAcceptableRedirectUri', () => {+ it('accepts https', () => {+ expect(isAcceptableRedirectUri('https://example.com/cb')).toBe(true)+ })++ it('accepts loopback http', () => {+ expect(isAcceptableRedirectUri('http://127.0.0.1:1234/cb')).toBe(true)+ })++ it('rejects a URI carrying a fragment', () => {+ expect(isAcceptableRedirectUri('https://example.com/cb#token')).toBe(false)+ })++ it('rejects a non-http scheme', () => {+ expect(isAcceptableRedirectUri('javascript:alert(1)')).toBe(false)+ })+})++describe('buildRedirectUrl', () => {+ it('appends parameters and skips undefined ones', () => {+ const url = buildRedirectUrl({+ redirectUri: 'https://example.com/cb?existing=1',+ params: { code: 'abc', state: undefined },+ })+ expect(url).toBe('https://example.com/cb?existing=1&code=abc')+ })++ it('encodes parameter values', () => {+ const url = buildRedirectUrl({+ redirectUri: 'https://example.com/cb',+ params: { state: 'a b&c' },+ })+ expect(url).toContain('state=a+b%26c')+ })+})++describe('resourceMatches', () => {+ it('ignores a trailing slash', () => {+ expect(resourceMatches({ granted: 'https://mcp.example.com/', requested: 'https://mcp.example.com' })).toBe(true)+ })++ it('rejects a token replayed against another resource', () => {+ expect(resourceMatches({ granted: 'https://mcp.example.com', requested: 'https://other.example.com' })).toBe(false)+ })++ it('is permissive when the grant carries no audience', () => {+ expect(resourceMatches({ granted: null, requested: 'https://mcp.example.com' })).toBe(true)+ })+})diff --git a/api/src/tv-modules/oauth/oauth.utils.ts b/api/src/tv-modules/oauth/oauth.utils.tsnew file mode 100644index 0000000..01c4fc5--- /dev/null+++ b/api/src/tv-modules/oauth/oauth.utils.ts@@ -0,0 +1,105 @@+import { createHash, randomBytes, timingSafeEqual } from 'crypto'+import type {+ BuildRedirectUrlArgs,+ MatchRedirectUriArgs,+ ResourceMatchArgs,+ VerifyPkceArgs,+} from './types'++export function isDcrEnabled(): boolean {+ const raw = process.env.OAUTH_DYNAMIC_REGISTRATION+ if (raw === undefined || raw.trim() === '') return true+ return raw.trim().toLowerCase() === 'true'+}++export function sha256Hex(value: string): string {+ return createHash('sha256').update(value).digest('hex')+}++export function randomToken(): string {+ return randomBytes(32).toString('hex')+}++export function safeCompareHex(a: string, b: string): boolean {+ if (a.length !== b.length) return false+ return timingSafeEqual(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'))+}++export function verifyPkce(args: VerifyPkceArgs): boolean {+ if (args.codeVerifier.length < 43 || args.codeVerifier.length > 128) return false+ const digest = createHash('sha256').update(args.codeVerifier).digest('base64url')+ return safeCompareHex(digest, args.codeChallenge)+}++function isLoopbackUrl(url: URL): boolean {+ return url.hostname === '127.0.0.1'+ || url.hostname === '::1'+ || url.hostname === '[::1]'+ || url.hostname === 'localhost'+}++/**+ * Exact match, with one carve-out: RFC 8252 lets a native client bind an+ * arbitrary loopback port, so the port is ignored for 127.0.0.1 / ::1 only.+ * Everything else must match the registered string exactly — this is the guard+ * against turning /authorize into an open redirect.+ */+export function matchesRegisteredRedirectUri(args: MatchRedirectUriArgs): boolean {+ if (args.registered.includes(args.candidate)) return true++ let candidateUrl: URL+ try {+ candidateUrl = new URL(args.candidate)+ } catch {+ return false+ }+ if (!isLoopbackUrl(candidateUrl)) return false++ return args.registered.some((registered) => {+ try {+ const registeredUrl = new URL(registered)+ return (+ isLoopbackUrl(registeredUrl)+ && registeredUrl.protocol === candidateUrl.protocol+ && registeredUrl.hostname === candidateUrl.hostname+ && registeredUrl.pathname === candidateUrl.pathname+ )+ } catch {+ return false+ }+ })+}++export function isAcceptableRedirectUri(raw: string): boolean {+ let parsed: URL+ try {+ parsed = new URL(raw)+ } catch {+ return false+ }+ if (parsed.hash) return false+ if (parsed.protocol === 'https:') return true+ // http is allowed only on loopback. There is deliberately no NODE_ENV escape+ // hatch: an install running without NODE_ENV=production would otherwise let+ // any client register a plaintext redirect to a host it does not control.+ if (parsed.protocol === 'http:') return isLoopbackUrl(parsed)+ return false+}++export function buildRedirectUrl(args: BuildRedirectUrlArgs): string {+ const url = new URL(args.redirectUri)+ for (const [key, value] of Object.entries(args.params)) {+ if (value !== undefined) url.searchParams.set(key, value)+ }+ return url.toString()+}++/**+ * RFC 8707 audience binding: a token minted for one MCP resource must not be+ * replayable against another. Compared on origin + path, ignoring trailing slash.+ */+export function resourceMatches(args: ResourceMatchArgs): boolean {+ if (!args.granted || !args.requested) return true+ const normalize = (value: string) => value.replace(/\/+$/, '').toLowerCase()+ return normalize(args.granted) === normalize(args.requested)+}diff --git a/api/src/tv-modules/oauth/types.ts b/api/src/tv-modules/oauth/types.tsnew file mode 100644index 0000000..8cd7f31--- /dev/null+++ b/api/src/tv-modules/oauth/types.ts@@ -0,0 +1,205 @@+import type { Response } from 'express'+import type { OAuthGrantsSchemaTypeForSelect } from 'taskview-db-schemas'+import { type } from 'arktype'++export const OAUTH_ACCESS_TOKEN_PREFIX = 'tvo_'+export const OAUTH_CODE_TTL_SECONDS = 60+export const OAUTH_ACCESS_TOKEN_TTL_SECONDS = 60 * 60+export const OAUTH_REFRESH_TOKEN_TTL_SECONDS = 60 * 60 * 24 * 30++export const OAuthAuthorizeArkType = type({+ response_type: "'code'",+ client_id: 'string > 0',+ redirect_uri: 'string > 0',+ code_challenge: 'string > 0',+ code_challenge_method: "'S256'",+ 'state?': 'string',+ 'resource?': 'string',+})++export type OAuthAuthorizeArgs = typeof OAuthAuthorizeArkType.infer++export const OAuthConsentArkType = type({+ client_id: 'string > 0',+ redirect_uri: 'string > 0',+ code_challenge: 'string > 0',+ code_challenge_method: "'S256'",+ 'allowedPermissions?': 'string[]',+ 'allowedGoalIds?': 'number[]',+ 'state?': 'string',+ 'resource?': 'string',+})++export type OAuthConsentArgs = typeof OAuthConsentArkType.infer++export const OAuthTokenArkType = type({+ grant_type: "'authorization_code'|'refresh_token'",+ 'client_id?': 'string',+ 'client_secret?': 'string',+ 'code?': 'string',+ 'code_verifier?': 'string',+ 'redirect_uri?': 'string',+ 'refresh_token?': 'string',+ 'resource?': 'string',+})++export type OAuthTokenArgs = typeof OAuthTokenArkType.infer++export const OAuthRegisterArkType = type({+ 'client_name?': 'string',+ redirect_uris: 'string[] > 0',+ 'token_endpoint_auth_method?': 'string',+ 'grant_types?': 'string[]',+ 'response_types?': 'string[]',+})++export type OAuthRegisterArgs = typeof OAuthRegisterArkType.infer++export const OAuthRevokeArkType = type({+ token: 'string > 0',+ 'token_type_hint?': 'string',+})++export type OAuthRevokeArgs = typeof OAuthRevokeArkType.infer++export type CreateAuthCodeArgs = {+ clientId: string+ userId: number+ redirectUri: string+ codeChallenge: string+ codeChallengeMethod: string+ allowedPermissions: string[]+ allowedGoalIds: number[]+ resource: string | null+}++export type ExchangeCodeArgs = {+ code: string+ codeVerifier: string+ clientId: string+ redirectUri: string+ resource: string | null+}++export type RefreshTokensArgs = {+ refreshToken: string+ clientId: string+ resource: string | null+}++export type RegisterClientArgs = {+ name: string+ redirectUris: string[]+ isPublic: boolean+}++export type OAuthTokenResponse = {+ access_token: string+ token_type: 'Bearer'+ expires_in: number+ refresh_token: string+}++export type OAuthFailure = { ok: false; error: string; description: string }+export type OAuthSuccess<T> = { ok: true; value: T }+export type OAuthResult<T> = OAuthSuccess<T> | OAuthFailure++export type ConnectedApp = {+ grantId: number+ clientId: string+ clientName: string+ allowedPermissions: string[]+ allowedGoalIds: number[]+ createdAt: Date+ lastUsedAt: Date | null+}++export type CreateOAuthClientArgs = {+ clientId: string+ clientSecretHash: string | null+ name: string+ redirectUris: string[]+ createdVia: string+}++export type ConsumeAuthCodeArgs = {+ id: number+ grantId: number+}++export type RotateRefreshTokenArgs = {+ grantId: number+ refreshTokenHash: string+ prevHash: string | null+ refreshExpiresAt: Date+}++export type RevokeGrantArgs = {+ grantId: number+ /** Omitted for server-side revocation; set when the owner revokes from the UI. */+ userId?: number+}++export type RevokeOwnGrantArgs = {+ grantId: number+ userId: number+}++export type CreateAccessTokenArgs = {+ userId: number+ name: string+ tokenHash: string+ allowedPermissions: string[]+ allowedGoalIds: number[]+ grantId: number+ expiresAt: Date+}++export type ValidateRedirectUriArgs = {+ clientId: string+ redirectUri: string+}++export type AuthenticateClientArgs = {+ clientId: string+ clientSecret?: string+}++export type IssueTokenPairArgs = {+ grant: OAuthGrantsSchemaTypeForSelect+ clientName: string+ prevRefreshHash?: string+}++export type VerifyPkceArgs = {+ codeVerifier: string+ codeChallenge: string+}++export type MatchRedirectUriArgs = {+ candidate: string+ registered: string[]+}++export type BuildRedirectUrlArgs = {+ redirectUri: string+ params: Record<string, string | undefined>+}++export type ResourceMatchArgs = {+ granted: string | null+ requested: string | null+}++export type SendTokenSuccessArgs = {+ res: Response+ body: Record<string, unknown>+}++export type SendTokenErrorArgs = {+ res: Response+ status: number+ error: string+ description: string+}+diff --git a/api/types/oauth.types.ts b/api/types/oauth.types.tsnew file mode 100644index 0000000..3af41c6--- /dev/null+++ b/api/types/oauth.types.ts@@ -0,0 +1,4 @@+export type OAuthConsentSelection = {+ allowedGoalIds: number[]+ allowedPermissions: string[]+}diff --git a/taskview-packages/taskview-api/src/api/oauth.ts b/taskview-packages/taskview-api/src/api/oauth.tsnew file mode 100644index 0000000..2f721c6--- /dev/null+++ b/taskview-packages/taskview-api/src/api/oauth.ts@@ -0,0 +1,35 @@+import TvApiBase from './base';+import type { AppResponse } from '@/api/base.types';+import type {+ OAuthConnectedApp,+ OAuthConsentRequest,+ OAuthConsentResponse,+} from './oauth.types';++export default class TvOAuth extends TvApiBase {+ protected moduleUrl = '/module/oauth';++ public async approveConsent(data: OAuthConsentRequest) {+ return this.request(+ this.$axios.post<AppResponse<OAuthConsentResponse>>(`${this.moduleUrl}/consent`, data)+ );+ }++ public async denyConsent(data: OAuthConsentRequest) {+ return this.request(+ this.$axios.post<AppResponse<OAuthConsentResponse>>(`${this.moduleUrl}/consent/deny`, data)+ );+ }++ public async fetchConnectedApps() {+ return this.request(+ this.$axios.get<AppResponse<OAuthConnectedApp[]>>(`${this.moduleUrl}/connected-apps`)+ );+ }++ public async revokeConnectedApp(grantId: number) {+ return this.request(+ this.$axios.delete<AppResponse<boolean>>(`${this.moduleUrl}/connected-apps`, { data: { grantId } })+ );+ }+}diff --git a/taskview-packages/taskview-api/src/api/oauth.types.ts b/taskview-packages/taskview-api/src/api/oauth.types.tsnew file mode 100644index 0000000..d7688f1--- /dev/null+++ b/taskview-packages/taskview-api/src/api/oauth.types.ts@@ -0,0 +1,25 @@+export type OAuthConsentRequest = {+ client_id: string;+ redirect_uri: string;+ code_challenge: string;+ code_challenge_method: 'S256';+ /** Empty means "do not narrow" — same semantics as a tvk_ token with no permissions picked. */+ allowedPermissions?: string[];+ allowedGoalIds?: number[];+ state?: string;+ resource?: string;+};++export type OAuthConsentResponse = {+ redirectUrl: string;+};++export type OAuthConnectedApp = {+ grantId: number;+ clientId: string;+ clientName: string;+ allowedPermissions: string[];+ allowedGoalIds: number[];+ createdAt: string | null;+ lastUsedAt: string | null;+};diff --git a/taskview-packages/taskview-api/src/index.ts b/taskview-packages/taskview-api/src/index.tsindex fcd0c40..1db36d0 100644--- a/taskview-packages/taskview-api/src/index.ts+++ b/taskview-packages/taskview-api/src/index.ts@@ -14,6 +14,7 @@ export * from '@/api/notifications.api.types';export * from '@/api/webhooks.types';export * from '@/api/messaging.types';export * from '@/api/api-tokens.types';+export * from '@/api/oauth.types';export * from '@/api/sessions.types';export * from '@/api/organizations.types';export * from '@/api/sso.types';diff --git a/taskview-packages/taskview-api/src/tv.ts b/taskview-packages/taskview-api/src/tv.tsindex b8965b1..a09fea9 100644--- a/taskview-packages/taskview-api/src/tv.ts+++ b/taskview-packages/taskview-api/src/tv.ts@@ -11,6 +11,7 @@ import TvNotificationsApi from "./api/notifications";import TvWebhooks from "./api/webhooks";import TvMessagingApi from "./api/messaging";import TvApiTokens from "./api/api-tokens";+import TvOAuth from "./api/oauth";import TvSessions from "./api/sessions";import TvOrganizationsApi from "./api/organizations";import TvSsoApi from "./api/sso";@@ -47,6 +48,7 @@ export class TvApi {public messaging: TvMessagingApi;public apiTokens: TvApiTokens;+ public oauth: TvOAuth;public sessions: TvSessions;@@ -90,6 +92,7 @@ export class TvApi {this.messaging = new TvMessagingApi(this.$axios);this.apiTokens = new TvApiTokens(this.$axios);+ this.oauth = new TvOAuth(this.$axios);this.sessions = new TvSessions(this.$axios);diff --git a/taskview-packages/taskview-db-schemas/src/index.ts b/taskview-packages/taskview-db-schemas/src/index.tsindex 01d4a42..06765a1 100644--- a/taskview-packages/taskview-db-schemas/src/index.ts+++ b/taskview-packages/taskview-db-schemas/src/index.ts@@ -16,6 +16,9 @@ export * from './schemas/notification-preferences.schema';export * from './schemas/webhooks.schema';export * from './schemas/messaging.schema';export * from './schemas/api-tokens.schema';+export * from './schemas/oauth-clients.schema';+export * from './schemas/oauth-auth-codes.schema';+export * from './schemas/oauth-grants.schema';export * from './schemas/user-tokens.schema';export * from './schemas/organizations.schema';export * from './schemas/sso.schema';diff --git a/taskview-packages/taskview-db-schemas/src/schemas/api-tokens.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/api-tokens.schema.tsindex a0a9b7e..ac904f9 100644--- a/taskview-packages/taskview-db-schemas/src/schemas/api-tokens.schema.ts+++ b/taskview-packages/taskview-db-schemas/src/schemas/api-tokens.schema.ts@@ -7,6 +7,7 @@ export const ApiTokensSchema = pgSchema('tv_auth').table('api_tokens', {tokenHash: varchar('token_hash', { length: 64 }).notNull().unique(),allowedPermissions: varchar('allowed_permissions').array().notNull().default([]),allowedGoalIds: integer('allowed_goal_ids').array().notNull().default([]),+ grantId: integer('grant_id'),lastUsedAt: timestamp('last_used_at'),expiresAt: timestamp('expires_at'),createdAt: timestamp('created_at').defaultNow(),diff --git a/taskview-packages/taskview-db-schemas/src/schemas/oauth-auth-codes.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/oauth-auth-codes.schema.tsnew file mode 100644index 0000000..7f6b1c8--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/oauth-auth-codes.schema.ts@@ -0,0 +1,21 @@+import { pgSchema, integer, timestamp, varchar } from "drizzle-orm/pg-core";++export const OAuthAuthCodesSchema = pgSchema('tv_auth').table('oauth_auth_codes', {+ id: integer().primaryKey().generatedAlwaysAsIdentity(),+ codeHash: varchar('code_hash', { length: 64 }).notNull().unique(),+ clientId: varchar('client_id', { length: 64 }).notNull(),+ userId: integer('user_id').notNull(),+ redirectUri: varchar('redirect_uri').notNull(),+ codeChallenge: varchar('code_challenge', { length: 128 }).notNull(),+ codeChallengeMethod: varchar('code_challenge_method', { length: 8 }).notNull().default('S256'),+ allowedPermissions: varchar('allowed_permissions').array().notNull().default([]),+ allowedGoalIds: integer('allowed_goal_ids').array().notNull().default([]),+ resource: varchar(),+ expiresAt: timestamp('expires_at').notNull(),+ usedAt: timestamp('used_at'),+ grantId: integer('grant_id'),+ createdAt: timestamp('created_at').notNull().defaultNow(),+});++export type OAuthAuthCodesSchemaTypeForSelect = typeof OAuthAuthCodesSchema.$inferSelect;+export type OAuthAuthCodesSchemaTypeForInsert = typeof OAuthAuthCodesSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/oauth-clients.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/oauth-clients.schema.tsnew file mode 100644index 0000000..773a4a8--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/oauth-clients.schema.ts@@ -0,0 +1,14 @@+import { pgSchema, integer, timestamp, varchar } from "drizzle-orm/pg-core";++export const OAuthClientsSchema = pgSchema('tv_auth').table('oauth_clients', {+ id: integer().primaryKey().generatedAlwaysAsIdentity(),+ clientId: varchar('client_id', { length: 64 }).notNull().unique(),+ clientSecretHash: varchar('client_secret_hash', { length: 64 }),+ name: varchar({ length: 200 }).notNull(),+ redirectUris: varchar('redirect_uris').array().notNull().default([]),+ createdVia: varchar('created_via', { length: 16 }).notNull().default('manual'),+ createdAt: timestamp('created_at').notNull().defaultNow(),+});++export type OAuthClientsSchemaTypeForSelect = typeof OAuthClientsSchema.$inferSelect;+export type OAuthClientsSchemaTypeForInsert = typeof OAuthClientsSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/oauth-grants.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/oauth-grants.schema.tsnew file mode 100644index 0000000..5165ac0--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/oauth-grants.schema.ts@@ -0,0 +1,19 @@+import { pgSchema, integer, timestamp, varchar } from "drizzle-orm/pg-core";++export const OAuthGrantsSchema = pgSchema('tv_auth').table('oauth_grants', {+ id: integer().primaryKey().generatedAlwaysAsIdentity(),+ userId: integer('user_id').notNull(),+ clientId: varchar('client_id', { length: 64 }).notNull(),+ allowedPermissions: varchar('allowed_permissions').array().notNull().default([]),+ allowedGoalIds: integer('allowed_goal_ids').array().notNull().default([]),+ resource: varchar(),+ refreshTokenHash: varchar('refresh_token_hash', { length: 64 }),+ refreshTokenPrevHash: varchar('refresh_token_prev_hash', { length: 64 }),+ refreshExpiresAt: timestamp('refresh_expires_at'),+ lastUsedAt: timestamp('last_used_at'),+ revokedAt: timestamp('revoked_at'),+ createdAt: timestamp('created_at').notNull().defaultNow(),+});++export type OAuthGrantsSchemaTypeForSelect = typeof OAuthGrantsSchema.$inferSelect;+export type OAuthGrantsSchemaTypeForInsert = typeof OAuthGrantsSchema.$inferInsert;diff --git a/taskview-packages/taskview-mcp/README.md b/taskview-packages/taskview-mcp/README.mdindex 94f1954..7c3ec2e 100644--- a/taskview-packages/taskview-mcp/README.md+++ b/taskview-packages/taskview-mcp/README.md@@ -73,6 +73,8 @@ Then use `"command": "taskview-mcp"` (no `args` needed).| `TASKVIEW_URL` | yes | TaskView API server URL (e.g. `https://api.taskview.tech`) || `TASKVIEW_TOKEN` | yes (stdio mode) | API token with `tvk_` prefix. Not used in HTTP mode — each caller sends their own token || `MCP_HTTP_PORT` | no (HTTP mode) | Port for the HTTP server, default `3100` |+| `MCP_PUBLIC_URL` | no (HTTP mode) | Public URL of this server as clients reach it. Used as the OAuth resource identifier; derived from the request host when unset |+| `MCP_ALLOWED_ORIGINS` | no (HTTP mode) | Comma-separated browser origins allowed to call `/mcp`. Unset means no browser origin is allowed; non-browser clients send no `Origin` and are unaffected |## HTTP server (remote / self-hosted)@@ -112,6 +114,29 @@ Self-hosted instances run their own copy next to their API (see `Dockerfile`in this package) — point `TASKVIEW_URL` at your API server and put the MCPport behind your reverse proxy with HTTPS.+### OAuth (ChatGPT and other cloud clients)++Clients that will not accept a pasted API token — ChatGPT connectors among+them — authorize over OAuth 2.1 instead. Nothing extra runs here: this server+advertises itself as the protected resource and points at your TaskView API,+which is the authorization server.++- `GET /.well-known/oauth-protected-resource` returns the resource metadata+ (RFC 9728), naming `TASKVIEW_URL` as the authorization server.+- A request with no token answers `401` with+ `WWW-Authenticate: Bearer resource_metadata="…"`, which is what starts+ discovery in the client.+- The client then registers, sends the user to the TaskView consent screen,+ and comes back with a `tvo_` access token that it sends here like any other+ bearer token.++Set `MCP_PUBLIC_URL` to the externally reachable URL of this server so the+advertised resource identifier matches what clients actually request.++Manually issued `tvk_` tokens keep working exactly as before — OAuth is an+additional way in, not a replacement. Use `tvk_` for stdio, CLIs and CI, where+there is no browser to complete an authorization flow.+## Available tools61 tools covering the full TaskView surface.diff --git a/taskview-packages/taskview-mcp/src/http.ts b/taskview-packages/taskview-mcp/src/http.tsindex 31e1d90..20338e6 100644--- a/taskview-packages/taskview-mcp/src/http.ts+++ b/taskview-packages/taskview-mcp/src/http.ts@@ -4,10 +4,20 @@ import axios from 'axios'import { TvApi } from 'taskview-api'import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'import { createMcpServer } from './server.js'-import type { HandleMcpRequestArgs } from './http.types.js'+import type { CorsHeadersArgs, HandleMcpRequestArgs, UnauthorizedArgs } from './http.types.js'const TASKVIEW_URL = process.env.TASKVIEW_URLconst PORT = Number(process.env.MCP_HTTP_PORT || 3100)+// Public URL of THIS server, as clients reach it. It is the OAuth "resource"+// identifier, so it must match what the client puts in the resource parameter.+const MCP_PUBLIC_URL = process.env.MCP_PUBLIC_URL?.replace(/\/+$/, '')+// Browser origins allowed to call /mcp. Unset means no browser origin is+// allowed — non-browser clients (ChatGPT, Claude, CLIs) send no Origin and are+// unaffected. Guards against DNS rebinding, which the MCP spec calls out.+const ALLOWED_ORIGINS = (process.env.MCP_ALLOWED_ORIGINS ?? '')+ .split(',')+ .map((value) => value.trim())+ .filter(Boolean)if (!TASKVIEW_URL) {console.error('Required environment variable: TASKVIEW_URL')@@ -15,11 +25,50 @@ if (!TASKVIEW_URL) {process.exit(1)}-const CORS_HEADERS = {- 'Access-Control-Allow-Origin': '*',- 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',- 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version',- 'Access-Control-Expose-Headers': 'Mcp-Session-Id',+function corsHeaders({ origin }: CorsHeadersArgs): Record<string, string> {+ const headers: Record<string, string> = {+ 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version',+ 'Access-Control-Expose-Headers': 'Mcp-Session-Id',+ Vary: 'Origin',+ }+ if (origin && ALLOWED_ORIGINS.includes(origin)) {+ headers['Access-Control-Allow-Origin'] = origin+ }+ return headers+}++function resourceUrl(req: IncomingMessage): string {+ if (MCP_PUBLIC_URL) return MCP_PUBLIC_URL+ const host = req.headers.host ?? `localhost:${PORT}`+ const proto = (req.headers['x-forwarded-proto'] as string | undefined)?.split(',')[0]?.trim()+ return `${proto || 'http'}://${host}`+}++/**+ * RFC 9728. Discovery starts here: the 401 below points at this document, and+ * this document points at the TaskView API that issues the tokens.+ */+function protectedResourceMetadata(req: IncomingMessage) {+ return {+ resource: resourceUrl(req),+ authorization_servers: [TASKVIEW_URL],+ bearer_methods_supported: ['header'],+ }+}++function sendUnauthorized({ req, res, message }: UnauthorizedArgs) {+ const metadataUrl = `${resourceUrl(req)}/.well-known/oauth-protected-resource`+ res.writeHead(401, {+ 'Content-Type': 'application/json',+ 'WWW-Authenticate': `Bearer resource_metadata="${metadataUrl}"`,+ }).end(+ JSON.stringify({+ jsonrpc: '2.0',+ error: { code: -32000, message },+ id: null,+ }),+ )}function extractBearerToken(req: IncomingMessage): string | null {@@ -53,7 +102,9 @@ async function handleMcpRequest({ req, res, token }: HandleMcpRequestArgs) {}const httpServer = createServer(async (req, res) => {- for (const [name, value] of Object.entries(CORS_HEADERS)) res.setHeader(name, value)+ for (const [name, value] of Object.entries(corsHeaders({ origin: req.headers.origin }))) {+ res.setHeader(name, value)+ }if (req.method === 'OPTIONS') {res.writeHead(204).end()@@ -67,6 +118,13 @@ const httpServer = createServer(async (req, res) => {return}+ if (path === '/.well-known/oauth-protected-resource') {+ res.writeHead(200, { 'Content-Type': 'application/json' }).end(+ JSON.stringify(protectedResourceMetadata(req)),+ )+ return+ }+if (path !== '/mcp') {res.writeHead(404, { 'Content-Type': 'application/json' }).end(JSON.stringify({ message: 'Not found. MCP endpoint is /mcp' }))return@@ -74,13 +132,11 @@ const httpServer = createServer(async (req, res) => {const token = extractBearerToken(req)if (!token) {- res.writeHead(401, { 'Content-Type': 'application/json', 'WWW-Authenticate': 'Bearer' }).end(- JSON.stringify({- jsonrpc: '2.0',- error: { code: -32000, message: 'Unauthorized: provide your TaskView API token as "Authorization: Bearer tvk_..."' },- id: null,- }),- )+ sendUnauthorized({+ req,+ res,+ message: 'Unauthorized: authorize with OAuth, or send a TaskView API token as "Authorization: Bearer tvk_..."',+ })return}diff --git a/taskview-packages/taskview-mcp/src/http.types.ts b/taskview-packages/taskview-mcp/src/http.types.tsindex 6425fbc..e1f0b1b 100644--- a/taskview-packages/taskview-mcp/src/http.types.ts+++ b/taskview-packages/taskview-mcp/src/http.types.ts@@ -5,3 +5,13 @@ export type HandleMcpRequestArgs = {res: ServerResponsetoken: string}++export type CorsHeadersArgs = {+ origin: string | undefined+}++export type UnauthorizedArgs = {+ req: IncomingMessage+ res: ServerResponse+ message: string+}diff --git a/web/src/bootstrap.ts b/web/src/bootstrap.tsindex d329aab..79a6f8c 100644--- a/web/src/bootstrap.ts+++ b/web/src/bootstrap.ts@@ -14,6 +14,7 @@ import { i18n, restoreSavedLocale } from './plugins/i18n'import { storeResetPlugin } from './plugins/pinia'import App from './App.vue'import authenticated from './middleware/authenticated'+import authenticatedWithReturn from './middleware/authenticated-with-return'import syncSelectedProject from './middleware/syncSelectedProject'import api from './plugins/axios'import LoginPage from './pages/login.vue'@@ -37,6 +38,15 @@ function buildRoutes(extensions: TvWebExtension[]): RouteRecordRaw[] {name: 'reset-password',component: () => import('./pages/reset-password.vue'),},+ {+ // Outside /:orgSlug on purpose — the OAuth flow lands here before any+ // organization is chosen. The guard sends an unauthenticated user to+ // login and back, so consent is always given by a real browser session.+ path: '/oauth/consent',+ name: 'oauth-consent',+ component: () => import('./pages/oauth-consent.vue'),+ beforeEnter: [authenticatedWithReturn],+ },...extensionRoutes,{path: '/:orgSlug',diff --git a/web/src/components/features/account/AccountSettings.vue b/web/src/components/features/account/AccountSettings.vueindex 79562c6..8b32c54 100644--- a/web/src/components/features/account/AccountSettings.vue+++ b/web/src/components/features/account/AccountSettings.vue@@ -16,6 +16,13 @@<ApiTokensPanel /></UPageCard>+ <UPageCard+ variant="soft"+ class="w-full rounded-3xl"+ >+ <ConnectedAppsPanel />+ </UPageCard>+<UPageCardv-if="isDefaultUser"variant="soft"@@ -68,6 +75,7 @@ import PasswordSettings from './parts/PasswordSettings.vue'import DefaultUserCredentials from './parts/DefaultUserCredentials.vue'import SessionsPanel from '@/components/features/sessions/SessionsPanel.vue'import ApiTokensPanel from '@/components/features/api-tokens/ApiTokensPanel.vue'+import ConnectedAppsPanel from '@/components/features/oauth/ConnectedAppsPanel.vue'const { t } = useI18n()const userStore = useUserStore()diff --git a/web/src/components/features/api-tokens/parts/CreateApiTokenModal.vue b/web/src/components/features/api-tokens/parts/CreateApiTokenModal.vueindex 6c99266..2b64054 100644--- a/web/src/components/features/api-tokens/parts/CreateApiTokenModal.vue+++ b/web/src/components/features/api-tokens/parts/CreateApiTokenModal.vue@@ -49,26 +49,7 @@class="underline underline-offset-2 hover:text-default">{{ t('apiTokens.permissionsDocs') }}</a></p>- <div class="max-h-64 overflow-y-auto border border-default rounded-lg p-3">- <div- v-for="(group, groupId) in groupedPermissions"- :key="groupId"- class="mb-3 last:mb-0"- >- <p class="text-xs font-semibold text-muted mb-1 uppercase">- {{ group.name }}- </p>- <div class="flex flex-col gap-1">- <UCheckbox- v-for="perm in group.items"- :key="perm.id"- :model-value="selectedPermissions.includes(perm.name)"- :label="perm.description || perm.name"- @update:model-value="togglePermission(perm.name)"- />- </div>- </div>- </div>+ <TvPermissionPicker v-model="selectedPermissions" /></UFormField></div></template>@@ -129,12 +110,13 @@</template><script setup lang="ts">-import { ref, computed, onMounted } from 'vue'+import { ref, computed } from 'vue'import { useI18n } from 'vue-i18n'import { useClipboard } from '@vueuse/core'import { useApiTokensStore } from '@/stores/api-tokens.store'import { useGoalsStore } from '@/stores/goals.store'import { useTaskView } from '@/composables/useTaskView'+import TvPermissionPicker from '@/components/features/base/TvPermissionPicker.vue'const isOpen = defineModel<boolean>('open', { default: false })@@ -170,34 +152,6 @@ const goalOptions = computed(() =>.map((g) => ({ label: g.name, value: g.id })),)-const permissionGroupNames: Record<number, string> = {- 1: 'Application level',- 2: 'Project',- 3: 'Lists',- 4: 'Tasks',-}--const groupedPermissions = computed(() => {- const groups: Record<number, { name: string; items: typeof store.permissions }> = {}- for (const perm of store.permissions) {- const gid = perm.permissionGroup- if (!groups[gid]) {- groups[gid] = { name: permissionGroupNames[gid] || `Group ${gid}`, items: [] }- }- groups[gid].items.push(perm)- }- return groups-})--function togglePermission(permName: string) {- const idx = selectedPermissions.value.indexOf(permName)- if (idx === -1) {- selectedPermissions.value.push(permName)- } else {- selectedPermissions.value.splice(idx, 1)- }-}-function getExpiresAt(): string | null {if (expiration.value === 'none') return nullconst days = parseInt(expiration.value)@@ -231,9 +185,4 @@ async function handleCreate() {}}-onMounted(() => {- if (store.permissions.length === 0) {- store.fetchPermissions()- }-})</script>diff --git a/web/src/components/features/auth/auth.helper.ts b/web/src/components/features/auth/auth.helper.tsindex b8892c3..10960be 100644--- a/web/src/components/features/auth/auth.helper.ts+++ b/web/src/components/features/auth/auth.helper.ts@@ -5,10 +5,23 @@ import { useOrganizationStore } from '@/stores/organization.store'import { useUiPreferencesStore } from '@/stores/uiPreferences.store'import { useProjectRoute } from '@/composables/useProjectRoute'+/** Only internal absolute paths — never an absolute URL, which would be an open redirect. */+const safeReturnPath = (raw: unknown): string | null => {+ if (typeof raw !== 'string') return null+ if (!raw.startsWith('/') || raw.startsWith('//')) return null+ return raw+}+export const redirectToUser = async (router: Router) => {const userStore = useUserStore()if (!userStore.accessToken) return+ const returnPath = safeReturnPath(router.currentRoute.value.query.redirect)+ if (returnPath) {+ await router.replace(returnPath)+ return+ }+const orgStore = useOrganizationStore()if (!orgStore.organizations.length) {await orgStore.fetchOrganizations()diff --git a/web/src/components/features/base/TvPermissionPicker.vue b/web/src/components/features/base/TvPermissionPicker.vuenew file mode 100644index 0000000..f4567da--- /dev/null+++ b/web/src/components/features/base/TvPermissionPicker.vue@@ -0,0 +1,61 @@+<template>+ <div class="max-h-64 overflow-y-auto border border-default rounded-lg p-3">+ <div+ v-for="(group, groupId) in groupedPermissions"+ :key="groupId"+ class="mb-3 last:mb-0"+ >+ <p class="text-xs font-semibold text-muted mb-1 uppercase">+ {{ group.name }}+ </p>+ <div class="flex flex-col gap-1">+ <UCheckbox+ v-for="perm in group.items"+ :key="perm.id"+ :model-value="selected.includes(perm.name)"+ :label="perm.description || perm.name"+ @update:model-value="toggle(perm.name)"+ />+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed, onMounted } from 'vue'+import { useI18n } from 'vue-i18n'+import { useApiTokensStore } from '@/stores/api-tokens.store'+import type { ApiTokenPermission } from 'taskview-api'++const selected = defineModel<string[]>({ default: () => [] })++const { t } = useI18n()+const store = useApiTokensStore()++const groupedPermissions = computed(() => {+ const groups: Record<number, { name: string; items: ApiTokenPermission[] }> = {}+ for (const perm of store.permissions) {+ const gid = perm.permissionGroup+ if (!groups[gid]) {+ groups[gid] = { name: t(`permissionGroups.${gid}`), items: [] }+ }+ groups[gid].items.push(perm)+ }+ return groups+})++function toggle(permName: string) {+ const index = selected.value.indexOf(permName)+ if (index === -1) {+ selected.value = [...selected.value, permName]+ } else {+ selected.value = selected.value.filter((name) => name !== permName)+ }+}++onMounted(() => {+ if (store.permissions.length === 0) {+ store.fetchPermissions()+ }+})+</script>diff --git a/web/src/components/features/oauth/ConnectedAppsPanel.vue b/web/src/components/features/oauth/ConnectedAppsPanel.vuenew file mode 100644index 0000000..bdeed8e--- /dev/null+++ b/web/src/components/features/oauth/ConnectedAppsPanel.vue@@ -0,0 +1,55 @@+<template>+ <div>+ <div class="mb-4">+ <h2 class="text-lg font-semibold">+ {{ t('oauth.connectedApps.title') }}+ </h2>+ <p class="text-sm text-muted">+ {{ t('oauth.connectedApps.description') }}+ </p>+ </div>++ <div+ v-if="store.loading"+ class="flex items-center justify-center h-32"+ >+ <p>{{ t('common.loading') }}</p>+ </div>++ <div+ v-else-if="store.connectedApps.length === 0"+ class="flex flex-col items-center justify-center h-32 text-muted"+ >+ <UIcon+ name="i-lucide-plug"+ class="size-10 mb-3"+ />+ <p>{{ t('oauth.connectedApps.empty') }}</p>+ </div>++ <div+ v-else+ class="flex flex-col gap-3"+ >+ <ConnectedAppItem+ v-for="app in store.connectedApps"+ :key="app.grantId"+ :app="app"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import { onMounted } from 'vue'+import { useI18n } from 'vue-i18n'+import { useOAuthStore } from '@/stores/oauth.store'+import ConnectedAppItem from './parts/ConnectedAppItem.vue'++const { t } = useI18n()+const store = useOAuthStore()++onMounted(() => {+ store.fetchConnectedApps()+})+</script>diff --git a/web/src/components/features/oauth/OAuthConsentCard.vue b/web/src/components/features/oauth/OAuthConsentCard.vuenew file mode 100644index 0000000..10be27d--- /dev/null+++ b/web/src/components/features/oauth/OAuthConsentCard.vue@@ -0,0 +1,169 @@+<template>+ <UCard class="w-full max-w-lg">+ <template #header>+ <div class="flex items-start gap-3">+ <UIcon+ name="i-lucide-plug-zap"+ class="size-6 shrink-0 text-primary"+ />+ <div>+ <h1 class="text-lg font-semibold">+ {{ t('oauth.consent.title', { client: clientName }) }}+ </h1>+ <p class="text-sm text-muted mt-1">+ {{ t('oauth.consent.subtitle', { client: clientName }) }}+ </p>+ </div>+ </div>++ <div class="mt-4 rounded-lg bg-elevated p-3">+ <p class="text-xs text-muted">+ {{ t('oauth.consent.destinationLabel') }}+ </p>+ <p class="font-medium break-all mt-0.5">+ {{ redirectHost }}+ </p>+ <p class="text-xs text-muted break-all mt-0.5">+ {{ redirectUri }}+ </p>+ <p class="text-xs text-muted mt-2">+ {{ isLocalDestination+ ? t('oauth.consent.destinationLocalHint')+ : t('oauth.consent.destinationHint') }}+ </p>+ </div>+ </template>++ <div class="flex flex-col gap-5">+ <UAlert+ icon="i-lucide-shield-check"+ color="neutral"+ variant="soft"+ :description="t('oauth.consent.rbacNote')"+ />++ <UFormField :label="t('oauth.consent.projectsLabel')">+ <USelectMenu+ v-model="selectedGoalIds"+ :items="goalOptions"+ multiple+ value-key="value"+ :search-input="false"+ class="w-full"+ :placeholder="t('oauth.consent.allProjects')"+ />+ <UAlert+ v-if="!selectedGoalIds.length"+ icon="i-lucide-triangle-alert"+ color="warning"+ variant="soft"+ class="mt-2"+ :ui="{ description: 'text-xs' }"+ :description="t('oauth.consent.projectsWarning')"+ />+ <p+ v-else+ class="text-xs text-muted mt-2"+ >+ {{ t('oauth.consent.projectsHint') }}+ </p>+ </UFormField>++ <UFormField :label="t('oauth.consent.permissionsLabel')">+ <TvPermissionPicker v-model="selectedPermissions" />+ <UAlert+ v-if="!selectedPermissions.length"+ icon="i-lucide-triangle-alert"+ color="warning"+ variant="soft"+ class="mt-2"+ :ui="{ description: 'text-xs' }"+ :description="t('oauth.consent.permissionsWarning')"+ />+ <p+ v-else+ class="text-xs text-muted mt-2"+ >+ {{ t('oauth.consent.permissionsHint') }}+ </p>+ </UFormField>+ </div>++ <template #footer>+ <div class="flex flex-col-reverse sm:flex-row sm:justify-end gap-2">+ <UButton+ :label="t('oauth.consent.deny')"+ color="neutral"+ variant="ghost"+ :disabled="store.submitting"+ @click="emit('deny')"+ />+ <UButton+ :label="t('oauth.consent.approve')"+ color="primary"+ :loading="store.submitting"+ @click="onApprove"+ />+ </div>+ </template>+ </UCard>+</template>++<script setup lang="ts">+import { computed, ref } from 'vue'+import { useI18n } from 'vue-i18n'+import { useOAuthStore } from '@/stores/oauth.store'+import { useGoalsStore } from '@/stores/goals.store'+import TvPermissionPicker from '@/components/features/base/TvPermissionPicker.vue'+import type { OAuthConsentSelection } from '@/types/oauth.types'++const { t } = useI18n()+const store = useOAuthStore()+const goalsStore = useGoalsStore()++const props = defineProps<{+ clientName: string+ redirectUri: string+}>()++const LOOPBACK_HOSTS = ['127.0.0.1', '::1', '[::1]', 'localhost']++const redirectUrl = computed(() => {+ try {+ return new URL(props.redirectUri)+ } catch {+ return null+ }+})++// The host is what a person can actually check against the app they think they+// are connecting; the full URI stays visible underneath it.+const redirectHost = computed(() => redirectUrl.value?.host ?? props.redirectUri)++const isLocalDestination = computed(() =>+ !!redirectUrl.value && LOOPBACK_HOSTS.includes(redirectUrl.value.hostname),+)++const emit = defineEmits<{+ approve: [selection: OAuthConsentSelection]+ deny: []+}>()++// Nothing ticked means "everything you can do", the same as a tvk_ token issued+// with no permissions picked. The warning under the picker spells that out.+const selectedPermissions = ref<string[]>([])+const selectedGoalIds = ref<number[]>([])++const goalOptions = computed(() =>+ goalsStore.goals+ .filter((goal) => goal.archive === 0)+ .map((goal) => ({ label: goal.name, value: goal.id })),+)++function onApprove() {+ emit('approve', {+ allowedGoalIds: selectedGoalIds.value,+ allowedPermissions: selectedPermissions.value,+ })+}+</script>diff --git a/web/src/components/features/oauth/parts/ConnectedAppItem.vue b/web/src/components/features/oauth/parts/ConnectedAppItem.vuenew file mode 100644index 0000000..f0834d5--- /dev/null+++ b/web/src/components/features/oauth/parts/ConnectedAppItem.vue@@ -0,0 +1,115 @@+<template>+ <UCard+ variant="soft"+ :ui="{ body: 'w-full flex items-center justify-between p-4', root: 'rounded-2xl' }"+ >+ <div class="flex items-center gap-3 min-w-0">+ <UIcon+ name="i-lucide-plug-zap"+ class="size-5 shrink-0 text-primary"+ />+ <div class="min-w-0">+ <p class="font-medium truncate">+ {{ app.clientName }}+ </p>+ <div class="flex flex-wrap items-center gap-3 text-xs text-muted mt-1">+ <span v-if="app.createdAt">+ {{ t('oauth.connectedApps.connected') }}: {{ formatDate(app.createdAt) }}+ </span>+ <span>+ {{ t('oauth.connectedApps.lastUsed') }}:+ {{ app.lastUsedAt ? formatDate(app.lastUsedAt) : t('oauth.connectedApps.never') }}+ </span>+ </div>+ <div class="flex flex-wrap items-center gap-1 mt-1.5">+ <UBadge+ variant="subtle"+ size="xs"+ >+ {{ app.allowedPermissions.length+ ? t('oauth.connectedApps.permissionsCount', { count: app.allowedPermissions.length })+ : t('oauth.connectedApps.allPermissions') }}+ </UBadge>+ <UBadge+ variant="subtle"+ color="neutral"+ size="xs"+ >+ {{ app.allowedGoalIds.length+ ? t('oauth.connectedApps.projectsCount', { count: app.allowedGoalIds.length })+ : t('oauth.connectedApps.allProjects') }}+ </UBadge>+ </div>+ </div>+ </div>+ <UButton+ icon="i-lucide-trash-2"+ variant="ghost"+ color="error"+ size="xl"+ @click="showRevokeConfirm = true"+ />+ </UCard>++ <UModal+ v-model:open="showRevokeConfirm"+ :fullscreen="isMobile"+ >+ <template #header>+ <h3 class="text-lg font-semibold">+ {{ t('oauth.connectedApps.revoke') }}+ </h3>+ </template>+ <template #body>+ <p class="text-sm">+ {{ t('oauth.connectedApps.revokeConfirm', { client: app.clientName }) }}+ </p>+ </template>+ <template #footer>+ <div class="w-full flex justify-end gap-2">+ <UButton+ :label="t('common.cancel')"+ variant="ghost"+ @click="showRevokeConfirm = false"+ />+ <UButton+ :label="t('oauth.connectedApps.revoke')"+ color="error"+ variant="soft"+ :loading="revoking"+ @click="handleRevoke"+ />+ </div>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { ref } from 'vue'+import { useI18n } from 'vue-i18n'+import type { OAuthConnectedApp } from 'taskview-api'+import { useOAuthStore } from '@/stores/oauth.store'+import { useTaskView } from '@/composables/useTaskView'++const props = defineProps<{+ app: OAuthConnectedApp+}>()++const { t } = useI18n()+const { isMobile } = useTaskView()+const store = useOAuthStore()++const showRevokeConfirm = ref(false)+const revoking = ref(false)++function formatDate(dateStr: string) {+ return new Date(dateStr).toLocaleDateString()+}++async function handleRevoke() {+ revoking.value = true+ await store.revokeConnectedApp(props.app.grantId)+ showRevokeConfirm.value = false+ revoking.value = false+}+</script>diff --git a/web/src/locales/de.ts b/web/src/locales/de.tsindex 48e612d..b53e1b6 100644--- a/web/src/locales/de.ts+++ b/web/src/locales/de.ts@@ -656,6 +656,9 @@ export default {page: {title: 'Analytik',subtitle: 'Metriken zu Produktivität und Projektgesundheit',+ destinationLabel: 'Daten werden gesendet an',+ destinationHint: 'Prüfen Sie, ob diese Adresse zu der App gehört, die Sie verbinden. Den Namen oben gibt die App selbst an, er kann beliebig sein.',+ destinationLocalHint: 'Diese Adresse liegt auf Ihrem eigenen Rechner, die App läuft also lokal.',emptyState: 'Noch keine Daten. Erstellen Sie Aufgaben, um Analytik zu sehen.',emptyStateForPeriod: 'Keine Daten für den ausgewählten Zeitraum. Versuchen Sie einen längeren Zeitraum.',partialFailure: 'Einige Abschnitte konnten nicht geladen werden. Versuchen Sie es erneut.',@@ -914,6 +917,44 @@ export default {tokenFailed: 'Token konnte nicht generiert werden',toggleFailed: 'SCIM konnte nicht umgeschaltet werden',},+ permissionGroups: {+ 1: 'Anwendungsebene',+ 2: 'Projekt',+ 3: 'Listen',+ 4: 'Aufgaben',+ },+ oauth: {+ consent: {+ title: '{client} verbinden',+ subtitle: '{client} fragt Zugriff auf Ihr TaskView-Konto an.',+ rbacNote: 'Der Zugriff geht nie über Ihre eigenen Berechtigungen hinaus — was Sie in TaskView nicht dürfen, darf die App auch nicht.',+ projectsLabel: 'Auf Projekte beschränken',+ allProjects: 'Alle Projekte',+ projectsHint: 'Leer lassen, um alle Projekte zuzulassen, auf die Sie Zugriff haben.',+ permissionsLabel: 'Berechtigungen einschränken',+ permissionsHint: 'Leer lassen, um alles zu erlauben, was Sie selbst dürfen.',+ projectsWarning: 'Kein Projekt ausgewählt — die App erhält Zugriff auf alle Projekte, auf die Sie Zugriff haben.',+ permissionsWarning: 'Keine Berechtigung ausgewählt — die App darf alles tun, was Sie selbst dürfen.',+ approve: 'Zugriff erlauben',+ deny: 'Ablehnen',+ invalidTitle: 'Ungültige Autorisierungsanfrage',+ invalidDescription: 'In diesem Link fehlen erforderliche Parameter. Starten Sie die Verbindung in der App erneut.',+ },+ connectedApps: {+ title: 'Verbundene Apps',+ description: 'Apps, die in Ihrem Namen handeln dürfen. Ein Widerruf beendet den Zugriff sofort.',+ empty: 'Keine verbundenen Apps',+ connected: 'Verbunden',+ lastUsed: 'Zuletzt verwendet',+ never: 'nie',+ projectsCount: '{count} Projekte',+ permissionsCount: '{count} Berechtigungen',+ allPermissions: 'Alle Berechtigungen',+ allProjects: 'Alle Projekte',+ revoke: 'Zugriff widerrufen',+ revokeConfirm: 'Zugriff für {client} widerrufen? Die App funktioniert sofort nicht mehr.',+ },+ },apiTokens: {title: 'API-Tokens',description: 'Erstellen Sie Tokens, um programmgesteuert auf die API zuzugreifen.',diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 38f948f..d90e19b 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -670,6 +670,9 @@ export default {page: {title: 'Analytics',subtitle: 'Productivity and project health metrics',+ destinationLabel: 'Data will be sent to',+ destinationHint: 'Check that this address belongs to the app you are connecting. The name above is supplied by the app itself and can be anything.',+ destinationLocalHint: 'This address is on your own computer, so the app runs locally.',emptyState: 'No data yet. Create tasks to see analytics.',emptyStateForPeriod: 'No data for the selected period. Try a longer one.',partialFailure: 'Some sections failed to load. Try refreshing.',@@ -928,6 +931,44 @@ export default {tokenFailed: 'Failed to generate token',toggleFailed: 'Failed to toggle SCIM',},+ permissionGroups: {+ 1: 'Application level',+ 2: 'Project',+ 3: 'Lists',+ 4: 'Tasks',+ },+ oauth: {+ consent: {+ title: 'Connect {client}',+ subtitle: '{client} is asking for access to your TaskView account.',+ rbacNote: 'Access never exceeds your own permissions — if you cannot do something in TaskView, neither can this app.',+ projectsLabel: 'Limit to projects',+ allProjects: 'All projects',+ projectsHint: 'Leave empty to allow every project you have access to.',+ permissionsLabel: 'Limit permissions',+ permissionsHint: 'Leave empty to allow everything you can do yourself.',+ projectsWarning: 'No project selected — the app will be able to reach every project you have access to.',+ permissionsWarning: 'No permission selected — the app will be able to do everything you can do yourself.',+ approve: 'Allow access',+ deny: 'Deny',+ invalidTitle: 'Invalid authorization request',+ invalidDescription: 'This link is missing required parameters. Start the connection again from the app you were using.',+ },+ connectedApps: {+ title: 'Connected apps',+ description: 'Apps you allowed to act on your behalf. Revoking one cuts off its access immediately.',+ empty: 'No connected apps',+ connected: 'Connected',+ lastUsed: 'Last used',+ never: 'never',+ projectsCount: '{count} projects',+ permissionsCount: '{count} permissions',+ allPermissions: 'All permissions',+ allProjects: 'All projects',+ revoke: 'Revoke access',+ revokeConfirm: 'Revoke access for {client}? It will stop working immediately.',+ },+ },apiTokens: {title: 'API Tokens',description: 'Create tokens to access the API programmatically.',diff --git a/web/src/locales/es.ts b/web/src/locales/es.tsindex 83e0ea9..b8484dc 100644--- a/web/src/locales/es.ts+++ b/web/src/locales/es.ts@@ -656,6 +656,9 @@ export default {page: {title: 'Analíticas',subtitle: 'Métricas de productividad y estado del proyecto',+ destinationLabel: 'Los datos se enviarán a',+ destinationHint: 'Comprueba que esta dirección pertenece a la aplicación que estás conectando. El nombre de arriba lo indica la propia aplicación y puede ser cualquiera.',+ destinationLocalHint: 'Esta dirección está en tu propio equipo, así que la aplicación se ejecuta localmente.',emptyState: 'Aún no hay datos. Crea tareas para ver las analíticas.',emptyStateForPeriod: 'No hay datos para el período seleccionado. Prueba con uno más largo.',partialFailure: 'Algunas secciones no se pudieron cargar. Prueba a actualizar.',@@ -914,6 +917,44 @@ export default {tokenFailed: 'Error al generar el token',toggleFailed: 'Error al activar o desactivar SCIM',},+ permissionGroups: {+ 1: 'Nivel de aplicación',+ 2: 'Proyecto',+ 3: 'Listas',+ 4: 'Tareas',+ },+ oauth: {+ consent: {+ title: 'Conectar {client}',+ subtitle: '{client} solicita acceso a tu cuenta de TaskView.',+ rbacNote: 'El acceso nunca supera tus propios permisos: si no puedes hacer algo en TaskView, la aplicación tampoco.',+ projectsLabel: 'Limitar a proyectos',+ allProjects: 'Todos los proyectos',+ projectsHint: 'Déjalo vacío para permitir todos los proyectos a los que tienes acceso.',+ permissionsLabel: 'Limitar permisos',+ permissionsHint: 'Déjalo vacío para permitir todo lo que tú mismo puedes hacer.',+ projectsWarning: 'Ningún proyecto seleccionado: la aplicación podrá acceder a todos los proyectos a los que tienes acceso.',+ permissionsWarning: 'Ningún permiso seleccionado: la aplicación podrá hacer todo lo que tú mismo puedes hacer.',+ approve: 'Permitir acceso',+ deny: 'Denegar',+ invalidTitle: 'Solicitud de autorización no válida',+ invalidDescription: 'A este enlace le faltan parámetros obligatorios. Inicia la conexión de nuevo desde la aplicación.',+ },+ connectedApps: {+ title: 'Aplicaciones conectadas',+ description: 'Aplicaciones a las que permitiste actuar en tu nombre. Revocar corta su acceso de inmediato.',+ empty: 'No hay aplicaciones conectadas',+ connected: 'Conectada',+ lastUsed: 'Último uso',+ never: 'nunca',+ projectsCount: '{count} proyectos',+ permissionsCount: '{count} permisos',+ allPermissions: 'Todos los permisos',+ allProjects: 'Todos los proyectos',+ revoke: 'Revocar acceso',+ revokeConfirm: '¿Revocar el acceso de {client}? Dejará de funcionar de inmediato.',+ },+ },apiTokens: {title: 'Tokens de API',description: 'Crea tokens para acceder a la API de forma programática.',diff --git a/web/src/locales/pt-br.ts b/web/src/locales/pt-br.tsindex daf6438..63451cb 100644--- a/web/src/locales/pt-br.ts+++ b/web/src/locales/pt-br.ts@@ -669,6 +669,9 @@ export default {page: {title: 'Análises',subtitle: 'Métricas de produtividade e saúde dos projetos',+ destinationLabel: 'Os dados serão enviados para',+ destinationHint: 'Verifique se este endereço pertence ao aplicativo que você está conectando. O nome acima é informado pelo próprio aplicativo e pode ser qualquer um.',+ destinationLocalHint: 'Este endereço está no seu próprio computador, então o aplicativo roda localmente.',emptyState: 'Ainda não há dados. Crie tarefas para visualizar as análises.',emptyStateForPeriod: 'Não há dados para o período selecionado. Tente um período maior.',partialFailure: 'Algumas seções não foram carregadas. Tente atualizar a página.',@@ -925,6 +928,44 @@ export default {tokenFailed: 'Falha ao gerar o token',toggleFailed: 'Falha ao alternar o SCIM',},+ permissionGroups: {+ 1: 'Nível do aplicativo',+ 2: 'Projeto',+ 3: 'Listas',+ 4: 'Tarefas',+ },+ oauth: {+ consent: {+ title: 'Conectar {client}',+ subtitle: '{client} está solicitando acesso à sua conta TaskView.',+ rbacNote: 'O acesso nunca ultrapassa suas próprias permissões — se você não pode fazer algo no TaskView, o aplicativo também não pode.',+ projectsLabel: 'Limitar a projetos',+ allProjects: 'Todos os projetos',+ projectsHint: 'Deixe vazio para permitir todos os projetos a que você tem acesso.',+ permissionsLabel: 'Limitar permissões',+ permissionsHint: 'Deixe vazio para permitir tudo o que você mesmo pode fazer.',+ projectsWarning: 'Nenhum projeto selecionado — o aplicativo poderá acessar todos os projetos a que você tem acesso.',+ permissionsWarning: 'Nenhuma permissão selecionada — o aplicativo poderá fazer tudo o que você mesmo pode fazer.',+ approve: 'Permitir acesso',+ deny: 'Negar',+ invalidTitle: 'Solicitação de autorização inválida',+ invalidDescription: 'Faltam parâmetros obrigatórios neste link. Inicie a conexão novamente pelo aplicativo.',+ },+ connectedApps: {+ title: 'Aplicativos conectados',+ description: 'Aplicativos que você autorizou a agir em seu nome. Revogar encerra o acesso imediatamente.',+ empty: 'Nenhum aplicativo conectado',+ connected: 'Conectado',+ lastUsed: 'Último uso',+ never: 'nunca',+ projectsCount: '{count} projetos',+ permissionsCount: '{count} permissões',+ allPermissions: 'Todas as permissões',+ allProjects: 'Todos os projetos',+ revoke: 'Revogar acesso',+ revokeConfirm: 'Revogar o acesso de {client}? Ele parará de funcionar imediatamente.',+ },+ },apiTokens: {title: 'Tokens de API',description: 'Crie tokens para acessar a API programaticamente.',diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.tsindex 0bd4d76..b4f2939 100644--- a/web/src/locales/ru.ts+++ b/web/src/locales/ru.ts@@ -643,6 +643,9 @@ export default {page: {title: 'Аналитика',subtitle: 'Показатели продуктивности и здоровья проектов',+ destinationLabel: 'Данные будут отправлены на',+ destinationHint: 'Убедитесь, что этот адрес принадлежит подключаемому приложению. Название выше приложение указывает о себе само, и оно может быть любым.',+ destinationLocalHint: 'Адрес указывает на ваш компьютер — значит приложение работает локально.',emptyState: 'Нет данных. Создайте задачи, чтобы увидеть аналитику.',emptyStateForPeriod: 'За выбранный период данных нет. Попробуйте увеличить период.',partialFailure: 'Некоторые секции не удалось загрузить. Попробуйте обновить.',@@ -907,6 +910,44 @@ export default {markAllRead: 'Прочитать все',loadMore: 'Загрузить ещё',},+ permissionGroups: {+ 1: 'Уровень приложения',+ 2: 'Проект',+ 3: 'Списки',+ 4: 'Задачи',+ },+ oauth: {+ consent: {+ title: 'Подключить {client}',+ subtitle: '{client} запрашивает доступ к вашему аккаунту TaskView.',+ rbacNote: 'Доступ никогда не превысит ваши собственные права — если вы чего-то не можете в TaskView, не сможет и приложение.',+ projectsLabel: 'Ограничить проектами',+ allProjects: 'Все проекты',+ projectsHint: 'Оставьте пустым, чтобы разрешить все доступные вам проекты.',+ permissionsLabel: 'Ограничить разрешения',+ permissionsHint: 'Оставьте пустым, чтобы разрешить всё, что можете вы сами.',+ projectsWarning: 'Проект не выбран — приложение получит доступ ко всем вашим проектам.',+ permissionsWarning: 'Разрешения не выбраны — приложение сможет делать всё, что можете вы сами.',+ approve: 'Разрешить доступ',+ deny: 'Отклонить',+ invalidTitle: 'Некорректный запрос авторизации',+ invalidDescription: 'В ссылке не хватает обязательных параметров. Начните подключение заново из приложения.',+ },+ connectedApps: {+ title: 'Подключённые приложения',+ description: 'Приложения, которым вы разрешили действовать от вашего имени. Отзыв мгновенно прекращает их доступ.',+ empty: 'Нет подключённых приложений',+ connected: 'Подключено',+ lastUsed: 'Последнее использование',+ never: 'никогда',+ projectsCount: 'проектов: {count}',+ permissionsCount: 'разрешений: {count}',+ allPermissions: 'Все разрешения',+ allProjects: 'Все проекты',+ revoke: 'Отозвать доступ',+ revokeConfirm: 'Отозвать доступ для {client}? Приложение сразу перестанет работать.',+ },+ },sessions: {title: 'Активные сессии',description: 'Управляйте активными сессиями. Вы можете завершить любую сессию кроме текущей.',diff --git a/web/src/middleware/authenticated-with-return.ts b/web/src/middleware/authenticated-with-return.tsnew file mode 100644index 0000000..b509fce--- /dev/null+++ b/web/src/middleware/authenticated-with-return.ts@@ -0,0 +1,16 @@+import type { RouteLocationNormalized } from 'vue-router'+import { $ls } from '@/plugins/axios'++/**+ * Like `authenticated`, but remembers where the user was going. The OAuth+ * consent screen is usually the first TaskView page a connector opens, so an+ * unauthenticated user must come back to it — with its query intact — instead+ * of landing on their project list with the authorization request lost.+ */+export default async function authenticatedWithReturn(to: RouteLocationNormalized) {+ await $ls.updateUserStoreByToken()+ if (!(await $ls.getToken())) {+ return { name: 'login', query: { redirect: to.fullPath } }+ }+ return true+}diff --git a/web/src/pages/oauth-consent.vue b/web/src/pages/oauth-consent.vuenew file mode 100644index 0000000..5d959a7--- /dev/null+++ b/web/src/pages/oauth-consent.vue@@ -0,0 +1,87 @@+<template>+ <div class="min-h-screen flex items-center justify-center p-4 bg-elevated/40">+ <div+ v-if="paramError"+ class="w-full max-w-lg"+ >+ <UAlert+ icon="i-lucide-triangle-alert"+ color="error"+ variant="soft"+ :title="t('oauth.consent.invalidTitle')"+ :description="t('oauth.consent.invalidDescription')"+ />+ </div>++ <OAuthConsentCard+ v-else+ :client-name="clientName"+ :redirect-uri="request.redirect_uri"+ @approve="onApprove"+ @deny="onDeny"+ />+ </div>+</template>++<script setup lang="ts">+import { computed, onMounted, ref } from 'vue'+import { useRoute } from 'vue-router'+import { useI18n } from 'vue-i18n'+import type { OAuthConsentRequest } from 'taskview-api'+import { useOAuthStore } from '@/stores/oauth.store'+import { useGoalsStore } from '@/stores/goals.store'+import { useOrganizationStore } from '@/stores/organization.store'+import OAuthConsentCard from '@/components/features/oauth/OAuthConsentCard.vue'+import type { OAuthConsentSelection } from '@/types/oauth.types'++const { t } = useI18n()+const route = useRoute()+const store = useOAuthStore()+const goalsStore = useGoalsStore()+const orgStore = useOrganizationStore()++const readParam = (key: string): string => {+ const value = route.query[key]+ return Array.isArray(value) ? (value[0] ?? '') : (value ?? '')+}++const clientName = computed(() => readParam('client_name') || readParam('client_id'))+const request = computed<OAuthConsentRequest>(() => ({+ client_id: readParam('client_id'),+ redirect_uri: readParam('redirect_uri'),+ code_challenge: readParam('code_challenge'),+ code_challenge_method: 'S256',+ state: readParam('state') || undefined,+ resource: readParam('resource') || undefined,+}))++const paramError = computed(() =>+ !request.value.client_id+ || !request.value.redirect_uri+ || !request.value.code_challenge+ || readParam('code_challenge_method') !== 'S256',+)++const leaving = ref(false)++const leaveTo = (url: string | null) => {+ if (!url) return+ leaving.value = true+ window.location.replace(url)+}++const onApprove = async (selection: OAuthConsentSelection) => {+ leaveTo(await store.approveConsent({ ...request.value, ...selection }))+}++const onDeny = async () => {+ leaveTo(await store.denyConsent(request.value))+}++onMounted(async () => {+ if (paramError.value) return+ if (!orgStore.organizations.length) await orgStore.fetchOrganizations()+ if (!orgStore.currentOrg) orgStore.restoreCurrentOrg()+ await goalsStore.fetchGoals()+})+</script>diff --git a/web/src/stores/oauth.store.ts b/web/src/stores/oauth.store.tsnew file mode 100644index 0000000..1341c41--- /dev/null+++ b/web/src/stores/oauth.store.ts@@ -0,0 +1,48 @@+import { defineStore } from 'pinia'+import type { OAuthConnectedApp, OAuthConsentRequest } from 'taskview-api'+import { $tvApi } from '@/plugins/axios'++interface OAuthStoreState {+ connectedApps: OAuthConnectedApp[]+ loading: boolean+ submitting: boolean+}++export const useOAuthStore = defineStore('oauth', {+ state: (): OAuthStoreState => ({+ connectedApps: [],+ loading: false,+ submitting: false,+ }),+ actions: {+ async fetchConnectedApps(): Promise<void> {+ this.loading = true+ const result = await $tvApi.oauth.fetchConnectedApps()+ this.connectedApps = result || []+ this.loading = false+ },++ async revokeConnectedApp(grantId: number): Promise<void> {+ const result = await $tvApi.oauth.revokeConnectedApp(grantId)+ if (!result) return+ const index = this.connectedApps.findIndex((app) => app.grantId === grantId)+ if (index !== -1) {+ this.connectedApps.splice(index, 1)+ }+ },++ async approveConsent(data: OAuthConsentRequest): Promise<string | null> {+ this.submitting = true+ const result = await $tvApi.oauth.approveConsent(data)+ this.submitting = false+ return result?.redirectUrl ?? null+ },++ async denyConsent(data: OAuthConsentRequest): Promise<string | null> {+ this.submitting = true+ const result = await $tvApi.oauth.denyConsent(data)+ this.submitting = false+ return result?.redirectUrl ?? null+ },+ },+})diff --git a/web/src/types/oauth.types.ts b/web/src/types/oauth.types.tsnew file mode 100644index 0000000..3af41c6--- /dev/null+++ b/web/src/types/oauth.types.ts@@ -0,0 +1,4 @@+export type OAuthConsentSelection = {+ allowedGoalIds: number[]+ allowedPermissions: string[]+}