Skip to content

TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.

feat: mcp & sso

Nikolai Gimanaf63530390c0
diff --git a/api/package.json b/api/package.json
index 9468683..3b79ebc 100644
--- a/api/package.json
+++ b/api/package.json
@@ -42,12 +42,14 @@
"typescript": "^5.0.0"
},
"dependencies": {
+ "@node-saml/node-saml": "^5.1.0",
"@types/bcryptjs": "^2.4.6",
"@types/passport": "^1.0.17",
"@types/passport-github2": "^1.2.9",
"@types/passport-google-oauth20": "^2.0.17",
"@vitejs/plugin-legacy": "^5.4.2",
"@vitejs/plugin-vue": "^5.1.4",
+ "@xmldom/xmldom": "^0.9.9",
"axios": "1.13.5",
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.7",
@@ -59,6 +61,7 @@
"firebase-admin": "^12.7.0",
"helmet": "^7.1.0",
"jsonwebtoken": "^9.0.2",
+ "openid-client": "^6.8.2",
"passport": "^0.7.0",
"passport-apple": "^2.0.2",
"passport-github2": "^0.1.12",
diff --git a/api/src/App.ts b/api/src/App.ts
index cdc2c2c..91c0232 100644
--- a/api/src/App.ts
+++ b/api/src/App.ts
@@ -58,7 +58,7 @@ export default class App {
this.app.use(cors({
credentials: true,
origin(origin, cb) {
- if (!origin) return cb(null, true);
+ if (!origin || origin === 'null') return cb(null, true);
if (allow.has(origin)) return cb(null, true);
return cb(new Error(`CORS blocked origin: ${origin}`), false);
},
diff --git a/api/src/core/AppUser.ts b/api/src/core/AppUser.ts
index 3ace75d..8a31098 100644
--- a/api/src/core/AppUser.ts
+++ b/api/src/core/AppUser.ts
@@ -10,6 +10,7 @@ import { TagsManager } from '../tv-modules/tags/TagsManager';
import { IntegrationsManager } from '../tv-modules/integrations/IntegrationsManager';
import { NotificationsManager } from '../tv-modules/notifications/NotificationsManager';
import { OrganizationManager } from '../tv-modules/organizations/OrganizationManager';
+import { SsoManager } from '../tv-modules/sso/SsoManager';
import { TasksManager } from '../tv-modules/tasks/TasksManager';
import type { UserDbRecord, UserJwtPayload } from '../types/auth.types';
import { GoalPermissionsFetcher } from './GoalPermissionsFetcher';
@@ -35,6 +36,7 @@ export class AppUser {
public readonly integrationsManager: IntegrationsManager;
public readonly notificationsManager: NotificationsManager;
public readonly organizationManager: OrganizationManager;
+ public readonly ssoManager: SsoManager;
constructor(userData?: UserJwtPayload) {
this.userData = userData;
@@ -52,6 +54,7 @@ export class AppUser {
this.integrationsManager = new IntegrationsManager(this);
this.notificationsManager = new NotificationsManager(this);
this.organizationManager = new OrganizationManager(this);
+ this.ssoManager = new SsoManager(this);
}
getTokenId(): number | undefined {
diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.json
index 61f7ef7..3ad2e1d 100644
--- a/api/src/migrations/taskview/migrate.json
+++ b/api/src/migrations/taskview/migrate.json
@@ -443,5 +443,21 @@
"Migrate existing users to personal workspaces",
"Added organization_id column to goals"
]
+ },
+ "36": {
+ "version": "1.33.0",
+ "name": "Release 1.33.0",
+ "releaseDate": "20260411",
+ "scripts": [
+ "/1.33.0/0.1.33.0.sql",
+ "/1.33.0/1.add-saml-signing-fields.sql",
+ "/1.33.0/2.add-saml-logout-url.sql"
+ ],
+ "description": [
+ "Added SSO support (SAML 2.0 + OIDC)",
+ "Added sso_configs, sso_identities, saml_request_cache tables",
+ "Added SAML AuthnRequest signing support",
+ "Added SAML logout URL for SLO"
+ ]
}
}
\ No newline at end of file
diff --git a/api/src/migrations/taskview/sql/1.33.0/0.1.33.0.sql b/api/src/migrations/taskview/sql/1.33.0/0.1.33.0.sql
new file mode 100644
index 0000000..7ad7db1
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.33.0/0.1.33.0.sql
@@ -0,0 +1,45 @@
+CREATE TABLE IF NOT EXISTS tv_auth.sso_configs (
+ id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
+ organization_id INTEGER NOT NULL REFERENCES tv_auth.organizations(id) ON DELETE CASCADE,
+ protocol VARCHAR NOT NULL,
+ display_name VARCHAR NOT NULL,
+ enabled INTEGER NOT NULL DEFAULT 1,
+
+ saml_entry_point VARCHAR,
+ saml_issuer VARCHAR,
+ saml_cert TEXT,
+ saml_callback_url VARCHAR,
+
+ oidc_issuer VARCHAR,
+ oidc_client_id VARCHAR,
+ oidc_client_secret VARCHAR,
+ oidc_callback_url VARCHAR,
+ oidc_scope VARCHAR,
+
+ default_org_role VARCHAR NOT NULL DEFAULT 'member',
+ email_domain_restriction VARCHAR NOT NULL,
+
+ created_at TIMESTAMP DEFAULT NOW(),
+ updated_at TIMESTAMP DEFAULT NOW(),
+ UNIQUE(email_domain_restriction)
+);
+
+CREATE TABLE IF NOT EXISTS tv_auth.sso_identities (
+ id INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
+ user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,
+ sso_config_id INTEGER NOT NULL REFERENCES tv_auth.sso_configs(id) ON DELETE CASCADE,
+ external_id VARCHAR NOT NULL,
+ email VARCHAR NOT NULL,
+ last_login_at TIMESTAMP,
+ created_at TIMESTAMP DEFAULT NOW(),
+ UNIQUE(sso_config_id, external_id)
+);
+
+CREATE INDEX IF NOT EXISTS idx_sso_identities_user_id ON tv_auth.sso_identities(user_id);
+CREATE INDEX IF NOT EXISTS idx_sso_identities_email ON tv_auth.sso_identities(email);
+
+CREATE TABLE IF NOT EXISTS tv_auth.saml_request_cache (
+ key VARCHAR PRIMARY KEY,
+ value VARCHAR NOT NULL,
+ created_at BIGINT NOT NULL
+);
diff --git a/api/src/migrations/taskview/sql/1.33.0/1.add-saml-signing-fields.sql b/api/src/migrations/taskview/sql/1.33.0/1.add-saml-signing-fields.sql
new file mode 100644
index 0000000..fcf9824
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.33.0/1.add-saml-signing-fields.sql
@@ -0,0 +1,2 @@
+ALTER TABLE tv_auth.sso_configs ADD COLUMN IF NOT EXISTS saml_signing_key TEXT;
+ALTER TABLE tv_auth.sso_configs ADD COLUMN IF NOT EXISTS saml_signing_cert TEXT;
diff --git a/api/src/migrations/taskview/sql/1.33.0/2.add-saml-logout-url.sql b/api/src/migrations/taskview/sql/1.33.0/2.add-saml-logout-url.sql
new file mode 100644
index 0000000..c36d114
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.33.0/2.add-saml-logout-url.sql
@@ -0,0 +1 @@
+ALTER TABLE tv_auth.sso_configs ADD COLUMN IF NOT EXISTS saml_logout_url VARCHAR;
diff --git a/api/src/routes/index.ts b/api/src/routes/index.ts
index c536b54..98464cb 100644
--- a/api/src/routes/index.ts
+++ b/api/src/routes/index.ts
@@ -14,6 +14,7 @@ import StartRoutes from '../tv-modules/start/StartRoutes';
import TagsRouter from '../tv-modules/tags/TagsRouter';
import TasksRoutes from '../tv-modules/tasks/TasksRoutes';
import OrganizationRoutes from '../tv-modules/organizations/OrganizationRoutes';
+import SsoRoutes from '../tv-modules/sso/SsoRoutes';
import type { Routable } from '../types/routable.type';
type RoutableConstructor = new (...args: any[]) => Routable;
@@ -35,6 +36,7 @@ const routes: Record<string, RoutableConstructor> = {
'/module/api-tokens': ApiTokensRoutes,
'/module/sessions': SessionsRoutes,
'/module/organizations': OrganizationRoutes,
+ '/module/sso': SsoRoutes,
};
export default routes;
diff --git a/api/src/tv-modules/notifications/NotificationDispatcher.ts b/api/src/tv-modules/notifications/NotificationDispatcher.ts
index 31e9fb5..f362a66 100644
--- a/api/src/tv-modules/notifications/NotificationDispatcher.ts
+++ b/api/src/tv-modules/notifications/NotificationDispatcher.ts
@@ -1,6 +1,6 @@
import { eq, and, or, isNull, inArray } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
-import { TasksSchema, CollaborationUsersSchema, UsersSchema } from 'taskview-db-schemas';
+import { TasksSchema, CollaborationUsersSchema, UsersSchema, GoalsSchema } from 'taskview-db-schemas';
import { eventBus, type AppEvents } from '../../core/EventBus';
import { getJobQueue } from '../../core/JobQueue';
import { Database } from '../../modules/db';
@@ -108,6 +108,7 @@ export class NotificationDispatcher implements Dispatcher {
): Promise<void> {
const initiatorName = await this.resolveUserName(data.initiatorId);
const message = NotificationMessages.assign(task.description, initiatorName);
+ const organizationId = await this.resolveOrganizationId(task.goalId);
$logger.info(`[NotificationDispatcher] Assign notification for task=${data.taskId}, recipients=[${recipientIds.join(',')}]`);
@@ -115,7 +116,7 @@ export class NotificationDispatcher implements Dispatcher {
recipientIds,
NotificationType.ASSIGN,
message,
- { goalId: task.goalId, goalListId: task.goalListId },
+ { goalId: task.goalId, goalListId: task.goalListId, organizationId },
data.taskId,
);
}
@@ -135,6 +136,7 @@ export class NotificationDispatcher implements Dispatcher {
const tz = task.owner ? await this.deviceTokensRepo.getTimezoneByUserId(task.owner) : 'UTC';
const message = NotificationMessages.deadline(task.description, task.endDate, task.endTime, tz);
+ const organizationId = await this.resolveOrganizationId(task.goalId);
$logger.info(`[NotificationDispatcher] Expired deadline notification for task=${data.taskId}, recipients=[${recipientIds.join(',')}]`);
@@ -142,7 +144,7 @@ export class NotificationDispatcher implements Dispatcher {
recipientIds,
NotificationType.DEADLINE,
message,
- { goalId: task.goalId, goalListId: task.goalListId },
+ { goalId: task.goalId, goalListId: task.goalListId, organizationId },
data.taskId,
);
}
@@ -152,6 +154,16 @@ export class NotificationDispatcher implements Dispatcher {
await this.deadlineScheduler.cancel(data.taskId);
}
+ private async resolveOrganizationId(goalId: number): Promise<number | null> {
+ const db = Database.getInstance();
+ const result = await db.dbDrizzle
+ .select({ organizationId: GoalsSchema.organizationId })
+ .from(GoalsSchema)
+ .where(eq(GoalsSchema.id, goalId))
+ .limit(1);
+ return result[0]?.organizationId ?? null;
+ }
+
private async resolveUserName(userId: number): Promise<string> {
const db = Database.getInstance();
const result = await db.dbDrizzle
diff --git a/api/src/tv-modules/notifications/NotificationProvider.ts b/api/src/tv-modules/notifications/NotificationProvider.ts
index a991105..7437fda 100644
--- a/api/src/tv-modules/notifications/NotificationProvider.ts
+++ b/api/src/tv-modules/notifications/NotificationProvider.ts
@@ -4,6 +4,7 @@ import type { NotificationChannel } from './types';
export interface NotificationMeta {
goalId: number;
goalListId: number | null;
+ organizationId: number | null;
}
export interface NotificationProvider {
diff --git a/api/src/tv-modules/notifications/providers/CentrifugoProvider.ts b/api/src/tv-modules/notifications/providers/CentrifugoProvider.ts
index 528d9c4..1c106ab 100644
--- a/api/src/tv-modules/notifications/providers/CentrifugoProvider.ts
+++ b/api/src/tv-modules/notifications/providers/CentrifugoProvider.ts
@@ -11,6 +11,7 @@ export class CentrifugoProvider implements NotificationProvider {
notification,
goalId: meta.goalId,
goalListId: meta.goalListId,
+ organizationId: meta.organizationId,
});
}
}
diff --git a/api/src/tv-modules/notifications/providers/FCMProvider.ts b/api/src/tv-modules/notifications/providers/FCMProvider.ts
index 2395c66..c4971d5 100644
--- a/api/src/tv-modules/notifications/providers/FCMProvider.ts
+++ b/api/src/tv-modules/notifications/providers/FCMProvider.ts
@@ -61,6 +61,7 @@ export class FCMProvider implements NotificationProvider {
taskId: notification.taskId ? String(notification.taskId) : '',
goalId: String(meta.goalId),
goalListId: meta.goalListId ? String(meta.goalListId) : '',
+ organizationId: meta.organizationId ? String(meta.organizationId) : '',
notificationId: String(notification.id),
},
android: {
diff --git a/api/src/tv-modules/notifications/schedulers/DeadlineScheduler.ts b/api/src/tv-modules/notifications/schedulers/DeadlineScheduler.ts
index e82bf8b..2d37b1a 100644
--- a/api/src/tv-modules/notifications/schedulers/DeadlineScheduler.ts
+++ b/api/src/tv-modules/notifications/schedulers/DeadlineScheduler.ts
@@ -33,11 +33,14 @@ export class DeadlineScheduler {
startAfter = deadlineDay > new Date() ? deadlineDay : undefined;
}
+ const organizationId = await this.resolveOrganizationId(Database.getInstance(), task.goalId);
+
const data: DeadlineJobData = {
taskId: task.id,
description: task.description ?? '',
goalId: task.goalId,
goalListId: task.goalListId,
+ organizationId,
endDate: task.endDate,
endTime: task.endTime,
initiatorId: initiatorId ?? null,
@@ -63,7 +66,7 @@ export class DeadlineScheduler {
await boss.createQueue(DEADLINE_JOB);
await boss.work<DeadlineJobData>(DEADLINE_JOB, async ([job]) => {
- const { taskId, description, goalId, goalListId, endDate, endTime, initiatorId, immediate } = job.data;
+ const { taskId, description, goalId, goalListId, organizationId, endDate, endTime, initiatorId, immediate } = job.data;
if (!taskId) return;
$logger.info(`[DeadlineScheduler] Worker: job=${job.id} task=${taskId}`);
@@ -105,7 +108,7 @@ export class DeadlineScheduler {
recipientIds,
NotificationType.DEADLINE,
message,
- { goalId, goalListId },
+ { goalId, goalListId, organizationId: organizationId ?? null },
taskId,
);
});
@@ -115,6 +118,15 @@ export class DeadlineScheduler {
return `deadline-${taskId}`;
}
+ private async resolveOrganizationId(db: Database, goalId: number): Promise<number | null> {
+ const result = await db.dbDrizzle
+ .select({ organizationId: GoalsSchema.organizationId })
+ .from(GoalsSchema)
+ .where(eq(GoalsSchema.id, goalId))
+ .limit(1);
+ return result[0]?.organizationId ?? null;
+ }
+
private async resolveRecipients(db: Database, taskId: number, goalId: number, taskOwner: number | null): Promise<number[] | null> {
const authUsers = alias(UsersSchema, 'auth_users');
diff --git a/api/src/tv-modules/notifications/types.ts b/api/src/tv-modules/notifications/types.ts
index 6b61a0d..54cede3 100644
--- a/api/src/tv-modules/notifications/types.ts
+++ b/api/src/tv-modules/notifications/types.ts
@@ -106,6 +106,7 @@ export interface DeadlineJobData {
description: string;
goalId: number;
goalListId: number | null;
+ organizationId: number | null;
endDate: string;
endTime: string | null;
initiatorId: number | null;
diff --git a/api/src/tv-modules/organizations/OrganizationManager.ts b/api/src/tv-modules/organizations/OrganizationManager.ts
index 4a27b3b..61f65c6 100644
--- a/api/src/tv-modules/organizations/OrganizationManager.ts
+++ b/api/src/tv-modules/organizations/OrganizationManager.ts
@@ -35,7 +35,7 @@ export class OrganizationManager {
if (!org) return false
await this.repository.addMember(org.id, email, 'owner')
- return org
+ return { ...org, currentUserRole: 'owner' }
}
async update(data: OrganizationArgUpdate) {
diff --git a/api/src/tv-modules/organizations/OrganizationRepository.ts b/api/src/tv-modules/organizations/OrganizationRepository.ts
index 86ee8f2..8633cc1 100644
--- a/api/src/tv-modules/organizations/OrganizationRepository.ts
+++ b/api/src/tv-modules/organizations/OrganizationRepository.ts
@@ -106,17 +106,23 @@ export class OrganizationRepository {
return result[0]
}
- async fetchForUserByEmail(email: string): Promise<OrganizationsSchemaTypeForSelect[]> {
+ async fetchForUserByEmail(email: string) {
const result = await callWithCatch(() =>
this.db.dbDrizzle
- .select({ org: OrganizationsSchema })
+ .select({
+ org: OrganizationsSchema,
+ role: OrganizationMembersSchema.role,
+ })
.from(OrganizationMembersSchema)
.innerJoin(OrganizationsSchema, eq(OrganizationMembersSchema.organizationId, OrganizationsSchema.id))
.where(eq(OrganizationMembersSchema.email, email))
)
if (!result) return []
- return result.map(r => r.org)
+ return result.map(r => ({
+ ...r.org,
+ currentUserRole: r.role,
+ }))
}
async addMember(orgId: number, email: string, role: string, invitedBy?: number): Promise<OrganizationMembersSchemaTypeForSelect | false> {
diff --git a/api/src/tv-modules/organizations/OrganizationRoutes.ts b/api/src/tv-modules/organizations/OrganizationRoutes.ts
index 31ae661..c1888f1 100644
--- a/api/src/tv-modules/organizations/OrganizationRoutes.ts
+++ b/api/src/tv-modules/organizations/OrganizationRoutes.ts
@@ -27,7 +27,7 @@ export default class OrganizationRoutes implements Routable {
this.router.patch('', [IsLoggedIn, IsOrgAdmin], this.controller.update)
this.router.delete('', [IsLoggedIn, IsOrgOwner], this.controller.delete)
- this.router.get('/:orgId/members', [IsLoggedIn, IsOrgMember], this.controller.fetchMembers)
+ this.router.get('/:orgId/members', [IsLoggedIn, IsOrgAdmin], this.controller.fetchMembers)
this.router.post('/members', [IsLoggedIn, IsOrgAdmin], this.controller.addMember)
this.router.patch('/members/role', [IsLoggedIn, IsOrgAdmin], this.controller.updateMemberRole)
this.router.delete('/members', [IsLoggedIn, IsOrgAdmin], this.controller.removeMember)
diff --git a/api/src/tv-modules/sso/SsoController.ts b/api/src/tv-modules/sso/SsoController.ts
new file mode 100644
index 0000000..9ffc2a8
--- /dev/null
+++ b/api/src/tv-modules/sso/SsoController.ts
@@ -0,0 +1,205 @@
+import { type } from 'arktype'
+import { hashSync } from 'bcryptjs'
+import type { Request, Response } from 'express'
+import { $logger } from '../../modules/logget'
+import { logError } from '../../utils/api'
+import { isEmail } from '../../utils/helpers'
+import AuthModel from '../auth/AuthModel'
+import { OrganizationRepository } from '../organizations/OrganizationRepository'
+import { createSsoProvider } from './providers/provider-factory'
+import { SsoRepository } from './SsoRepository'
+import { parseSamlMetadata } from './saml-metadata-parser'
+import { SsoConfigArkTypeCreate, SsoConfigArkTypeUpdate } from './types'
+
+function generateRandomString(length: number): string {
+ let result = ''
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
+ for (let i = 0; i < length; i++) {
+ result += chars.charAt(Math.floor(Math.random() * chars.length))
+ }
+ return result
+}
+
+function generateLoginCode(): string {
+ return `${generateRandomString(12)}:${Date.now()}`.toLowerCase()
+}
+
+export class SsoController {
+ private readonly ssoRepo = new SsoRepository()
+ private readonly authModel = new AuthModel()
+ private readonly orgRepo = new OrganizationRepository()
+
+ initiateLogin = async (req: Request, res: Response) => {
+ const configId = Number(req.params.configId)
+ if (!configId) return res.status(400).tvJson({ message: 'Invalid config ID' })
+
+ const config = await this.ssoRepo.findEnabledById(configId)
+ if (!config) return res.status(404).tvJson({ message: 'SSO provider not found' })
+
+ try {
+ const provider = createSsoProvider(config)
+ const relayState = JSON.stringify({ platform: req.query.platform || '' })
+ await provider.initiateLogin(req, res, relayState)
+ } catch (error) {
+ $logger.error(error, `SSO initiate login error for config ${configId}`)
+ return res.status(500).tvJson({ message: 'Failed to initiate SSO login' })
+ }
+ }
+
+ handleCallback = async (req: Request, res: Response) => {
+ const configId = Number(req.params.configId)
+ if (!configId) return res.status(400).tvJson({ message: 'Invalid config ID' })
+
+ const config = await this.ssoRepo.findEnabledById(configId)
+ if (!config) return res.status(404).tvJson({ message: 'SSO provider not found' })
+
+ try {
+ const provider = createSsoProvider(config)
+ const ssoResult = await provider.handleCallback(req)
+
+ if (config.emailDomainRestriction) {
+ const domain = ssoResult.email.split('@')[1]
+ if (domain !== config.emailDomainRestriction) {
+ return res.status(403).tvJson({ message: 'Email domain not allowed for this SSO provider' })
+ }
+ }
+
+ let userData = await this.authModel.getUserByLogin(ssoResult.email, isEmail(ssoResult.email))
+
+ if (!userData) {
+ const password = generateRandomString(16)
+ const login = generateRandomString(7)
+ const id = await this.authModel.registerUserInDb({
+ login,
+ email: ssoResult.email,
+ password: hashSync(password, 10),
+ block: 0,
+ confirmEmailCode: '',
+ })
+
+ if (!id) {
+ $logger.error('Failed to create user during SSO login')
+ return res.status(500).tvJson({ message: 'Failed to create user' })
+ }
+
+ const personalOrgSlug = `org-${crypto.randomUUID().slice(0, 8)}`
+ const personalOrg = await this.orgRepo.create({ name: `${login}'s workspace`, slug: personalOrgSlug }, id, true)
+ if (personalOrg) {
+ await this.orgRepo.addMember(personalOrg.id, ssoResult.email, 'owner')
+ }
+
+ userData = await this.authModel.getUserByLogin(ssoResult.email, isEmail(ssoResult.email))
+ }
+
+ if (!userData) {
+ return res.status(500).tvJson({ message: 'Failed to resolve user after SSO login' })
+ }
+
+ await this.orgRepo.addMember(config.organizationId, ssoResult.email, config.defaultOrgRole)
+
+ await this.ssoRepo.upsertIdentity({
+ userId: userData.id,
+ ssoConfigId: config.id,
+ externalId: ssoResult.externalId,
+ email: ssoResult.email,
+ })
+
+ const code = generateLoginCode()
+ await this.authModel.updateLoginCode(code, userData.email)
+
+ const authData = {
+ code: code.split(':')[0],
+ email: userData.email,
+ }
+ const encodedAuthData = encodeURIComponent(JSON.stringify(authData))
+
+ try {
+ const relayState = req.body?.RelayState || req.query?.state
+ if (relayState) {
+ const platformData = JSON.parse(relayState as string)
+ if (platformData.platform === 'mobile') {
+ return res.redirect(`taskview://login?tokens=${encodedAuthData}`)
+ }
+ }
+ } catch { /* relay state parse error — ignore, use web redirect */ }
+
+ return res.redirect(`${process.env.APP_URL}/login?tokens=${encodedAuthData}`)
+ } catch (error) {
+ $logger.error(error, `SSO callback error for config ${configId}`)
+ return res.redirect(`${process.env.APP_URL}/login?sso_error=authentication_failed`)
+ }
+ }
+
+ listPublicProviders = async (req: Request, res: Response) => {
+ const domain = req.query.domain as string
+ if (!domain) return res.tvJson(null)
+
+ const config = await this.ssoRepo.findEnabledByDomain(domain)
+ if (!config) return res.tvJson(null)
+
+ return res.tvJson({
+ id: config.id,
+ displayName: config.displayName,
+ protocol: config.protocol,
+ })
+ }
+
+ listConfigs = async (req: Request, res: Response) => {
+ const orgId = Number(req.query.organizationId)
+ if (!orgId) return res.status(400).tvJson({ message: 'organizationId is required' })
+
+ const configs = await this.ssoRepo.listByOrgId(orgId)
+ return res.tvJson(configs)
+ }
+
+ createConfig = async (req: Request, res: Response) => {
+ const out = SsoConfigArkTypeCreate(req.body)
+ if (out instanceof type.errors) {
+ return res.status(400).send(out.summary)
+ }
+
+ const config = await req.appUser.ssoManager.createConfig(out).catch(logError)
+ return res.tvJson(config ?? null)
+ }
+
+ updateConfig = async (req: Request, res: Response) => {
+ const configId = Number(req.params.configId)
+ if (!configId) return res.status(400).end()
+
+ const out = SsoConfigArkTypeUpdate(req.body)
+ if (out instanceof type.errors) {
+ return res.status(400).send(out.summary)
+ }
+
+ const config = await req.appUser.ssoManager.updateConfig(configId, out).catch(logError)
+ return res.tvJson(config ?? null)
+ }
+
+ parseMetadata = async (req: Request, res: Response) => {
+ const metadataUrl = req.query.url as string
+ if (!metadataUrl) return res.status(400).tvJson({ message: 'url is required' })
+
+ try {
+ const response = await fetch(metadataUrl)
+ if (!response.ok) {
+ return res.status(400).tvJson({ message: `Failed to fetch metadata: ${response.status}` })
+ }
+
+ const xml = await response.text()
+ const parsed = parseSamlMetadata(xml)
+
+ return res.tvJson(parsed)
+ } catch (error) {
+ $logger.error(error, 'Failed to parse SAML metadata')
+ return res.status(400).tvJson({ message: 'Failed to fetch or parse metadata' })
+ }
+ }
+
+ deleteConfig = async (req: Request, res: Response) => {
+ const configId = Number(req.params.configId)
+ if (!configId) return res.status(400).end()
+
+ const result = await req.appUser.ssoManager.deleteConfig(configId).catch(logError)
+ return res.tvJson(!!result)
+ }
+}
diff --git a/api/src/tv-modules/sso/SsoManager.ts b/api/src/tv-modules/sso/SsoManager.ts
new file mode 100644
index 0000000..1d8ead9
--- /dev/null
+++ b/api/src/tv-modules/sso/SsoManager.ts
@@ -0,0 +1,48 @@
+import type { AppUser } from '../../core/AppUser'
+import { SsoRepository } from './SsoRepository'
+import type { SsoConfigArgCreate, SsoConfigArgUpdate } from './types'
+
+export class SsoManager {
+ public readonly repository: SsoRepository
+ private readonly user: AppUser
+
+ constructor(user: AppUser) {
+ this.user = user
+ this.repository = new SsoRepository()
+ }
+
+ async listConfigsForOrg(orgId: number) {
+ return await this.repository.listByOrgId(orgId)
+ }
+
+ async createConfig(data: SsoConfigArgCreate) {
+ return await this.repository.create({
+ organizationId: data.organizationId,
+ protocol: data.protocol,
+ displayName: data.displayName,
+ enabled: data.enabled ?? 1,
+ samlEntryPoint: data.samlEntryPoint ?? null,
+ samlIssuer: data.samlIssuer ?? null,
+ samlCert: data.samlCert ?? null,
+ samlCallbackUrl: data.samlCallbackUrl ?? null,
+ samlSigningKey: data.samlSigningKey ?? null,
+ samlSigningCert: data.samlSigningCert ?? null,
+ samlLogoutUrl: data.samlLogoutUrl ?? null,
+ oidcIssuer: data.oidcIssuer ?? null,
+ oidcClientId: data.oidcClientId ?? null,
+ oidcClientSecret: data.oidcClientSecret ?? null,
+ oidcCallbackUrl: data.oidcCallbackUrl ?? null,
+ oidcScope: data.oidcScope ?? null,
+ defaultOrgRole: data.defaultOrgRole ?? 'member',
+ emailDomainRestriction: data.emailDomainRestriction.toLowerCase(),
+ })
+ }
+
+ async updateConfig(configId: number, data: SsoConfigArgUpdate) {
+ return await this.repository.update(configId, data)
+ }
+
+ async deleteConfig(configId: number) {
+ return await this.repository.delete(configId)
+ }
+}
diff --git a/api/src/tv-modules/sso/SsoRepository.ts b/api/src/tv-modules/sso/SsoRepository.ts
new file mode 100644
index 0000000..1ff1133
--- /dev/null
+++ b/api/src/tv-modules/sso/SsoRepository.ts
@@ -0,0 +1,167 @@
+import { and, eq } from 'drizzle-orm'
+import {
+ SsoConfigsSchema,
+ SsoIdentitiesSchema,
+ type SsoConfigsSchemaTypeForSelect,
+ type SsoConfigsSchemaTypeForInsert,
+ type SsoIdentitiesSchemaTypeForSelect,
+} from 'taskview-db-schemas'
+import { Database } from '../../modules/db'
+import { callWithCatch } from '../../utils/helpers'
+
+export class SsoRepository {
+ private readonly db: Database
+
+ constructor() {
+ this.db = Database.getInstance()
+ }
+
+ async findEnabledByDomain(domain: string): Promise<SsoConfigsSchemaTypeForSelect | null> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(SsoConfigsSchema)
+ .where(
+ and(
+ eq(SsoConfigsSchema.emailDomainRestriction, domain.toLowerCase()),
+ eq(SsoConfigsSchema.enabled, 1),
+ )
+ )
+ )
+ if (!result || result.length === 0) return null
+ return result[0]
+ }
+
+ async findEnabledById(id: number): Promise<SsoConfigsSchemaTypeForSelect | null> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(SsoConfigsSchema)
+ .where(
+ and(
+ eq(SsoConfigsSchema.id, id),
+ eq(SsoConfigsSchema.enabled, 1),
+ )
+ )
+ )
+ if (!result || result.length === 0) return null
+ return result[0]
+ }
+
+ async listEnabledByOrgId(orgId: number): Promise<SsoConfigsSchemaTypeForSelect[]> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(SsoConfigsSchema)
+ .where(
+ and(
+ eq(SsoConfigsSchema.organizationId, orgId),
+ eq(SsoConfigsSchema.enabled, 1),
+ )
+ )
+ )
+ return result ?? []
+ }
+
+ async listByOrgId(orgId: number): Promise<SsoConfigsSchemaTypeForSelect[]> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(SsoConfigsSchema)
+ .where(eq(SsoConfigsSchema.organizationId, orgId))
+ )
+ return result ?? []
+ }
+
+ async findById(id: number): Promise<SsoConfigsSchemaTypeForSelect | null> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(SsoConfigsSchema)
+ .where(eq(SsoConfigsSchema.id, id))
+ )
+ if (!result || result.length === 0) return null
+ return result[0]
+ }
+
+ async create(data: SsoConfigsSchemaTypeForInsert): Promise<SsoConfigsSchemaTypeForSelect | null> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .insert(SsoConfigsSchema)
+ .values(data)
+ .returning()
+ )
+ if (!result || result.length === 0) return null
+ return result[0]
+ }
+
+ async update(id: number, data: Partial<SsoConfigsSchemaTypeForInsert>): Promise<SsoConfigsSchemaTypeForSelect | null> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .update(SsoConfigsSchema)
+ .set({ ...data, updatedAt: new Date() })
+ .where(eq(SsoConfigsSchema.id, id))
+ .returning()
+ )
+ if (!result || result.length === 0) return null
+ return result[0]
+ }
+
+ async delete(id: number): Promise<boolean> {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .delete(SsoConfigsSchema)
+ .where(eq(SsoConfigsSchema.id, id))
+ )
+ return !!(result?.rowCount && result.rowCount > 0)
+ }
+
+ async upsertIdentity(data: {
+ userId: number
+ ssoConfigId: number
+ externalId: string
+ email: string
+ }): Promise<SsoIdentitiesSchemaTypeForSelect | null> {
+ const existing = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .select()
+ .from(SsoIdentitiesSchema)
+ .where(
+ and(
+ eq(SsoIdentitiesSchema.ssoConfigId, data.ssoConfigId),
+ eq(SsoIdentitiesSchema.externalId, data.externalId),
+ )
+ )
+ )
+
+ if (existing && existing.length > 0) {
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .update(SsoIdentitiesSchema)
+ .set({
+ email: data.email,
+ lastLoginAt: new Date(),
+ })
+ .where(eq(SsoIdentitiesSchema.id, existing[0].id))
+ .returning()
+ )
+ if (!result || result.length === 0) return null
+ return result[0]
+ }
+
+ const result = await callWithCatch(() =>
+ this.db.dbDrizzle
+ .insert(SsoIdentitiesSchema)
+ .values({
+ userId: data.userId,
+ ssoConfigId: data.ssoConfigId,
+ externalId: data.externalId,
+ email: data.email,
+ lastLoginAt: new Date(),
+ })
+ .returning()
+ )
+ if (!result || result.length === 0) return null
+ return result[0]
+ }
+}
diff --git a/api/src/tv-modules/sso/SsoRoutes.ts b/api/src/tv-modules/sso/SsoRoutes.ts
new file mode 100644
index 0000000..c6dbf10
--- /dev/null
+++ b/api/src/tv-modules/sso/SsoRoutes.ts
@@ -0,0 +1,34 @@
+import { Router } from 'express'
+import type { Routable } from '../../types/routable.type'
+import { IsLoggedIn } from '../auth/middlewares/is-logged-in'
+import { IsOrgAdmin } from '../organizations/middlewares/IsOrgAdmin'
+import { IsSsoConfigAdmin } from './middlewares/IsSsoConfigAdmin'
+import { SsoController } from './SsoController'
+
+export default class SsoRoutes implements Routable {
+ private readonly router: ReturnType<typeof Router>
+ private readonly controller: SsoController
+
+ constructor() {
+ this.router = Router()
+ this.controller = new SsoController()
+ this.initRoutes()
+ }
+
+ getRouter() {
+ return this.router
+ }
+
+ initRoutes() {
+ this.router.get('/providers', this.controller.listPublicProviders)
+ this.router.get('/login/:configId', this.controller.initiateLogin)
+ this.router.get('/callback/:configId', this.controller.handleCallback)
+ this.router.post('/callback/:configId', this.controller.handleCallback)
+
+ this.router.get('/admin/metadata', [IsLoggedIn], this.controller.parseMetadata)
+ this.router.get('/admin/configs', [IsLoggedIn], this.controller.listConfigs)
+ this.router.post('/admin/configs', [IsLoggedIn, IsOrgAdmin], this.controller.createConfig)
+ this.router.patch('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin], this.controller.updateConfig)
+ this.router.delete('/admin/configs/:configId', [IsLoggedIn, IsSsoConfigAdmin], this.controller.deleteConfig)
+ }
+}
diff --git a/api/src/tv-modules/sso/middlewares/IsSsoConfigAdmin.ts b/api/src/tv-modules/sso/middlewares/IsSsoConfigAdmin.ts
new file mode 100644
index 0000000..9536217
--- /dev/null
+++ b/api/src/tv-modules/sso/middlewares/IsSsoConfigAdmin.ts
@@ -0,0 +1,24 @@
+import type { NextFunction, Request, Response } from 'express'
+import { ORG_ADMIN_ROLES, type OrgRole } from '../../organizations/types'
+import { SsoRepository } from '../SsoRepository'
+
+const ssoRepo = new SsoRepository()
+
+/**
+ * Resolves SSO config by :configId param, finds its organization,
+ * and checks that the current user is admin/owner of that organization.
+ */
+export const IsSsoConfigAdmin = async (req: Request, res: Response, next: NextFunction) => {
+ const configId = Number(req.params.configId)
+ if (!configId) return res.status(400).end()
+
+ const config = await ssoRepo.findById(configId)
+ if (!config) return res.status(404).end()
+
+ const member = await req.appUser.organizationManager.getCurrentUserMember(config.organizationId)
+ if (!member || !ORG_ADMIN_ROLES.includes(member.role as OrgRole)) {
+ return res.status(403).end()
+ }
+
+ next()
+}
diff --git a/api/src/tv-modules/sso/providers/oidc.provider.ts b/api/src/tv-modules/sso/providers/oidc.provider.ts
new file mode 100644
index 0000000..3be1fb7
--- /dev/null
+++ b/api/src/tv-modules/sso/providers/oidc.provider.ts
@@ -0,0 +1,81 @@
+import * as client from 'openid-client'
+import type { Request, Response } from 'express'
+import type { SsoConfigsSchemaTypeForSelect } from 'taskview-db-schemas'
+import type { SsoProvider, SsoAuthResult } from './sso-provider.interface'
+
+export class OidcProvider implements SsoProvider {
+ private readonly config: SsoConfigsSchemaTypeForSelect
+ private oidcConfig: client.Configuration | null = null
+
+ constructor(config: SsoConfigsSchemaTypeForSelect) {
+ this.config = config
+ }
+
+ private async getOidcConfig(): Promise<client.Configuration> {
+ if (!this.oidcConfig) {
+ this.oidcConfig = await client.discovery(
+ new URL(this.config.oidcIssuer!),
+ this.config.oidcClientId!,
+ this.config.oidcClientSecret!,
+ )
+ }
+ return this.oidcConfig
+ }
+
+ async initiateLogin(_req: Request, res: Response, relayState?: string): Promise<void> {
+ const config = await this.getOidcConfig()
+ const scope = this.config.oidcScope ?? 'openid email profile'
+ const codeVerifier = client.randomPKCECodeVerifier()
+ const codeChallenge = await client.calculatePKCECodeChallenge(codeVerifier)
+
+ res.cookie(`sso_cv_${this.config.id}`, codeVerifier, {
+ httpOnly: true,
+ secure: true,
+ sameSite: 'lax',
+ maxAge: 5 * 60 * 1000,
+ })
+
+ const params = new URLSearchParams({
+ redirect_uri: this.config.oidcCallbackUrl!,
+ scope,
+ code_challenge: codeChallenge,
+ code_challenge_method: 'S256',
+ response_type: 'code',
+ })
+
+ if (relayState) {
+ params.set('state', relayState)
+ }
+
+ const authUrl = client.buildAuthorizationUrl(config, params)
+ res.redirect(authUrl.href)
+ }
+
+ async handleCallback(req: Request): Promise<SsoAuthResult> {
+ const config = await this.getOidcConfig()
+ const codeVerifier = req.cookies[`sso_cv_${this.config.id}`]
+
+ if (!codeVerifier) {
+ throw new Error('Missing PKCE code verifier — session may have expired')
+ }
+
+ const currentUrl = new URL(req.originalUrl, `${req.protocol}://${req.get('host')}`)
+ const tokens = await client.authorizationCodeGrant(config, currentUrl, {
+ pkceCodeVerifier: codeVerifier,
+ expectedState: req.query.state as string | undefined,
+ })
+
+ const claims = tokens.claims()
+
+ if (!claims || !claims.email) {
+ throw new Error('OIDC token missing email claim')
+ }
+
+ return {
+ email: (claims.email as string).toLowerCase(),
+ externalId: claims.sub,
+ displayName: claims.name as string | undefined,
+ provider: `oidc-${this.config.id}`,
+ }
+ }
+}
diff --git a/api/src/tv-modules/sso/providers/provider-factory.ts b/api/src/tv-modules/sso/providers/provider-factory.ts
new file mode 100644
index 0000000..442877f
--- /dev/null
+++ b/api/src/tv-modules/sso/providers/provider-factory.ts
@@ -0,0 +1,15 @@
+import type { SsoConfigsSchemaTypeForSelect } from 'taskview-db-schemas'
+import type { SsoProvider } from './sso-provider.interface'
+import { SamlProvider } from './saml.provider'
+import { OidcProvider } from './oidc.provider'
+
+export function createSsoProvider(config: SsoConfigsSchemaTypeForSelect): SsoProvider {
+ switch (config.protocol) {
+ case 'saml':
+ return new SamlProvider(config)
+ case 'oidc':
+ return new OidcProvider(config)
+ default:
+ throw new Error(`Unsupported SSO protocol: ${config.protocol}`)
+ }
+}
diff --git a/api/src/tv-modules/sso/providers/saml-cache-provider.ts b/api/src/tv-modules/sso/providers/saml-cache-provider.ts
new file mode 100644
index 0000000..b53f847
--- /dev/null
+++ b/api/src/tv-modules/sso/providers/saml-cache-provider.ts
@@ -0,0 +1,61 @@
+import type { CacheItem, CacheProvider } from '@node-saml/node-saml'
+import { eq, lt } from 'drizzle-orm'
+import { SamlRequestCacheSchema } from 'taskview-db-schemas'
+import { Database } from '../../../modules/db'
+
+export class SamlDbCacheProvider implements CacheProvider {
+ private readonly db: Database
+ private readonly ttlMs: number
+
+ constructor(ttlMs: number = 5 * 60 * 1000) {
+ this.db = Database.getInstance()
+ this.ttlMs = ttlMs
+ }
+
+ async saveAsync(key: string, value: string): Promise<CacheItem | null> {
+ const createdAt = Date.now()
+ await this.db.dbDrizzle
+ .insert(SamlRequestCacheSchema)
+ .values({ key, value, createdAt })
+ .onConflictDoUpdate({
+ target: SamlRequestCacheSchema.key,
+ set: { value, createdAt },
+ })
+ this.cleanup()
+ return { value, createdAt }
+ }
+
+ async getAsync(key: string): Promise<string | null> {
+ const result = await this.db.dbDrizzle
+ .select()
+ .from(SamlRequestCacheSchema)
+ .where(eq(SamlRequestCacheSchema.key, key))
+
+ if (!result.length) return null
+
+ const row = result[0]
+ if (Date.now() - row.createdAt > this.ttlMs) {
+ await this.removeAsync(key)
+ return null
+ }
+ return row.value
+ }
+
+ async removeAsync(key: string | null): Promise<string | null> {
+ if (!key) return null
+ const result = await this.db.dbDrizzle
+ .delete(SamlRequestCacheSchema)
+ .where(eq(SamlRequestCacheSchema.key, key))
+ .returning()
+
+ return result[0]?.value ?? null
+ }
+
+ private cleanup() {
+ const cutoff = Date.now() - this.ttlMs
+ this.db.dbDrizzle
+ .delete(SamlRequestCacheSchema)
+ .where(lt(SamlRequestCacheSchema.createdAt, cutoff))
+ .catch(() => {})
+ }
+}
diff --git a/api/src/tv-modules/sso/providers/saml.provider.ts b/api/src/tv-modules/sso/providers/saml.provider.ts
new file mode 100644
index 0000000..721b52a
--- /dev/null
+++ b/api/src/tv-modules/sso/providers/saml.provider.ts
@@ -0,0 +1,78 @@
+import { SAML, ValidateInResponseTo } from '@node-saml/node-saml'
+import type { Request, Response } from 'express'
+import type { SsoConfigsSchemaTypeForSelect } from 'taskview-db-schemas'
+import type { SsoProvider, SsoAuthResult } from './sso-provider.interface'
+import { SamlDbCacheProvider } from './saml-cache-provider'
+
+function normalizeCert(cert: string): string {
+ return cert
+ .replace(/-----BEGIN CERTIFICATE-----/g, '')
+ .replace(/-----END CERTIFICATE-----/g, '')
+ .replace(/[\s\r\n]/g, '')
+}
+
+function buildSamlOptions(config: SsoConfigsSchemaTypeForSelect, mode: 'assertion' | 'response') {
+ return {
+ entryPoint: config.samlEntryPoint!,
+ issuer: config.samlIssuer!,
+ idpCert: normalizeCert(config.samlCert!),
+ callbackUrl: config.samlCallbackUrl!,
+ wantAssertionsSigned: mode === 'assertion',
+ wantAuthnResponseSigned: mode === 'response',
+ validateInResponseTo: ValidateInResponseTo.always,
+ requestIdExpirationPeriodMs: 5 * 60 * 1000,
+ cacheProvider: new SamlDbCacheProvider(),
+ ...(config.samlSigningKey && config.samlSigningCert ? {
+ privateKey: config.samlSigningKey,
+ signingCert: config.samlSigningCert,
+ signatureAlgorithm: 'sha256' as const,
+ } : {}),
+ }
+}
+
+export class SamlProvider implements SsoProvider {
+ private readonly samlAssertion: SAML
+ private readonly samlResponse: SAML
+ private readonly config: SsoConfigsSchemaTypeForSelect
+
+ constructor(config: SsoConfigsSchemaTypeForSelect) {
+ this.config = config
+ this.samlAssertion = new SAML(buildSamlOptions(config, 'assertion'))
+ this.samlResponse = new SAML(buildSamlOptions(config, 'response'))
+ }
+
+ async initiateLogin(req: Request, res: Response, relayState?: string): Promise<void> {
+ const loginUrl = await this.samlAssertion.getAuthorizeUrlAsync(relayState ?? '', req.hostname, {})
+ res.redirect(loginUrl)
+ }
+
+ async handleCallback(req: Request): Promise<SsoAuthResult> {
+ let profile
+
+ try {
+ const result = await this.samlAssertion.validatePostResponseAsync(req.body)
+ profile = result.profile
+ } catch {
+ const result = await this.samlResponse.validatePostResponseAsync(req.body)
+ profile = result.profile
+ }
+
+ if (!profile || !profile.nameID) {
+ throw new Error('SAML response missing nameID')
+ }
+
+ const email = (
+ profile.email
+ ?? profile['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress']
+ ?? profile.nameID
+ ) as string
+
+ return {
+ email: email.toLowerCase(),
+ externalId: profile.nameID,
+ displayName: (profile.displayName
+ ?? profile['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name']) as string | undefined,
+ provider: `saml-${this.config.id}`,
+ }
+ }
+}
diff --git a/api/src/tv-modules/sso/providers/sso-provider.interface.ts b/api/src/tv-modules/sso/providers/sso-provider.interface.ts
new file mode 100644
index 0000000..8eeba92
--- /dev/null
+++ b/api/src/tv-modules/sso/providers/sso-provider.interface.ts
@@ -0,0 +1,13 @@
+import type { Request, Response } from 'express'
+
+export type SsoAuthResult = {
+ email: string
+ externalId: string
+ displayName?: string
+ provider: string
+}
+
+export type SsoProvider = {
+ initiateLogin(req: Request, res: Response, relayState?: string): Promise<void>
+ handleCallback(req: Request): Promise<SsoAuthResult>
+}
diff --git a/api/src/tv-modules/sso/saml-metadata-parser.ts b/api/src/tv-modules/sso/saml-metadata-parser.ts
new file mode 100644
index 0000000..48576bc
--- /dev/null
+++ b/api/src/tv-modules/sso/saml-metadata-parser.ts
@@ -0,0 +1,67 @@
+import { DOMParser, type Document } from '@xmldom/xmldom'
+
+type SamlMetadataResult = {
+ samlEntryPoint: string
+ samlCert: string
+ samlLogoutUrl: string
+}
+
+export function parseSamlMetadata(xml: string): SamlMetadataResult {
+ const doc = new DOMParser().parseFromString(xml, 'text/xml')
+
+ const entryPoint = findSsoLocation(doc)
+ const cert = findSigningCertificate(doc)
+ const logoutUrl = findSloLocation(doc)
+
+ return { samlEntryPoint: entryPoint, samlCert: cert, samlLogoutUrl: logoutUrl }
+}
+
+function findSsoLocation(doc: Document): string {
+ const ssoNodes = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'SingleSignOnService')
+
+ for (let i = 0; i < ssoNodes.length; i++) {
+ const node = ssoNodes[i]
+ const binding = node.getAttribute('Binding') ?? ''
+
+ if (binding.includes('HTTP-POST') || binding.includes('HTTP-Redirect')) {
+ return node.getAttribute('Location') ?? ''
+ }
+ }
+
+ return ''
+}
+
+function findSloLocation(doc: Document): string {
+ const sloNodes = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'SingleLogoutService')
+
+ for (let i = 0; i < sloNodes.length; i++) {
+ const node = sloNodes[i]
+ const binding = node.getAttribute('Binding') ?? ''
+
+ if (binding.includes('HTTP-POST') || binding.includes('HTTP-Redirect')) {
+ return node.getAttribute('Location') ?? ''
+ }
+ }
+
+ return ''
+}
+
+function findSigningCertificate(doc: Document): string {
+ const keyDescriptors = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'KeyDescriptor')
+
+ for (let i = 0; i < keyDescriptors.length; i++) {
+ const descriptor = keyDescriptors[i]
+ const use = descriptor.getAttribute('use')
+
+ if (use && use !== 'signing') continue
+
+ const certNodes = descriptor.getElementsByTagNameNS('http://www.w3.org/2000/09/xmldsig#', 'X509Certificate')
+
+ if (certNodes.length > 0) {
+ const certText = certNodes[0].textContent ?? ''
+ return certText.replace(/[\s\r\n]/g, '')
+ }
+ }
+
+ return ''
+}
diff --git a/api/src/tv-modules/sso/types.ts b/api/src/tv-modules/sso/types.ts
new file mode 100644
index 0000000..e73c6d1
--- /dev/null
+++ b/api/src/tv-modules/sso/types.ts
@@ -0,0 +1,58 @@
+import { type } from 'arktype'
+
+export const SsoProtocols = {
+ SAML: 'saml',
+ OIDC: 'oidc',
+} as const
+
+export type SsoProtocol = typeof SsoProtocols[keyof typeof SsoProtocols]
+
+export const SsoConfigArkTypeCreate = type({
+ organizationId: 'number',
+ protocol: "'saml' | 'oidc'",
+ displayName: 'string > 0',
+ 'enabled?': 'number',
+
+ 'samlEntryPoint?': 'string',
+ 'samlIssuer?': 'string',
+ 'samlCert?': 'string',
+ 'samlCallbackUrl?': 'string',
+ 'samlSigningKey?': 'string',
+ 'samlSigningCert?': 'string',
+ 'samlLogoutUrl?': 'string',
+
+ 'oidcIssuer?': 'string',
+ 'oidcClientId?': 'string',
+ 'oidcClientSecret?': 'string',
+ 'oidcCallbackUrl?': 'string',
+ 'oidcScope?': 'string',
+
+ 'defaultOrgRole?': 'string',
+ emailDomainRestriction: 'string > 0',
+})
+
+export type SsoConfigArgCreate = typeof SsoConfigArkTypeCreate.infer
+
+export const SsoConfigArkTypeUpdate = type({
+ 'displayName?': 'string',
+ 'enabled?': 'number',
+
+ 'samlEntryPoint?': 'string',
+ 'samlIssuer?': 'string',
+ 'samlCert?': 'string',
+ 'samlCallbackUrl?': 'string',
+ 'samlSigningKey?': 'string',
+ 'samlSigningCert?': 'string',
+ 'samlLogoutUrl?': 'string',
+
+ 'oidcIssuer?': 'string',
+ 'oidcClientId?': 'string',
+ 'oidcClientSecret?': 'string',
+ 'oidcCallbackUrl?': 'string',
+ 'oidcScope?': 'string',
+
+ 'defaultOrgRole?': 'string',
+ 'emailDomainRestriction?': 'string',
+})
+
+export type SsoConfigArgUpdate = typeof SsoConfigArkTypeUpdate.infer
diff --git a/docs/2.features/10.organizations.md b/docs/2.features/10.organizations.md
new file mode 100644
index 0000000..d33244b
--- /dev/null
+++ b/docs/2.features/10.organizations.md
@@ -0,0 +1,84 @@
+---
+title: Organizations
+description: Group projects and team members under organizations in TaskView. Manage access with organization-level roles - owner, admin, and member. Each organization has its own members, projects, and settings.
+navigation:
+ icon: i-lucide-building-2
+---
+
+Organizations let you group projects and people together. Every project belongs to an organization, and every user gets a personal organization automatically on registration.
+
+## Types of organizations
+
+**Personal** - created automatically for each user. Contains your personal projects. Can't be deleted.
+
+**Team** - created manually. Use these to collaborate with other people. You can invite members, assign roles, and manage shared projects.
+
+## Creating an organization
+
+Go to the **Organizations** page and click the **+** button. Enter a name - a slug will be generated automatically. You can change the slug later.
+
+## Roles
+
+Each member of an organization has one of three roles:
+
+| Role | Description |
+|------|-------------|
+| **Owner** | The person who created the organization. One owner per organization. Can't be transferred, can't be removed |
+| **Admin** | Can edit organization settings, invite and remove members, change roles |
+| **Member** | Can work in projects they've been added to, but can't manage the organization, view member list, or change settings |
+
+## What each role can do
+
+| Action | Owner | Admin | Member |
+|--------|:-----:|:-----:|:------:|
+| View organization | + | + | + |
+| Edit name and slug | + | + | - |
+| View member list | + | + | - |
+| Add members | + | + | - |
+| Change member roles | + | + | - |
+| Remove members | + | + | - |
+| Create projects | + | + | + |
+| Delete organization | + | - | - |
+
+Regular members don't see the **Members** tab and can't edit organization settings - fields are disabled for them. The **Delete** button is only visible to the owner.
+
+## Managing members
+
+Only **owners** and **admins** can manage members. The **Members** tab is not visible to regular members.
+
+1. Open the organization
+2. Go to the **Members** tab
+3. Enter an email address and click **Add Member**
+
+New members are added with the **member** role by default. You can change their role to **admin** using the role dropdown next to their name. Members can only be invited by email. The person needs to have a TaskView account with that email.
+
+::callout{icon="i-lucide-alert-triangle" color="warning"}
+When a project member with the **Manage users** permission invites someone into a project, that person is automatically added to the organization as a **member** - even though only admins and owners can add members directly. This is by design: a person can't be in a project without being in its organization. The auto-added member gets the minimum role and can't manage the organization.
+::
+
+## Removing members
+
+Click the **X** button next to a member's name. They'll lose access to the organization and all its projects immediately. The owner can't be removed.
+
+## Projects and ownership
+
+Any organization member can create a project inside the organization. When a member creates a project:
+
+- The **project owner** is set to the **organization owner**, not the person who created it
+- The creator is automatically added as a **collaborator with full access** to that project
+- The project belongs to the organization and follows its lifecycle - deleting the organization deletes all its projects
+
+## Deleting an organization
+
+Only the owner can delete an organization. Click the **Delete** button in the organization settings footer. This removes the organization and all its projects permanently.
+
+## Organization vs project permissions
+
+Organizations and projects have separate permission systems:
+
+- **Organization roles** (owner, admin, member) control who can manage the organization itself - settings, members, deletion
+- **Project roles** control what users can do inside a specific project - create tasks, edit statuses, manage Kanban, etc.
+
+Being an organization admin doesn't automatically give you permissions inside projects. You still need to be added to each project and assigned a project role. See [Roles and Permissions](/docs/collaboration/roles-and-permissions) for project-level access control.
+
+The member list API endpoint is restricted to owners and admins. Regular members cannot fetch the list of organization members.
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bcbc452..d6264ef 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -45,6 +45,9 @@ importers:
api:
dependencies:
+ '@node-saml/node-saml':
+ specifier: ^5.1.0
+ version: 5.1.0
'@types/bcryptjs':
specifier: ^2.4.6
version: 2.4.6
@@ -63,12 +66,15 @@ importers:
'@vitejs/plugin-vue':
specifier: ^5.1.4
+ '@xmldom/xmldom':
+ specifier: ^0.9.9
+ version: 0.9.9
arktype:
specifier: 2.1.20
version: 2.1.20
axios:
- specifier: ^1.7.7
- version: 1.13.2
+ specifier: 1.13.5
+ version: 1.13.5
bcryptjs:
specifier: ^2.4.3
version: 2.4.3
@@ -102,6 +108,9 @@ importers:
jsonwebtoken:
specifier: ^9.0.2
version: 9.0.3
+ openid-client:
+ specifier: ^6.8.2
+ version: 6.8.2
passport:
specifier: ^0.7.0
version: 0.7.0
@@ -216,8 +225,8 @@ importers:
specifier: ^8.10.9
version: 8.16.0
axios:
- specifier: ^1.2.3
- version: 1.13.2
+ specifier: 1.13.5
+ version: 1.13.5
bun:
specifier: ^1.3.0
version: 1.3.6
@@ -235,7 +244,7 @@ importers:
vitest:
specifier: ^3.2.4
taskview-packages/taskview-db-schemas:
dependencies:
@@ -269,7 +278,7 @@ importers:
specifier: ^22.0.0
version: 22.19.7
axios:
- specifier: ^1.2.3
+ specifier: 1.13.5
version: 1.13.5
taskview-api:
specifier: workspace:*
@@ -401,7 +410,7 @@ importers:
specifier: 2.1.20
version: 2.1.20
axios:
- specifier: ^1.13.4
+ specifier: 1.13.5
version: 1.13.5
centrifuge:
specifier: ^5.5.3
@@ -2175,6 +2184,10 @@ packages:
resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}
engines: {node: ^14.21.3 || >=16}
+ '@node-saml/[email protected]':
+ resolution: {integrity: sha512-t3cJnZ4aC7HhPZ6MGylGZULvUtBOZ6FzuUndaHGXjmIZHXnLfC/7L8a57O9Q9V7AxJGKAiRM5zu2wNm9EsvQpw==}
+ engines: {node: '>= 18'}
+
'@nodelib/[email protected]':
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -3229,6 +3242,9 @@ packages:
resolution: {integrity: sha512-f4gkWqzPZvYmKhOsDnhq/R8mO4UMcKdxZo+i5SCkOU1wvGeHJeUXGIHeE9pnwGyPMDof1Vx5ZQo4nxpeg2TTVQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}
+
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
@@ -3403,6 +3419,12 @@ packages:
resolution: {integrity: sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-I69K/WW1Dv7j6O3jh13z0X8sLWJRXbu5xnHDl9yHzUNDUBtUoBY058eb5s+x/WG6yZC1h8aKdI2EoyEPjyEh+Q==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-4YnrRemBShWRO2QjvUin8ESA41rH+9nQGLUGZV/1IDhi3SL9OhdpNC/MrulTWuptXKwhx/aDxE7toV0f/ypIXQ==}
+
'@typescript-eslint/[email protected]':
resolution: {integrity: sha512-cFYYFZ+oQFi6hUnBTbLRXfTJiaQtYE3t4O692agbBl+2Zy+eqSKWtPjhPXJu1G7j4RLjKgeJPDdq3EqOwmX5Ag==}
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
@@ -3765,14 +3787,23 @@ packages:
'@xml-tools/[email protected]':
resolution: {integrity: sha512-aKqQ077XnR+oQtHJlrAflaZaL7qZsulWc/i/ZEooar5JiWj1eLt0+Wg28cpa+XLney107wXqneC+oG1IZvxkTA==}
+ '@xmldom/[email protected]':
+ resolution: {integrity: sha512-CJDxIgE5I0FH+ttq/Fxy6nRpxP70+e2O048EPe85J2use3XKdatVM7dDVvFNjQudd9B49NPoZ+8PG49zj4Er8Q==}
+ engines: {node: '>= 16'}
+
'@xmldom/[email protected]':
resolution: {integrity: sha512-lm2GW5PkosIzccsaZIz7tp8cPADSIlIHWDFTR1N0SzfinhhYgeIQjFMz4rYzanCScr3DqQLeomUDArp6MWKm+g==}
engines: {node: '>=10.0.0'}
- deprecated: this version is no longer supported, please update to at least 0.8.*
+ deprecated: this version has critical issues, please update to the latest version
'@xmldom/[email protected]':
resolution: {integrity: sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==}
engines: {node: '>=10.0.0'}
+ deprecated: this version has critical issues, please update to the latest version
+
+ '@xmldom/[email protected]':
+ resolution: {integrity: sha512-qycIHAucxy/LXAYIjmLmtQ8q9GPnMbnjG1KXhWm9o5sCr6pOYDATkMPiTNa6/v8eELyqOQ2FsEqeoFYmgv/gJg==}
+ engines: {node: '>=14.6'}
resolution: {integrity: sha512-E+iruNOY8VV9s4JEbe1aNEm6MiszPRr/UfcHMz0TQh1BXSxHK+ASV1R6W4HpjBhSeS+54PIsAMCBmwD06LLsqQ==}
@@ -3978,9 +4009,6 @@ packages:
engines: {node: '>= 10.0.0'}
deprecated: The AWS SDK for JavaScript (v2) has reached end-of-support, and no longer receives updates. Please migrate your code to use AWS SDK for JavaScript (v3). More info https://a.co/cUPnyil
- resolution: {integrity: sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==}
-
resolution: {integrity: sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q==}
@@ -6644,6 +6672,9 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-A8jmyUckVhRJj5lspguklcl90Ydqk61H3dcU0oLhH3Yv13KpAliKTt5hknpGGPZSSfOwGyraNEFmofDYH+1kSg==}
+
resolution: {integrity: sha512-JtFnB+8nxDEXgNyniwz573xxbKSOu3R8D40xQKqcjwJ2CDkYqUDI53o6IuzDJBx60Z8VKCm271+t8iFjakrl8Q==}
@@ -6687,6 +6718,9 @@ packages:
resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-uOvTCndr4udZsKihJ68H9bUICrriHdUVJ6Az+4Ns6cW55rwM5h0bjVIzDz2SxgOI84LKjFyjOFvERLzdTUROGA==}
+
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
@@ -8621,6 +8655,13 @@ packages:
resolution: {integrity: sha512-kCz5k7J7XbJtjABOvkc5lJmkiDh8VhjVCGNiqdKCscmVpdVUpEAyXv1xmCLkQJ5dsHqx3IPO4XW+NTDhU/fatA==}
engines: {node: '>=10.0.0'}
+ resolution: {integrity: sha512-leBOVQdVi8FvPJrMYoum7Ici9qyxfE4kVi+AkpUoYCSXaQF4IlBm1cneTK9oAxR61LpYxTx7lNcsnBIeRpGW2w==}
+ engines: {node: '>=16'}
+
+ resolution: {integrity: sha512-PV7qnYpoAMXbf1kvQkqMScLeQpjCMixddAKq9PtqVrho8HnYbBOWNfG0kA4R7zxQDo7w9kiYAyzS/ullAyO55Q==}
+
resolution: {integrity: sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==}
hasBin: true
@@ -8656,6 +8697,14 @@ packages:
resolution: {integrity: sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw==}
engines: {node: '>=0.6.0'}
+ resolution: {integrity: sha512-NNXnzrkDrAzalLhIUc01jO2mOzXGXh1JwPgkihcLLzw98c0WgYDmmjSh1Kl3wzaxSVWMuA+fe0WTWOBDWCBmNA==}
+ engines: {node: '>=0.6.0'}
+
+ resolution: {integrity: sha512-FxF6+rkr1rNSQrhUNYrAFJpRXNzlDoMxeXN5qI84939ylEv3qqPFKa85Oxr6tDaJKqwW6KKyo2v26TSv3k6LeA==}
+ engines: {node: '>=0.6.0'}
+
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
@@ -10711,6 +10760,23 @@ snapshots:
'@noble/[email protected]': {}
+ '@node-saml/[email protected]':
+ dependencies:
+ '@types/debug': 4.1.13
+ '@types/qs': 6.14.0
+ '@types/xml-encryption': 1.2.4
+ '@types/xml2js': 0.4.14
+ '@xmldom/is-dom-node': 1.0.1
+ '@xmldom/xmldom': 0.8.11
+ debug: 4.4.3
+ xml-crypto: 6.1.2
+ xml-encryption: 3.1.0
+ xml2js: 0.6.2
+ xmlbuilder: 15.1.1
+ xpath: 0.0.34
+ transitivePeerDependencies:
+ - supports-color
+
'@nodelib/[email protected]':
dependencies:
'@nodelib/fs.stat': 2.0.5
@@ -11898,6 +11964,10 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/ms': 2.1.0
+
'@types/[email protected]': {}
@@ -12118,6 +12188,14 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.7
+
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.7
+
dependencies:
'@eslint-community/regexpp': 4.12.2
@@ -12662,10 +12740,14 @@ snapshots:
dependencies:
chevrotain: 7.1.1
+ '@xmldom/[email protected]': {}
+
'@xmldom/[email protected]': {}
'@xmldom/[email protected]': {}
+ '@xmldom/[email protected]': {}
+
dependencies:
jsonparse: 1.3.1
@@ -12888,14 +12970,6 @@ snapshots:
uuid: 8.0.0
xml2js: 0.6.2
- dependencies:
- follow-redirects: 1.15.11
- form-data: 4.0.5
- proxy-from-env: 1.1.0
- transitivePeerDependencies:
- - debug
-
dependencies:
follow-redirects: 1.15.11
@@ -15764,6 +15838,8 @@ snapshots:
pathe: 2.0.3
tinyexec: 1.0.2
+
@@ -15803,6 +15879,11 @@ snapshots:
is-docker: 2.2.1
is-wsl: 2.2.0
+ dependencies:
+ jose: 6.2.2
+ oauth4webapi: 3.8.5
+
dependencies:
deep-is: 0.1.4
@@ -17658,7 +17739,7 @@ snapshots:
- supports-color
- terser
dependencies:
'@types/chai': 5.2.3
'@vitest/expect': 3.2.4
@@ -17684,6 +17765,7 @@ snapshots:
why-is-node-running: 2.3.0
optionalDependencies:
+ '@types/debug': 4.1.13
'@types/node': 25.3.0
jsdom: 20.0.3
transitivePeerDependencies:
@@ -17891,6 +17973,18 @@ snapshots:
simple-plist: 1.3.1
uuid: 7.0.3
+ dependencies:
+ '@xmldom/is-dom-node': 1.0.1
+ '@xmldom/xmldom': 0.8.11
+ xpath: 0.0.33
+
+ dependencies:
+ '@xmldom/xmldom': 0.8.11
+ escape-html: 1.0.3
+ xpath: 0.0.32
+
dependencies:
sax: 1.4.4
@@ -17918,6 +18012,10 @@ snapshots:
+
+
diff --git a/taskview-packages/taskview-api/src/api/organizations.types.ts b/taskview-packages/taskview-api/src/api/organizations.types.ts
index f7e117a..defe3e9 100644
--- a/taskview-packages/taskview-api/src/api/organizations.types.ts
+++ b/taskview-packages/taskview-api/src/api/organizations.types.ts
@@ -7,6 +7,7 @@ export type Organization = {
plan: string
createdAt: string
updatedAt: string
+ currentUserRole: 'owner' | 'admin' | 'member'
}
export type OrgMember = {
diff --git a/taskview-packages/taskview-api/src/api/sso.ts b/taskview-packages/taskview-api/src/api/sso.ts
new file mode 100644
index 0000000..6037535
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/sso.ts
@@ -0,0 +1,54 @@
+import TvApiBase from './base'
+import type { AppResponse } from './base.types'
+import type {
+ SsoConfig,
+ SsoConfigArgCreate,
+ SsoConfigArgUpdate,
+ SsoProviderPublic,
+} from './sso.types'
+
+export default class TvSsoApi extends TvApiBase {
+ protected moduleUrl = '/module/sso'
+
+ public async listConfigs(organizationId: number) {
+ return this.request(
+ this.$axios.get<AppResponse<SsoConfig[]>>(`${this.moduleUrl}/admin/configs`, {
+ params: { organizationId },
+ })
+ )
+ }
+
+ public async createConfig(data: SsoConfigArgCreate) {
+ return this.request(
+ this.$axios.post<AppResponse<SsoConfig>>(`${this.moduleUrl}/admin/configs`, data)
+ )
+ }
+
+ public async updateConfig(configId: number, data: SsoConfigArgUpdate) {
+ return this.request(
+ this.$axios.patch<AppResponse<SsoConfig>>(`${this.moduleUrl}/admin/configs/${configId}`, data)
+ )
+ }
+
+ public async deleteConfig(configId: number) {
+ return this.request(
+ this.$axios.delete<AppResponse<boolean>>(`${this.moduleUrl}/admin/configs/${configId}`)
+ )
+ }
+
+ public async parseMetadata(url: string) {
+ return this.request(
+ this.$axios.get<AppResponse<{ samlEntryPoint: string, samlCert: string, samlLogoutUrl: string }>>(`${this.moduleUrl}/admin/metadata`, {
+ params: { url },
+ })
+ )
+ }
+
+ public async checkDomain(domain: string) {
+ return this.request(
+ this.$axios.get<AppResponse<SsoProviderPublic | null>>(`${this.moduleUrl}/providers`, {
+ params: { domain },
+ })
+ )
+ }
+}
diff --git a/taskview-packages/taskview-api/src/api/sso.types.ts b/taskview-packages/taskview-api/src/api/sso.types.ts
new file mode 100644
index 0000000..2e36d78
--- /dev/null
+++ b/taskview-packages/taskview-api/src/api/sso.types.ts
@@ -0,0 +1,79 @@
+export type SsoConfig = {
+ id: number
+ organizationId: number
+ protocol: 'saml' | 'oidc'
+ displayName: string
+ enabled: number
+
+ samlEntryPoint: string | null
+ samlIssuer: string | null
+ samlCert: string | null
+ samlCallbackUrl: string | null
+ samlSigningKey: string | null
+ samlSigningCert: string | null
+ samlLogoutUrl: string | null
+
+ oidcIssuer: string | null
+ oidcClientId: string | null
+ oidcClientSecret: string | null
+ oidcCallbackUrl: string | null
+ oidcScope: string | null
+
+ defaultOrgRole: string
+ emailDomainRestriction: string
+
+ createdAt: string
+ updatedAt: string
+}
+
+export type SsoConfigArgCreate = {
+ organizationId: number
+ protocol: 'saml' | 'oidc'
+ displayName: string
+ enabled?: number
+ emailDomainRestriction: string
+
+ samlEntryPoint?: string
+ samlIssuer?: string
+ samlCert?: string
+ samlCallbackUrl?: string
+ samlSigningKey?: string
+ samlSigningCert?: string
+ samlLogoutUrl?: string
+
+ oidcIssuer?: string
+ oidcClientId?: string
+ oidcClientSecret?: string
+ oidcCallbackUrl?: string
+ oidcScope?: string
+
+ defaultOrgRole?: string
+}
+
+export type SsoConfigArgUpdate = {
+ displayName?: string
+ enabled?: number
+ emailDomainRestriction?: string
+
+ samlEntryPoint?: string
+ samlIssuer?: string
+ samlCert?: string
+ samlCallbackUrl?: string
+ samlSigningKey?: string
+ samlSigningCert?: string
+ samlLogoutUrl?: string
+
+ oidcIssuer?: string
+ oidcClientId?: string
+ oidcClientSecret?: string
+ oidcCallbackUrl?: string
+ oidcScope?: string
+
+ defaultOrgRole?: string
+}
+
+export type SsoProviderPublic = {
+ id: number
+ displayName: string
+ protocol: string
+}
diff --git a/taskview-packages/taskview-api/src/tv.ts b/taskview-packages/taskview-api/src/tv.ts
index 311999f..41437c8 100644
--- a/taskview-packages/taskview-api/src/tv.ts
+++ b/taskview-packages/taskview-api/src/tv.ts
@@ -12,6 +12,7 @@ import TvWebhooks from "./api/webhooks";
import TvApiTokens from "./api/api-tokens";
import TvSessions from "./api/sessions";
import TvOrganizationsApi from "./api/organizations";
+import TvSsoApi from "./api/sso";
export class TvApi {
@@ -43,6 +44,8 @@ export class TvApi {
public organizations: TvOrganizationsApi;
+ public sso: TvSsoApi;
+
constructor($axios: AxiosInstance) {
this.$axios = $axios;
@@ -71,6 +74,8 @@ export class TvApi {
this.sessions = new TvSessions(this.$axios);
this.organizations = new TvOrganizationsApi(this.$axios);
+
+ this.sso = new TvSsoApi(this.$axios);
}
public setBaseUrl(baseUrl: string) {
diff --git a/taskview-packages/taskview-db-schemas/src/index.ts b/taskview-packages/taskview-db-schemas/src/index.ts
index 65b536d..e0af58c 100644
--- a/taskview-packages/taskview-db-schemas/src/index.ts
+++ b/taskview-packages/taskview-db-schemas/src/index.ts
@@ -16,3 +16,4 @@ export * from './schemas/webhooks.schema';
export * from './schemas/api-tokens.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/sso.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/sso.schema.ts
new file mode 100644
index 0000000..92f6296
--- /dev/null
+++ b/taskview-packages/taskview-db-schemas/src/schemas/sso.schema.ts
@@ -0,0 +1,55 @@
+import { bigint, integer, pgSchema, text, timestamp, unique, varchar } from 'drizzle-orm/pg-core'
+import { UsersSchema } from './users.schema'
+import { OrganizationsSchema } from './organizations.schema'
+
+export const SsoConfigsSchema = pgSchema('tv_auth').table('sso_configs', {
+ id: integer().primaryKey().generatedAlwaysAsIdentity(),
+ organizationId: integer('organization_id').notNull().references(() => OrganizationsSchema.id, { onDelete: 'cascade' }),
+ protocol: varchar().notNull(),
+ displayName: varchar('display_name').notNull(),
+ enabled: integer().notNull().default(1),
+
+ samlEntryPoint: varchar('saml_entry_point'),
+ samlIssuer: varchar('saml_issuer'),
+ samlCert: text('saml_cert'),
+ samlCallbackUrl: varchar('saml_callback_url'),
+ samlSigningKey: text('saml_signing_key'),
+ samlSigningCert: text('saml_signing_cert'),
+ samlLogoutUrl: varchar('saml_logout_url'),
+
+ oidcIssuer: varchar('oidc_issuer'),
+ oidcClientId: varchar('oidc_client_id'),
+ oidcClientSecret: varchar('oidc_client_secret'),
+ oidcCallbackUrl: varchar('oidc_callback_url'),
+ oidcScope: varchar('oidc_scope'),
+
+ defaultOrgRole: varchar('default_org_role').notNull().default('member'),
+ emailDomainRestriction: varchar('email_domain_restriction').notNull().unique(),
+
+ createdAt: timestamp('created_at').defaultNow(),
+ updatedAt: timestamp('updated_at').defaultNow(),
+})
+
+export type SsoConfigsSchemaTypeForSelect = typeof SsoConfigsSchema.$inferSelect
+export type SsoConfigsSchemaTypeForInsert = typeof SsoConfigsSchema.$inferInsert
+
+export const SsoIdentitiesSchema = pgSchema('tv_auth').table('sso_identities', {
+ id: integer().primaryKey().generatedAlwaysAsIdentity(),
+ userId: integer('user_id').notNull().references(() => UsersSchema.id, { onDelete: 'cascade' }),
+ ssoConfigId: integer('sso_config_id').notNull().references(() => SsoConfigsSchema.id, { onDelete: 'cascade' }),
+ externalId: varchar('external_id').notNull(),
+ email: varchar().notNull(),
+ lastLoginAt: timestamp('last_login_at'),
+ createdAt: timestamp('created_at').defaultNow(),
+}, (table) => [
+ unique().on(table.ssoConfigId, table.externalId),
+])
+
+export type SsoIdentitiesSchemaTypeForSelect = typeof SsoIdentitiesSchema.$inferSelect
+export type SsoIdentitiesSchemaTypeForInsert = typeof SsoIdentitiesSchema.$inferInsert
+
+export const SamlRequestCacheSchema = pgSchema('tv_auth').table('saml_request_cache', {
+ key: varchar().primaryKey(),
+ value: varchar().notNull(),
+ createdAt: bigint('created_at', { mode: 'number' }).notNull(),
+})
diff --git a/web/src/components/UserMenu.vue b/web/src/components/UserMenu.vue
index 4074f4a..34cc2f7 100644
--- a/web/src/components/UserMenu.vue
+++ b/web/src/components/UserMenu.vue
@@ -143,6 +143,7 @@ const items = computed<DropdownMenuItem[][]>(() => [
onSelect(e: Event) {
e.preventDefault()
orgStore.setCurrentOrg(org)
+ router.push({ name: 'user', params: { orgSlug: org.slug } })
},
})),
},
diff --git a/web/src/components/features/auth/LoginBySso.vue b/web/src/components/features/auth/LoginBySso.vue
new file mode 100644
index 0000000..4ca184b
--- /dev/null
+++ b/web/src/components/features/auth/LoginBySso.vue
@@ -0,0 +1,105 @@
+<template>
+ <div class="space-y-4">
+ <UForm
+ :state="state"
+ :schema="schema"
+ class="space-y-4"
+ @submit="handleSubmit"
+ >
+ <UFormField
+ :label="t('auth.email')"
+ name="email"
+ >
+ <UInput
+ v-model="state.email"
+ type="email"
+ :placeholder="t('auth.emailPlaceholder')"
+ icon="i-lucide-mail"
+ class="w-full"
+ />
+ </UFormField>
+
+ <UButton
+ :label="t('auth.ssoSignIn')"
+ type="submit"
+ color="primary"
+ block
+ :loading="isLoading"
+ />
+ </UForm>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { type } from 'arktype'
+import { ref, reactive } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { Capacitor } from '@capacitor/core'
+import { Browser } from '@capacitor/browser'
+import $api from '@/helpers/axios'
+import { useAdditionalServer } from '@/composables/useAdditionalServer'
+
+const { t } = useI18n()
+const toast = useToast()
+
+const isLoading = ref(false)
+
+const emailType = type('string.email').configure({ message: t('auth.invalidEmail') })
+
+const schema = type({
+ email: emailType,
+})
+
+type SsoProviderResponse = {
+ response: {
+ id: number
+ displayName: string
+ protocol: string
+ } | null
+}
+
+const state = reactive({
+ email: '',
+})
+
+async function handleSubmit() {
+ isLoading.value = true
+
+ try {
+ const domain = state.email.split('@')[1]
+ if (!domain) return
+
+ const result = await $api.get<SsoProviderResponse>('/module/sso/providers', {
+ params: { domain },
+ })
+
+ const provider = result.data.response
+ if (!provider) {
+ toast.add({
+ title: t('auth.ssoNotFound'),
+ description: t('auth.ssoNotFoundDescription', { domain }),
+ color: 'warning',
+ })
+ return
+ }
+
+ const { mainServer } = await useAdditionalServer()
+ const platform = Capacitor.isNativePlatform() ? 'mobile' : 'web'
+ const url = `${mainServer.value}/module/sso/login/${provider.id}?platform=${platform}`
+
+ if (Capacitor.isNativePlatform()) {
+ await Browser.open({ url })
+ } else {
+ window.location.href = url
+ }
+ } catch {
+ toast.add({
+ title: t('auth.error'),
+ description: t('auth.ssoError'),
+ color: 'error',
+ })
+ } finally {
+ isLoading.value = false
+ }
+}
+</script>
diff --git a/web/src/components/features/auth/LoginForm.vue b/web/src/components/features/auth/LoginForm.vue
index 1057f8d..be6fe47 100644
--- a/web/src/components/features/auth/LoginForm.vue
+++ b/web/src/components/features/auth/LoginForm.vue
@@ -53,6 +53,12 @@
/>
</div>
</template>
+
+ <template #sso>
+ <div class="pt-4">
+ <LoginBySso />
+ </div>
+ </template>
</UTabs>
</template>
@@ -97,6 +103,7 @@ import { ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import LoginByCode from './LoginByCode.vue'
import LoginByPassword from './LoginByPassword.vue'
+import LoginBySso from './LoginBySso.vue'
import ForgotPassword from './ForgotPassword.vue'
import SocialButtons from './SocialButtons.vue'
import ServerSelector from './ServerSelector.vue'
@@ -107,13 +114,14 @@ const emit = defineEmits<{
success: [token: string]
}>()
-type View = 'code' | 'password' | 'forgot'
+type View = 'code' | 'password' | 'sso' | 'forgot'
const currentView = ref<View>('code')
const tabs = computed(() => [
{ value: 'code', label: t('auth.magicLink'), slot: 'code' as const },
{ value: 'password', label: t('auth.password'), slot: 'password' as const },
+ { value: 'sso', label: 'SSO', slot: 'sso' as const },
])
function onTabChange(value: string | number) {
diff --git a/web/src/components/features/auth/auth.helper.ts b/web/src/components/features/auth/auth.helper.ts
index b713b3b..c6fe9c4 100644
--- a/web/src/components/features/auth/auth.helper.ts
+++ b/web/src/components/features/auth/auth.helper.ts
@@ -1,9 +1,15 @@
import { useUserStore } from '@/stores/user.store'
+import { useOrganizationStore } from '@/stores/organization.store'
import { Router } from 'vue-router'
export const redirectToUser = async (router: Router) => {
- const userStore: ReturnType<typeof useUserStore> = useUserStore()
+ const userStore = useUserStore()
if (userStore.accessToken) {
- await router.push({ name: 'user', params: { user: userStore.login } })
+ const orgStore = useOrganizationStore()
+ if (!orgStore.organizations.length) {
+ await orgStore.fetchOrganizations()
+ orgStore.restoreCurrentOrg()
+ }
+ await router.push({ name: 'user', params: { orgSlug: orgStore.currentOrgSlug } })
}
}
\ No newline at end of file
diff --git a/web/src/components/features/organizations/parts/OrgDetailModal.vue b/web/src/components/features/organizations/parts/OrgDetailModal.vue
index ee606ff..123f25b 100644
--- a/web/src/components/features/organizations/parts/OrgDetailModal.vue
+++ b/web/src/components/features/organizations/parts/OrgDetailModal.vue
@@ -1,7 +1,7 @@
<template>
- <UModal v-model:open="open" :fullscreen="isMobile" :ui="{ content: 'max-w-lg' }">
+ <UModal v-model:open="open" :fullscreen="isMobile" :ui="{ content: 'max-w-lg max-h-[90vh] flex flex-col' }">
<template #content>
- <UCard v-if="organization">
+ <UCard v-if="organization" :ui="{ root: 'flex flex-col flex-1 min-h-0', body: 'flex-1 min-h-0 overflow-y-auto' }">
<template #header>
<div class="flex items-center justify-between">
<h3 class="font-semibold">{{ organization.name }}</h3>
@@ -13,12 +13,12 @@
<template #general>
<div class="flex flex-col gap-4 pt-4">
<UFormField :label="t('organizations.name')">
- <UInput v-model="editName" class="w-full" />
+ <UInput v-model="editName" :disabled="!isAdmin" class="w-full" />
</UFormField>
<UFormField :label="t('organizations.slug')">
- <UInput v-model="editSlug" :placeholder="t('organizations.slugPlaceholder')" class="w-full" />
+ <UInput v-model="editSlug" :disabled="!isAdmin" :placeholder="t('organizations.slugPlaceholder')" class="w-full" />
</UFormField>
- <UButton :label="t('organizations.save')" :loading="saving" @click="save" />
+ <UButton v-if="isAdmin" :label="t('organizations.save')" :loading="saving" @click="save" />
</div>
</template>
@@ -66,17 +66,22 @@
</div>
</div>
</template>
+ <template #sso>
+ <OrgSsoSettings :organization-id="organization.id" />
+ </template>
</UTabs>
<template #footer>
<div class="flex justify-between">
<UButton
+ v-if="isOwner"
:label="t('organizations.delete')"
color="error"
variant="ghost"
icon="i-lucide-trash-2"
@click="deleteOrg"
/>
+ <div v-else />
<UButton :label="t('organizations.save')" variant="ghost" @click="open = false" />
</div>
</template>
@@ -90,6 +95,8 @@ import { ref, watch, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useOrganizationStore } from '@/stores/organization.store'
import { useTaskView } from '@/composables/useTaskView'
+import { useOrgPermissions } from '@/composables/useOrgPermissions'
+import OrgSsoSettings from './OrgSsoSettings.vue'
const open = defineModel<boolean>({ default: false })
const props = defineProps<{
@@ -100,6 +107,7 @@ const { t } = useI18n()
const toast = useToast()
const { isMobile } = useTaskView()
const orgStore = useOrganizationStore()
+const { isAdmin, isOwner } = useOrgPermissions(() => props.organization)
const editName = ref('')
const editSlug = ref('')
@@ -107,10 +115,16 @@ const newMemberEmail = ref('')
const saving = ref(false)
const addingMember = ref(false)
-const tabs = computed(() => [
- { label: t('organizations.general'), slot: 'general' },
- { label: t('organizations.members'), slot: 'members' },
-])
+const tabs = computed(() => {
+ const items = [
+ { label: t('organizations.general'), slot: 'general' },
+ ]
+ if (isAdmin.value) {
+ items.push({ label: t('organizations.members'), slot: 'members' })
+ items.push({ label: 'SSO', slot: 'sso' })
+ }
+ return items
+})
const roleOptions = [
{ label: 'Admin', value: 'admin' },
@@ -121,7 +135,9 @@ watch(() => props.organization, (org) => {
if (org) {
editName.value = org.name
editSlug.value = org.slug
- orgStore.fetchMembers(org.id)
+ if (org.currentUserRole === 'owner' || org.currentUserRole === 'admin') {
+ orgStore.fetchMembers(org.id)
+ }
}
}, { immediate: true })
diff --git a/web/src/components/features/organizations/parts/OrgSsoSettings.vue b/web/src/components/features/organizations/parts/OrgSsoSettings.vue
new file mode 100644
index 0000000..a37d4d7
--- /dev/null
+++ b/web/src/components/features/organizations/parts/OrgSsoSettings.vue
@@ -0,0 +1,438 @@
+<template>
+ <div class="flex flex-col gap-4 pt-4">
+ <template v-if="!ssoConfig && !showForm">
+ <div class="text-center py-6 text-muted">
+ <p>{{ t('sso.noConfig') }}</p>
+ <UButton
+ :label="t('sso.configure')"
+ class="mt-3"
+ @click="showForm = true"
+ />
+ </div>
+ </template>
+
+ <template v-else-if="ssoConfig && !showForm">
+ <div class="flex flex-col gap-3">
+ <div class="flex items-center justify-between p-3 rounded-md bg-elevated">
+ <div>
+ <p class="text-sm font-medium">{{ ssoConfig.displayName }}</p>
+ <p class="text-xs text-dimmed">
+ ID {{ ssoConfig.id }} &middot; {{ ssoConfig.protocol.toUpperCase() }} &middot; {{ ssoConfig.emailDomainRestriction }}
+ </p>
+ </div>
+ <div class="flex items-center gap-2">
+ <UBadge :color="ssoConfig.enabled ? 'success' : 'neutral'">
+ {{ ssoConfig.enabled ? t('sso.enabled') : t('sso.disabled') }}
+ </UBadge>
+ <UButton
+ icon="i-lucide-pencil"
+ size="xs"
+ variant="ghost"
+ @click="editConfig"
+ />
+ <UButton
+ icon="i-lucide-trash-2"
+ size="xs"
+ variant="ghost"
+ color="error"
+ @click="deleteConfig"
+ />
+ </div>
+ </div>
+
+ <div class="flex flex-col gap-1 p-3 rounded-md bg-elevated">
+ <p class="text-xs text-dimmed">{{ t('sso.callbackUrlLabel') }}</p>
+ <div class="flex items-center gap-2">
+ <code class="text-xs flex-1 break-all">{{ activeCallbackUrl }}</code>
+ <UButton
+ icon="i-lucide-copy"
+ size="xs"
+ variant="ghost"
+ @click="copyCallbackUrl"
+ />
+ </div>
+ </div>
+ </div>
+ </template>
+
+ <template v-if="showForm">
+ <UFormField :label="t('sso.protocol')">
+ <USelect
+ v-model="form.protocol"
+ :items="protocolOptions"
+ class="w-full"
+ />
+ </UFormField>
+
+ <UFormField :label="t('sso.displayName')">
+ <UInput
+ v-model="form.displayName"
+ :placeholder="t('sso.displayNamePlaceholder')"
+ class="w-full"
+ />
+ </UFormField>
+
+ <UFormField :label="t('sso.emailDomain')">
+ <UInput
+ v-model="form.emailDomainRestriction"
+ placeholder="company.com"
+ class="w-full"
+ />
+ </UFormField>
+
+ <template v-if="form.protocol === 'saml'">
+ <UFormField :label="t('sso.metadataUrl')">
+ <div class="flex gap-2">
+ <UInput
+ v-model="metadataUrl"
+ placeholder="https://idp.example.com/saml/metadata"
+ class="flex-1"
+ />
+ <UButton
+ :label="t('sso.sync')"
+ :loading="syncing"
+ icon="i-lucide-refresh-cw"
+ variant="outline"
+ @click="syncMetadata"
+ />
+ </div>
+ </UFormField>
+ <UFormField :label="t('sso.samlEntryPoint')">
+ <UInput
+ v-model="form.samlEntryPoint"
+ placeholder="https://idp.example.com/saml/sso"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField :label="t('sso.samlIssuer')">
+ <UInput
+ v-model="form.samlIssuer"
+ placeholder="taskview"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField :label="t('sso.samlCert')">
+ <UTextarea
+ v-model="form.samlCert"
+ :placeholder="t('sso.samlCertPlaceholder')"
+ :rows="4"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField :label="t('sso.samlCallbackUrl')">
+ <UInput
+ v-model="form.samlCallbackUrl"
+ :placeholder="callbackUrlPlaceholder"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField :label="t('sso.samlLogoutUrl')">
+ <UInput
+ v-model="form.samlLogoutUrl"
+ placeholder="https://idp.example.com/saml/logout"
+ class="w-full"
+ />
+ </UFormField>
+ <UCollapsible>
+ <UButton
+ class="group"
+ :label="t('sso.requestSigning')"
+ color="neutral"
+ variant="ghost"
+ trailing-icon="i-lucide-chevron-down"
+ :ui="{
+ trailingIcon: 'group-data-[state=open]:rotate-180 transition-transform duration-200'
+ }"
+ size="sm"
+ />
+ <template #content>
+ <div class="flex flex-col gap-4 pt-2">
+ <UAlert
+ color="info"
+ icon="i-lucide-shield"
+ :title="t('sso.requestSigningDescription')"
+ />
+ <UAlert
+ color="neutral"
+ icon="i-lucide-terminal"
+ :title="t('sso.generateKeysTitle')"
+ :description="t('sso.generateKeysHint')"
+ >
+ <template #actions>
+ <UButton
+ icon="i-lucide-copy"
+ size="xs"
+ variant="ghost"
+ @click="copyOpenSslCommand"
+ />
+ </template>
+ </UAlert>
+ <UFormField :label="t('sso.samlSigningKey')">
+ <UTextarea
+ v-model="form.samlSigningKey"
+ :placeholder="t('sso.samlSigningKeyPlaceholder')"
+ :rows="4"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField :label="t('sso.samlSigningCert')">
+ <UTextarea
+ v-model="form.samlSigningCert"
+ :placeholder="t('sso.samlSigningCertPlaceholder')"
+ :rows="4"
+ class="w-full"
+ />
+ </UFormField>
+ </div>
+ </template>
+ </UCollapsible>
+ </template>
+
+ <template v-if="form.protocol === 'oidc'">
+ <UFormField :label="t('sso.oidcIssuer')">
+ <UInput
+ v-model="form.oidcIssuer"
+ placeholder="https://accounts.google.com"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField :label="t('sso.oidcClientId')">
+ <UInput
+ v-model="form.oidcClientId"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField :label="t('sso.oidcClientSecret')">
+ <UInput
+ v-model="form.oidcClientSecret"
+ type="password"
+ class="w-full"
+ />
+ </UFormField>
+ <UFormField :label="t('sso.oidcCallbackUrl')">
+ <UInput
+ v-model="form.oidcCallbackUrl"
+ :placeholder="callbackUrlPlaceholder"
+ class="w-full"
+ />
+ </UFormField>
+ </template>
+
+ <div class="flex gap-2">
+ <UButton
+ :label="isEditing ? t('sso.save') : t('sso.create')"
+ :loading="saving"
+ @click="saveConfig"
+ />
+ <UButton
+ :label="t('sso.cancel')"
+ variant="ghost"
+ color="neutral"
+ @click="cancelForm"
+ />
+ </div>
+ </template>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { ref, reactive, computed, watch, onMounted } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { storeToRefs } from 'pinia'
+import { $tvApi } from '@/plugins/axios'
+import { additionalUrlStore } from '@/stores/additional-url.store'
+import { useAdditionalServer } from '@/composables/useAdditionalServer'
+import type { SsoConfig } from 'taskview-api/src/api/sso.types'
+
+const props = defineProps<{
+ organizationId: number
+}>()
+
+const { t } = useI18n()
+const toast = useToast()
+const { mainServer } = storeToRefs(additionalUrlStore())
+
+const ssoConfig = ref<SsoConfig | null>(null)
+const showForm = ref(false)
+const saving = ref(false)
+const syncing = ref(false)
+const isEditing = ref(false)
+const metadataUrl = ref('')
+
+const form = reactive({
+ protocol: 'saml' as 'saml' | 'oidc',
+ displayName: '',
+ emailDomainRestriction: '',
+ samlEntryPoint: '',
+ samlIssuer: '',
+ samlCert: '',
+ samlCallbackUrl: '',
+ samlSigningKey: '',
+ samlSigningCert: '',
+ samlLogoutUrl: '',
+ oidcIssuer: '',
+ oidcClientId: '',
+ oidcClientSecret: '',
+ oidcCallbackUrl: '',
+})
+
+const protocolOptions = [
+ { label: 'SAML 2.0', value: 'saml' },
+ { label: 'OpenID Connect', value: 'oidc' },
+]
+
+const apiBaseUrl = computed(() => mainServer.value || window.location.origin)
+
+const callbackUrlPlaceholder = computed(() => {
+ const configId = ssoConfig.value?.id ?? '{id}'
+ return `${apiBaseUrl.value}/module/sso/callback/${configId}`
+})
+
+const activeCallbackUrl = computed(() => {
+ if (!ssoConfig.value) return ''
+ return `${apiBaseUrl.value}/module/sso/callback/${ssoConfig.value.id}`
+})
+
+async function syncMetadata() {
+ if (!metadataUrl.value.trim()) {
+ toast.add({ title: t('sso.metadataUrlRequired'), color: 'warning' })
+ return
+ }
+
+ syncing.value = true
+
+ try {
+ const result = await $tvApi.sso.parseMetadata(metadataUrl.value.trim())
+ if (result.samlEntryPoint) form.samlEntryPoint = result.samlEntryPoint
+ if (result.samlCert) form.samlCert = result.samlCert
+ if (result.samlLogoutUrl) form.samlLogoutUrl = result.samlLogoutUrl
+ toast.add({ title: t('sso.metadataSynced'), color: 'success' })
+ } catch {
+ toast.add({ title: t('sso.metadataSyncFailed'), color: 'error' })
+ } finally {
+ syncing.value = false
+ }
+}
+
+async function copyToClipboard(text: string) {
+ try {
+ await navigator.clipboard.writeText(text)
+ toast.add({ title: t('sso.copied'), color: 'success' })
+ } catch {
+ toast.add({ title: t('sso.copyFailed'), color: 'error' })
+ }
+}
+
+function copyCallbackUrl() {
+ copyToClipboard(activeCallbackUrl.value)
+}
+
+function copyOpenSslCommand() {
+ copyToClipboard('openssl req -x509 -newkey rsa:2048 -keyout sp-key.pem -out sp-cert.pem -days 3650 -nodes -subj "/CN=taskview"')
+}
+
+onMounted(async () => {
+ await useAdditionalServer()
+})
+
+watch(() => props.organizationId, () => {
+ fetchConfig()
+}, { immediate: true })
+
+async function fetchConfig() {
+ try {
+ const configs = await $tvApi.sso.listConfigs(props.organizationId)
+ ssoConfig.value = configs.length > 0 ? configs[0] : null
+ } catch {
+ ssoConfig.value = null
+ }
+}
+
+function editConfig() {
+ if (!ssoConfig.value) return
+ isEditing.value = true
+ showForm.value = true
+ form.protocol = ssoConfig.value.protocol
+ form.displayName = ssoConfig.value.displayName
+ form.emailDomainRestriction = ssoConfig.value.emailDomainRestriction
+ form.samlEntryPoint = ssoConfig.value.samlEntryPoint ?? ''
+ form.samlIssuer = ssoConfig.value.samlIssuer ?? ''
+ form.samlCert = ssoConfig.value.samlCert ?? ''
+ form.samlCallbackUrl = ssoConfig.value.samlCallbackUrl ?? ''
+ form.samlSigningKey = ssoConfig.value.samlSigningKey ?? ''
+ form.samlSigningCert = ssoConfig.value.samlSigningCert ?? ''
+ form.samlLogoutUrl = ssoConfig.value.samlLogoutUrl ?? ''
+ form.oidcIssuer = ssoConfig.value.oidcIssuer ?? ''
+ form.oidcClientId = ssoConfig.value.oidcClientId ?? ''
+ form.oidcClientSecret = ssoConfig.value.oidcClientSecret ?? ''
+ form.oidcCallbackUrl = ssoConfig.value.oidcCallbackUrl ?? ''
+}
+
+function cancelForm() {
+ showForm.value = false
+ isEditing.value = false
+ resetForm()
+}
+
+function resetForm() {
+ form.protocol = 'saml'
+ form.displayName = ''
+ form.emailDomainRestriction = ''
+ form.samlEntryPoint = ''
+ form.samlIssuer = ''
+ form.samlCert = ''
+ form.samlCallbackUrl = ''
+ form.samlSigningKey = ''
+ form.samlSigningCert = ''
+ form.samlLogoutUrl = ''
+ form.oidcIssuer = ''
+ form.oidcClientId = ''
+ form.oidcClientSecret = ''
+ form.oidcCallbackUrl = ''
+}
+
+async function saveConfig() {
+ if (!form.displayName || !form.emailDomainRestriction) {
+ toast.add({ title: t('sso.fillRequired'), color: 'warning' })
+ return
+ }
+
+ saving.value = true
+
+ try {
+ if (isEditing.value && ssoConfig.value) {
+ const { protocol: _protocol, ...updatePayload } = form
+ await $tvApi.sso.updateConfig(ssoConfig.value.id, updatePayload)
+ toast.add({ title: t('sso.updated'), color: 'success' })
+ } else {
+ await $tvApi.sso.createConfig({
+ organizationId: props.organizationId,
+ ...form,
+ })
+ toast.add({ title: t('sso.created'), color: 'success' })
+ }
+
+ showForm.value = false
+ isEditing.value = false
+ resetForm()
+ await fetchConfig()
+ } catch (error) {
+ console.error('SSO save failed:', error)
+ toast.add({ title: t('sso.saveFailed'), color: 'error' })
+ } finally {
+ saving.value = false
+ }
+}
+
+async function deleteConfig() {
+ if (!ssoConfig.value) return
+
+ try {
+ await $tvApi.sso.deleteConfig(ssoConfig.value.id)
+ ssoConfig.value = null
+ toast.add({ title: t('sso.deleted'), color: 'success' })
+ } catch {
+ toast.add({ title: t('sso.deleteFailed'), color: 'error' })
+ }
+}
+</script>
diff --git a/web/src/composables/useAppRouteInfo.ts b/web/src/composables/useAppRouteInfo.ts
index d4dbeb9..7cc2a8c 100644
--- a/web/src/composables/useAppRouteInfo.ts
+++ b/web/src/composables/useAppRouteInfo.ts
@@ -3,6 +3,7 @@ import { useRoute } from 'vue-router'
export const useAppRouteInfo = () => {
const route = useRoute()
+ const orgSlug = computed(() => String(route.params.orgSlug || ''))
const isUserRoute = computed(() => route.name === 'user')
const isAccountRoute = computed(() => route.name === 'account')
const projectId = computed(() => Number(route.params.projectId) || -1)
@@ -12,6 +13,7 @@ export const useAppRouteInfo = () => {
const taskId = computed(() => Number(route.params.taskId) || -1)
return {
+ orgSlug,
isUserRoute,
isAccountRoute,
hasProject,
diff --git a/web/src/composables/useOrgPermissions.ts b/web/src/composables/useOrgPermissions.ts
new file mode 100644
index 0000000..7550ba8
--- /dev/null
+++ b/web/src/composables/useOrgPermissions.ts
@@ -0,0 +1,17 @@
+import { computed } from 'vue'
+import type { Organization } from 'taskview-api'
+
+export function useOrgPermissions(orgRef: () => Organization | null | undefined) {
+ const currentUserRole = computed(() => orgRef()?.currentUserRole ?? 'member')
+
+ const isOwner = computed(() => currentUserRole.value === 'owner')
+ const isAdmin = computed(() => currentUserRole.value === 'owner' || currentUserRole.value === 'admin')
+ const isMember = computed(() => currentUserRole.value === 'member')
+
+ return {
+ currentUserRole,
+ isOwner,
+ isAdmin,
+ isMember,
+ }
+}
diff --git a/web/src/composables/useProjectDataLoader.ts b/web/src/composables/useProjectDataLoader.ts
index 9680275..c8faf56 100644
--- a/web/src/composables/useProjectDataLoader.ts
+++ b/web/src/composables/useProjectDataLoader.ts
@@ -11,6 +11,7 @@ export function useProjectDataLoader(projectId: Ref<number>) {
const tagsStore = useTagsStore()
tagsStore.fetchAllTags()
+ collaborationStore.fetchAllCollaborationUsers()
watch(projectId, (id) => {
if (id > 0) {
diff --git a/web/src/composables/usePushNotifications.ts b/web/src/composables/usePushNotifications.ts
index 0f69b76..6717920 100644
--- a/web/src/composables/usePushNotifications.ts
+++ b/web/src/composables/usePushNotifications.ts
@@ -3,6 +3,7 @@ import { Capacitor } from '@capacitor/core'
import { FirebaseMessaging } from '@capacitor-firebase/messaging'
import { $tvApi } from '@/plugins/axios'
import { useNotificationsStore } from '@/stores/notifications.store'
+import { useOrganizationStore } from '@/stores/organization.store'
import { useRouter } from 'vue-router'
import { ALL_TASKS_LIST_ID } from 'taskview-api'
@@ -43,9 +44,17 @@ export function usePushNotifications() {
FirebaseMessaging.addListener('notificationActionPerformed', (action) => {
const data = action.notification.data as Record<string, string> | undefined
if (data?.taskId && data?.goalId) {
+ const orgStore = useOrganizationStore()
+ if (data.organizationId) {
+ const org = orgStore.organizations.find(o => o.id === Number(data.organizationId))
+ if (org && org.id !== orgStore.currentOrg?.id) {
+ orgStore.setCurrentOrg(org)
+ }
+ }
router.push({
name: 'user',
params: {
+ orgSlug: orgStore.currentOrgSlug,
projectId: data.goalId,
listId: data.goalListId || ALL_TASKS_LIST_ID,
taskId: data.taskId,
diff --git a/web/src/layouts/UserLayout.vue b/web/src/layouts/UserLayout.vue
index fb3b452..40e21c7 100644
--- a/web/src/layouts/UserLayout.vue
+++ b/web/src/layouts/UserLayout.vue
@@ -15,7 +15,7 @@
>
<div class="flex items-center justify-between px-1 gap-2">
<TvGoalLikeItem
- to="/user"
+ :to="{ name: 'user' }"
variant="taskview"
class="flex-1"
>
@@ -72,7 +72,7 @@ watch(
if (!initialized || !projectId) return
const exists = goals.some((g) => g.id === Number(projectId))
if (!exists) {
- router.replace(`/${userStore.login}`)
+ router.replace({ name: 'user' })
}
},
)
@@ -104,8 +104,23 @@ onMounted(async () => {
connectCentrifugo()
initPush()
- await orgStore.fetchOrganizations()
- orgStore.restoreCurrentOrg()
+ if (!orgStore.organizations.length) {
+ await orgStore.fetchOrganizations()
+ }
+
+ const slugFromUrl = route.params.orgSlug as string
+ const matchedOrg = orgStore.findOrgBySlug(slugFromUrl)
+ if (matchedOrg) {
+ orgStore.setCurrentOrg(matchedOrg)
+ orgStore.initialized = true
+ } else {
+ orgStore.restoreCurrentOrg()
+ if (orgStore.currentOrg) {
+ router.replace({ name: 'user', params: { orgSlug: orgStore.currentOrgSlug } })
+ return
+ }
+ }
+
await goalsStore.fetchGoals()
await CapacitorUpdater.notifyAppReady()
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index d635878..2dafdfe 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -72,6 +72,12 @@ export default {
failedToResendCode: 'Failed to resend code',
failedToSendResetLink: 'Failed to send reset link. Please try again.',
+ // SSO
+ ssoSignIn: 'Sign in with SSO',
+ ssoNotFound: 'SSO not configured',
+ ssoNotFoundDescription: 'No SSO provider found for domain {domain}',
+ ssoError: 'SSO authentication failed. Please try again.',
+
// Validation
invalidEmail: 'Invalid email address',
loginRequired: 'Login is required',
@@ -478,6 +484,51 @@ export default {
roleUpdated: 'Role updated',
slugTaken: 'This slug is already taken',
},
+ sso: {
+ noConfig: 'SSO is not configured for this organization',
+ configure: 'Configure SSO',
+ protocol: 'Protocol',
+ displayName: 'Provider name',
+ displayNamePlaceholder: 'e.g. Okta, Azure AD',
+ emailDomain: 'Email domain',
+ metadataUrl: 'IdP Metadata URL',
+ metadataUrlRequired: 'Enter metadata URL',
+ metadataSynced: 'Metadata synced successfully',
+ metadataSyncFailed: 'Failed to sync metadata',
+ sync: 'Sync',
+ samlEntryPoint: 'IdP SSO URL',
+ samlIssuer: 'SP Entity ID',
+ samlCert: 'IdP Certificate',
+ samlCertPlaceholder: 'Paste the IdP public certificate (PEM format)',
+ samlCallbackUrl: 'ACS URL (Callback)',
+ samlLogoutUrl: 'IdP Logout URL (SLO)',
+ requestSigning: 'Request signing (enterprise)',
+ requestSigningDescription: 'Sign SAML AuthnRequests with a private key. Required by some IdPs for enhanced security.',
+ generateKeysTitle: 'openssl req -x509 -newkey rsa:2048 -keyout sp-key.pem -out sp-cert.pem -days 3650 -nodes -subj "/CN=taskview"',
+ generateKeysHint: 'sp-key.pem → Private Key field. sp-cert.pem → Certificate field + upload to IdP.',
+ samlSigningKey: 'SP Private Key (PEM)',
+ samlSigningKeyPlaceholder: 'Paste PEM private key (-----BEGIN PRIVATE KEY-----...)',
+ samlSigningCert: 'SP Certificate (PEM)',
+ samlSigningCertPlaceholder: 'Paste PEM certificate (-----BEGIN CERTIFICATE-----...)',
+ oidcIssuer: 'Issuer URL',
+ oidcClientId: 'Client ID',
+ oidcClientSecret: 'Client Secret',
+ oidcCallbackUrl: 'Callback URL',
+ enabled: 'Enabled',
+ disabled: 'Disabled',
+ callbackUrlLabel: 'Callback URL (use this in your IdP)',
+ copied: 'Copied to clipboard',
+ copyFailed: 'Failed to copy',
+ create: 'Create',
+ save: 'Save',
+ cancel: 'Cancel',
+ created: 'SSO provider created',
+ updated: 'SSO provider updated',
+ deleted: 'SSO provider deleted',
+ saveFailed: 'Failed to save SSO configuration',
+ deleteFailed: 'Failed to delete SSO configuration',
+ fillRequired: 'Please fill in all required fields',
+ },
apiTokens: {
title: 'API Tokens',
description: 'Create tokens to access the API programmatically.',
diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.ts
index 463c186..e163fcc 100644
--- a/web/src/locales/ru.ts
+++ b/web/src/locales/ru.ts
@@ -72,6 +72,12 @@ export default {
failedToResendCode: 'Не удалось отправить код повторно',
failedToSendResetLink: 'Не удалось отправить ссылку. Попробуйте снова.',
+ // SSO
+ ssoSignIn: 'Войти через SSO',
+ ssoNotFound: 'SSO не настроен',
+ ssoNotFoundDescription: 'Для домена {domain} не настроен SSO провайдер',
+ ssoError: 'Ошибка SSO авторизации. Попробуйте снова.',
+
// Validation
invalidEmail: 'Неверный email адрес',
loginRequired: 'Введите логин',
@@ -450,6 +456,51 @@ export default {
roleUpdated: 'Роль обновлена',
slugTaken: 'Этот slug уже занят',
},
+ sso: {
+ noConfig: 'SSO не настроен для этой организации',
+ configure: 'Настроить SSO',
+ protocol: 'Протокол',
+ displayName: 'Название провайдера',
+ displayNamePlaceholder: 'например Okta, Azure AD',
+ emailDomain: 'Домен email',
+ metadataUrl: 'URL метаданных IdP',
+ metadataUrlRequired: 'Укажите URL метаданных',
+ metadataSynced: 'Метаданные синхронизированы',
+ metadataSyncFailed: 'Не удалось синхронизировать метаданные',
+ sync: 'Синхр.',
+ samlEntryPoint: 'URL входа IdP',
+ samlIssuer: 'SP Entity ID',
+ samlCert: 'Сертификат IdP',
+ samlCertPlaceholder: 'Вставьте публичный сертификат IdP (формат PEM)',
+ samlCallbackUrl: 'ACS URL (Callback)',
+ samlLogoutUrl: 'URL выхода IdP (SLO)',
+ requestSigning: 'Подпись запросов (enterprise)',
+ requestSigningDescription: 'Подписывать SAML AuthnRequest приватным ключом. Требуется некоторыми IdP для повышенной безопасности.',
+ generateKeysTitle: 'openssl req -x509 -newkey rsa:2048 -keyout sp-key.pem -out sp-cert.pem -days 3650 -nodes -subj "/CN=taskview"',
+ generateKeysHint: 'sp-key.pem → поле Private Key. sp-cert.pem → поле Certificate + загрузить в IdP.',
+ samlSigningKey: 'Приватный ключ SP (PEM)',
+ samlSigningKeyPlaceholder: 'Вставьте PEM приватный ключ (-----BEGIN PRIVATE KEY-----...)',
+ samlSigningCert: 'Сертификат SP (PEM)',
+ samlSigningCertPlaceholder: 'Вставьте PEM сертификат (-----BEGIN CERTIFICATE-----...)',
+ oidcIssuer: 'URL издателя',
+ oidcClientId: 'Client ID',
+ oidcClientSecret: 'Client Secret',
+ oidcCallbackUrl: 'Callback URL',
+ enabled: 'Включён',
+ disabled: 'Выключен',
+ callbackUrlLabel: 'Callback URL (укажи в настройках IdP)',
+ copied: 'Скопировано',
+ copyFailed: 'Не удалось скопировать',
+ create: 'Создать',
+ save: 'Сохранить',
+ cancel: 'Отмена',
+ created: 'SSO провайдер создан',
+ updated: 'SSO провайдер обновлён',
+ deleted: 'SSO провайдер удалён',
+ saveFailed: 'Не удалось сохранить настройки SSO',
+ deleteFailed: 'Не удалось удалить SSO конфигурацию',
+ fillRequired: 'Заполните все обязательные поля',
+ },
notifications: {
title: 'Уведомления',
empty: 'Нет уведомлений',
diff --git a/web/src/main.ts b/web/src/main.ts
index 38fa068..834bf84 100644
--- a/web/src/main.ts
+++ b/web/src/main.ts
@@ -40,7 +40,7 @@ const router = createRouter({
component: () => import('./pages/reset-password.vue'),
},
{
- path: '/:user',
+ path: '/:orgSlug',
component: () => import('./layouts/UserLayout.vue'),
beforeEnter: [authenticated],
children: [
diff --git a/web/src/pages/login.vue b/web/src/pages/login.vue
index 39715fc..38313de 100644
--- a/web/src/pages/login.vue
+++ b/web/src/pages/login.vue
@@ -8,6 +8,7 @@
<script setup lang="ts">
import { onMounted } from 'vue'
+import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { App } from '@capacitor/app'
import { Browser } from '@capacitor/browser'
@@ -26,8 +27,10 @@ type LoginResponse = {
refresh: string
}
+const { t } = useI18n()
const route = useRoute()
const router = useRouter()
+const toast = useToast()
async function loginByCode(code: string, email: string) {
const result = await $api.post<LoginResponse>('/module/auth/login-by-code', { code, email })
@@ -48,6 +51,15 @@ onMounted(async () => {
return
}
+ // Handle SSO error redirect
+ if (route.query.sso_error) {
+ toast.add({
+ title: t('auth.error'),
+ description: t('auth.ssoError'),
+ color: 'error',
+ })
+ }
+
// Handle OAuth callback tokens from URL
try {
const tokens = route.query.tokens as string
diff --git a/web/src/stores/organization.store.ts b/web/src/stores/organization.store.ts
index 4eb8ac8..c159cba 100644
--- a/web/src/stores/organization.store.ts
+++ b/web/src/stores/organization.store.ts
@@ -1,5 +1,5 @@
import { defineStore } from 'pinia'
-import { ref } from 'vue'
+import { ref, computed } from 'vue'
import type { Organization, OrgMember } from 'taskview-api'
import { $tvApi } from '@/plugins/axios'
@@ -10,6 +10,12 @@ export const useOrganizationStore = defineStore('organization', () => {
const loading = ref(false)
const initialized = ref(false)
+ const currentOrgSlug = computed(() => currentOrg.value?.slug ?? '')
+
+ function findOrgBySlug(slug: string) {
+ return organizations.value.find(o => o.slug === slug) ?? null
+ }
+
async function fetchOrganizations() {
loading.value = true
try {
@@ -132,9 +138,11 @@ export const useOrganizationStore = defineStore('organization', () => {
return {
organizations,
currentOrg,
+ currentOrgSlug,
members,
loading,
initialized,
+ findOrgBySlug,
fetchOrganizations,
createOrganization,
updateOrganization,