* theming improvements * border style improvements * refactor: migrate org routes to server-side data fetching Move client-side API calls to server-side load functions for better performance, security, and SEO. Implement permission-based course filtering * refactor: clean up course and community components This commit removes unused components and files related to courses and community features, streamlining the codebase. It also updates various routes to enhance performance and maintainability. Additionally, it introduces new types and constants for better type safety and organization. * refactor: fix video formatting on website and other styles * refactor: update course and dashboard components for improved styling and functionality * more icon improvements * refactor: streamline course and dashboard components This commit updates various course and dashboard components for improved styling and functionality. It includes the removal of unused files, updates to imports and exports, and enhancements to type safety. Additionally, it introduces new routes and optimizes existing ones for better performance and maintainability. * refactor: enhance lesson completion logic * chore: delete all emails on dashboard and move other api routes to backend. move all emails to the backend and * feat: Refactor API and database queries for courses, quizzes, and lessons, migrating Supabase functions and schema management. * get app loading * fix ui and build error of cio/api * refactor: move direct database queries to query layer - Create query functions: getCourseWithOrgData, getOrganizationByCourseId, updateCourseVersion, updateLessonsSectionId, getProfileByGroupMemberId, getQuestionTypesByIds - Refactor services to use query functions instead of direct db queries - Add transaction support to updateCourseVersion and updateLessonsSectionId - Fix getProfileByGroupMemberId to return profile directly (not nested) - Fix updateLessonsSectionId to use .returning() instead of rowCount This aligns services with architecture pattern where services orchestrate queries rather than executing them directly. * exercise saving improvements * fix and optimise exercise creation * refactor: update dialog components for improved styling and functionality - Adjusted dialog content width and maximum constraints for better responsiveness. - Changed heading font size for consistency in the new exercise modal. - Replaced CloseIcon with CrossIcon for a more modern appearance in dialog close button. * refactor: enhance course and exercise management components - Introduced new components for exercise creation, editing, and viewing, improving user experience. - Refactored existing lesson and exercise components for better organization and maintainability. - Updated routing for exercises and lessons to streamline navigation within the course structure. - Added new utility functions and constants to support content management across the application. * feat: implement course content management API and UI components - Added new API routes for updating and deleting course content, enhancing content management capabilities. - Introduced new Svelte components for displaying and managing course content, including content lists and action handlers. - Updated existing course routing to integrate new content management features. - Refactored content-related utility functions for improved organization and maintainability. * refactor: remove Supabase references and implement course section management - Removed Supabase-related environment variables and Dockerfile arguments to streamline configuration. - Introduced a new section management API with routes for creating, updating, deleting, and reordering course sections. - Updated course services to handle section operations, ensuring consistency in course content management. - Refactored existing lesson section logic to align with the new course section structure, enhancing maintainability. * chore: update .prettierignore to exclude additional file types - Added exclusions for SQL and environment files to the Prettier ignore list. - Included Dockerfile and .prettierignore itself to prevent formatting issues. * feat: enhance course content management with translation support and UI improvements - Added translation keys for user-facing text in course-related components, ensuring all UI copy is sourced from translation files. - Updated lesson and exercise creation components to utilize translation keys for success and error messages, improving localization. - Refactored course content management components to streamline the creation and editing process, enhancing user experience. - Introduced new constants for content options and stepper states to standardize component behavior and improve maintainability. - Improved styling and functionality of course content modals and steppers for better user interaction. * feat: enhance course content management and UI components - Updated .prettierignore to exclude storybook-static directory. - Improved exercise creation logic by refining option handling and adding UUID support for option values. - Enhanced navigation component with debugging output for custom links. - Introduced a new method in CourseApi to update content items locally, improving state management during navigation. - Added caching for exercise templates by tag in ExerciseTemplateApi to optimize performance. - Refactored lesson and exercise components for better organization and maintainability, including updates to modal styling and functionality. - Implemented local patching for lesson and exercise list items to ensure UI consistency after updates. * student + teacher invite (not fully tested) * refactor: streamline course team member middleware - Removed unnecessary console logging and timing for checking user permissions. - Simplified the logic for determining if a user is a course team member or organization admin. * reorder course sidebar to move content to its own page. * feat: implement unified course enrollment route and API - Introduced a new enrollment route `/course/:slug/enroll` to replace the previous invite system. - Unified enrollment logic for free and paid courses, allowing direct enrollment for free courses and invite token validation for paid courses. - Updated course landing page to redirect to the new enrollment route for free courses. - Removed obsolete invite routes and related logic, streamlining the enrollment process. - Enhanced API with a new `POST /course/:courseId/enroll` endpoint for handling enrollments. - Added rate limiting for enrollment requests to prevent abuse. - Updated UI components to reflect changes in enrollment flow and messaging. * chore: update docker stack, docs, and auth token automation * chore: make prettier check ignore unknown file types * fix: avoid using authClient on server file and keep authClient client focused * chore: always get the server on demand depending on the environment * chore: update dashboard configuration and Docker setup for environment variables - Modified the Svelte configuration to directly use the PUBLIC_SERVER_URL environment variable. - Enhanced the Docker Compose file to include health check formatting and added environment variable arguments for the dashboard build. - Updated the Dockerfile to echo environment variable values during the build process, ensuring clarity on the configuration being used. * chore: enhance Docker setup and documentation for production deployment - Added a new production Docker Compose file and example environment file for published images. - Updated README and usage documentation to include instructions for deploying with production images. - Modified Svelte configuration to standardize the use of the posthog domain. - Removed unnecessary console logs from the API client and layout server files for cleaner output. - Improved overall clarity in Docker documentation regarding self-hosting and image publishing. * chore(db): log function name in query catch blocks (console.error 'funcName error:', error) Co-authored-by: Cursor <[email protected]> * fix: multiple refresh issue * fix: server key not passed to api * fix: clarify usage of PRIVATE_SERVER_KEY and AUTH_BEARER_TOKEN in documentation - Updated documentation to specify that PRIVATE_SERVER_KEY is used for server-to-server API key authentication and is validated by API key middleware. - Clarified that AUTH_BEARER_TOKEN is a separate token not utilized by apiKeyMiddleware. - Adjusted examples in Docker setup and self-hosting documentation to reflect these changes. * fix migration script * fix: improve language handling and add database reset script - Updated language extraction to handle potential undefined values, defaulting to 'en' if necessary. - Added a new script for resetting the database, including functionality to truncate public tables and run setup with optional seeding. * feat: add promote ungrouped section functionality and enhance document handling in dashboard - Implemented a new API endpoint to promote synthetic "Ungrouped" content into a real persisted section, allowing for better organization of course materials. - Updated the dashboard to include a new component for displaying content count badges for lessons and exercises. - Enhanced document management features, including a new document card component with dropdown actions for viewing, downloading, and removing documents. - Improved file upload handling with a dedicated file drop zone and error handling for file type and size restrictions. - Refactored existing components for better readability and maintainability, including updates to lesson and document lists. * chore: use root env file for docker compose * docs: document docker no-build startup flow * chore: add no-build option to docker full stack script * fix(email): handle SMTP TLS mode by port * feat(auth): add configurable cookie domain env and docs * apps/dashboard/src/lib/utils/services/auth/session.ts * fix(email): make sender configurable via SMTP_SENDER * chore(i18n): regenerate locale translations and support language targeting * chore(config): switch api to PUBLIC_SERVER_URL * fix(i18n): persist selected locale across navigation * feat(assets): implement organization asset management routes and services - Added new routes for managing organization assets, including listing, creating, updating, deleting, and exporting assets. - Introduced asset-related services for handling asset operations such as creation, retrieval, and deletion. - Integrated YouTube metadata resolution and asset attachment/detachment functionalities. - Updated organization routes to include the new asset management routes. - Enhanced error handling for asset-related operations. * fix(document-list): update conditional rendering for edit mode in document list * debug self hosted layout setup * refactor(sidebar): simplify lms sidebar footer and improve navigation item rendering * feat: tags * chore: tags roadmap + translations * fix(api): add authMiddleware to exercise, invites, and content routers - exerciseRouter: apply authMiddleware before courseMemberMiddleware on all 10 routes - invitesRouter: apply authMiddleware before courseTeamMemberMiddleware on all 4 routes - contentRouter: add authMiddleware to PUT route (DELETE already had it) Both courseMemberMiddleware and courseTeamMemberMiddleware document requiring authMiddleware to be applied first. This aligns with lessonRouter pattern and ensures explicit middleware contract regardless of global session middleware. Co-authored-by: Rotimi Best <[email protected]> * fix(course): use courseTeamMemberMiddleware for PUT, DELETE, and analytics routes These routes require admin/tutor role per JSDoc but were using courseMemberMiddleware which allows any course member including students. Switch to courseTeamMemberMiddleware to restrict access to ADMIN/TUTOR group members and org admins. Co-authored-by: Rotimi Best <[email protected]> * chore: unify pricing component between dashboard and website (#630) * feat: modularize pricing card * feat: initia implementation of pricing togge * fix: minor amendment * refactor: update pricing components for improved layout and styling - Adjusted spacing in the pricing card layout for better visual consistency. - Modified button styles and sizes for enhanced usability. - Cleaned up the pricing toggle component by removing unnecessary console logs and restructuring the button rendering logic. * add handle click * chore(css): update Tailwind CSS output with new utility classes and theme variables * fix(api): enable orgMemberMiddleware for stats route This change ensures that the stats route is protected by orgMemberMiddleware, aligning access control with other routes. Additionally, removed unnecessary console log from the layout server file to clean up the code. --------- Co-authored-by: Rotimi Best <[email protected]> * pass query parameter to signup from pricing page * ui updates to pricing cards * commit all PRDs * add open api spec to api prd * make blue default theme * more prds * sync option id sequence on question update * docs: more classroomio features * chore: more ui improvements * docs: new component docs * chore: CSP Configuration (#638) * feat(validation): add GitHub repository name validation - Add ZRepositoryName schema for validating GitHub repo names - Add ZRepositoryOwner for owner/username validation - Add ZRepositoryIdentifier for owner/repo format - Follow GitHub rules: A-Za-z0-9_.-, 1-100 chars, reserved names - Add translation keys for validation messages Fixes #637 Co-authored-by: Rotimi Best <[email protected]> * Revert "feat(validation): add GitHub repository name validation" This reverts commit 3436536bb17a0f05b3a9fe8dd7682cde64dd1dce. * feat(dashboard): make CSP external domains configurable via env Move hardcoded external domains from svelte.config.js to .env configuration for on-premise deployments with strict security policies, data residency constraints, or CISO-driven allowlists. - ALLOWED_EXTERNAL_DOMAINS: single list for all CSP directives - CSP_SCRIPT_SRC_DOMAINS, CSP_STYLE_SRC_DOMAINS, CSP_CONNECT_SRC_DOMAINS, CSP_FRAME_SRC_DOMAINS, CSP_FONT_SRC_DOMAINS: per-directive override - When unset, defaults retain current SaaS behavior (backward compatible) Fixes #637 Co-authored-by: Rotimi Best <[email protected]> * fix(dashboard): self-hosted CSP uses only env vars, no defaults Co-authored-by: Rotimi Best <[email protected]> * fix(dashboard): add all classroomio.com domains to CSP defaults Co-authored-by: Rotimi Best <[email protected]> * docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides Co-authored-by: Rotimi Best <[email protected]> * feat(docker): pass CSP domain env vars as build args to dashboard Co-authored-by: Rotimi Best <[email protected]> --------- Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: Rotimi Best <[email protected]> * feat: add SSO and token authentication routes and services - Introduced new routes for SSO and token authentication under the organization namespace. - Implemented SSO connection management including creation, update, activation, and deletion. - Added token authentication configuration with support for secret rotation and status retrieval. - Enhanced error handling for SSO and token authentication processes. - Updated existing routes and services to integrate new functionalities. - Improved gradebook service to fetch student marks and exercises. - Refactored API structure for better organization and maintainability. * update translations * fix: add PUBLIC_SERVER_URL to .env.example to prevent localhost fallback in production (#641) Co-authored-by: Cursor Agent <[email protected]> * feat: new exercise question types * MinIO S3 storage backend (#639) * feat(storage): add MinIO/S3-compatible object storage backend - Add OBJECT_STORAGE_* env vars for generic S3-compatible backends (MinIO, AWS S3) - Create storage config module with Cloudflare R2 fallback for backward compatibility - Refactor s3.ts to use configurable client and bucket names from config - Update media.ts to use provider-neutral public URL (OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN) - Add MinIO service and init to docker-compose (profile: minio) with videos/documents/media buckets - Add localhost:9000 to dashboard CSP for local MinIO presigned URL uploads - Update self-hosting and Cloudflare docs with MinIO option - Update .env examples and docker USAGE.md Fixes #635 Co-authored-by: Rotimi Best <[email protected]> * docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides Co-authored-by: Rotimi Best <[email protected]> * feat(media): refactor media management and integrate MinIO support - Updated media API to use a new `mediaApi` module, replacing `mediaManagerApi` references across components. - Added MinIO configuration options to the Docker setup, allowing for optional object storage exclusion. - Enhanced environment variable management for MinIO in the `.env.example` file. - Updated Content Security Policy (CSP) to allow local MinIO access in the dashboard. - Introduced new media components for asset management, including asset cards and usage dialogs. This refactor improves the modularity of the media handling system and provides better support for S3-compatible storage solutions. * feat(dashboard): enhance logging and refactor auth session handling - Added console logging for event and environment variables in hooks.server.ts to aid debugging. - Refactored auth session handling to use authServerClient instead of authClient in session.ts for improved consistency. - Updated Dockerfile to ensure the dashboard build output is present before starting the application. - Expanded self-hosting documentation to include troubleshooting steps for disk space issues in PostgreSQL and Docker. These changes improve the observability of the application and streamline the authentication process. * refactor(dashboard): remove debug logging and enhance Postgres healthcheck - Removed console logging for event and environment variables in hooks.server.ts to clean up the code. - Updated Postgres healthcheck in docker-compose.yaml to require a successful `SELECT 1` query, ensuring dependent services only start once the database is ready. - Expanded self-hosting documentation to include troubleshooting steps for database recovery issues. These changes improve code clarity and reliability in service startup sequences. --------- Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: Rotimi Best <[email protected]> * feat: add Plyr media player icons and PDF.js integration - Introduced new Plyr SVG icons for media player controls in both course and dashboard applications. - Updated Plyr player configuration to use local icon assets. - Integrated PDF.js for document viewing, replacing external CDN links with local paths for improved performance and reliability. - Enhanced PDF viewer modal z-index for better visibility. This update improves the media player experience and ensures consistent access to necessary resources. * feat: enhance account and organization services with type definitions and promise return types - Updated `getAccountData` to return a structured result type including profile and organizations. - Modified `getOrganizationsWithFilters` to specify a promise return type for better type safety. - Added new type imports for organization-related data structures to improve clarity and maintainability. These changes improve type safety and enhance the overall structure of the account and organization services. * feat: implement Redis caching for presigned URLs and refactor API interactions - Added Redis caching for presigned download URLs in the API to reduce redundant S3 calls, improving performance. - Introduced a new `PresignApi` class in the frontend to centralize presigned URL requests, enhancing code maintainability. - Updated various components to utilize the new `presignApi` methods for document and video upload/download operations. - Enhanced error handling for Redis operations to ensure graceful degradation in case of cache failures. These changes optimize the presigned URL generation process and streamline API interactions across the application. * fix: add better-auth dependency to dashboard (#645) * chore: unify exercise answer data format * feat: make selfhosting run under one org for simplicity (#647) * feat: implement self-hosting PRD + license key system Self-hosting single-org: - Add PUBLIC_IS_SELFHOSTED to API env, block org creation when org exists - Auto-add non-members as students in GET /account bootstrap - getOrgSiteInfo: root domain returns single org for self-hosted - App init: route to /lms when self-hosted + no orgs - Hide org switcher and Add Org modal when self-hosted Invite-only signup: - Add settings.signup.inviteOnly via ZUpdateOrganization - Allow public signups toggle in org auth settings - Signup page: hide form when invite-only and no invite context - Landing page nav: respect inviteOnly for signup link First signup auto-verify: - Self-hosted first signup (no orgs) auto-verifies email in createProfileHook License key system: - LICENSE_KEY, LICENSE_VERIFICATION_URL for external verification API - Feature gates: SSO, token-auth, no-tracking (PostHog/Senja) - requireLicense middleware for API routes - Dashboard: license store, gate PostHog/Senja/SSO/token-auth UI - docs/LICENSE_API_CONTRACT.md for external API spec Co-authored-by: Rotimi Best <[email protected]> * feat: get rid of carbon completely * chore: license verification happens only for selfhosted instance * fix: in self hosted instance, orgSite is the default * docs: how to write math in cio editor * Update packages/db/src/queries/organization/organization.ts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * Update apps/api/src/services/license.ts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * fix: translations, cursor pr reviews, simplify license fetching and check * refactor: update analytics setup for cloud and self-hosted deployments; enhance settings merge logic * refactor: update license fetching URL for development environment; optimize organization query to prevent plan row loss * more selfhosting improvements * feat: enhance signup guard for self-hosted instances by requiring organization context when no org ID is provided * pr reviews * fix: correct query parameter handling in course navigation * pr reviews --------- Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: Rotimi Best <[email protected]> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --------- Co-authored-by: Cursor <[email protected]> Co-authored-by: Rotimi Best <[email protected]> Co-authored-by: Abdulmuizz Hamzat <[email protected]> Co-authored-by: Adeyemi Adetunji <[email protected]> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Enterprise SSO PRD (SAML 2.0 + OIDC)
Purpose
Add enterprise SSO for ClassroomIO with per-organization configuration, supporting both SAML 2.0 and OIDC, while preserving the current Better Auth session model and multi-tenant org permissions.
Confirmed Decisions (2026-02-17)
- IdPs to support: Auth0, Google Workspace, Okta.
- Scope: per organization (not global tenant-wide config).
- Protocols: OIDC for v1. SAML 2.0 deferred to v2.
- Force SSO: enabled (orgs can disable email/password when SSO is enabled).
- Provisioning: JIT only for v1. SCIM deferred to future phase.
- SAML deferred to v2 (Better Auth SAML is in active development).
- Break-glass: simplified emergency access via pre-configured admin bypass.
- Domain enforcement: simplified to auto-join toggle.
- Entitlement: SSO is gated to
PLAN.ENTERPRISE. - SCIM deprovisioning: future phase, with interim login-time entitlement checks.
Architecture: Better Auth SSO Plugin
v1 leverages Better Auth's official SSO plugin (@better-auth/sso) for OIDC support:
- Built-in OIDC discovery and flow handling
- Automatic callback URL generation
- Domain-based provider routing
- Claim mapping support
- Session management via Better Auth
Our custom layer handles:
- Enterprise plan entitlement checks
- Organization-scoped provider management
- Force SSO policy enforcement
- Org membership JIT provisioning
- Admin configuration UI
Current-State Audit
| Capability | Current State | Notes |
|---|---|---|
| Auth framework | available | Better Auth with cookie sessions (packages/db/src/auth.ts) |
| Email/password auth | available | Enabled via emailAndPassword (packages/db/src/auth/email-password.ts) |
| Social login | partial | Google social login only (packages/db/src/auth.ts, apps/dashboard/src/lib/features/ui/auth-ui.svelte) |
| Session handling | available | /api/auth/* mounted in API, auth.api.getSession middleware (apps/api/src/app.ts) |
| Multi-tenant org model | available | organization, organizationmember, org role checks and cio-org-id header enforcement |
| Org invite flows | available | Role-aware organization invites already implemented |
| Enterprise SSO (SAML/OIDC per org) | missing | No SSO connection model, no discovery, no SAML/OIDC enterprise callback flows |
| Force SSO policy | missing | No org-level policy to block local email/password |
| SCIM | missing | No SCIM endpoints or provisioning sync |
Product Goals
- Allow each organization to configure one SSO connection.
- Support Auth0, Google Workspace, and Okta with OIDC.
- Preserve existing Better Auth sessions/cookies and downstream auth middleware behavior.
- Add Force SSO policy at org level.
- Keep invite/onboarding flows compatible with SSO.
- Ship JIT provisioning for v1.
- Add simple domain-based auto-join policy.
- Gate all SSO capabilities to Enterprise plan organizations.
Non-Goals (v1)
- SAML 2.0 (deferred to v2 - Better Auth SAML is in active development).
- SCIM implementation (deferred to future phase).
- Multiple SSO connections per organization.
- Custom claim mapping UI (use standard claims).
- Global logout / SAML Single Logout (SLO).
- Arbitrary custom IdP templates beyond Auth0/Google Workspace/Okta.
- Cross-organization identity linking rules beyond current email + org membership model.
Data Sources Checked
packages/db/src/auth.tspackages/db/src/auth/email-password.tsapps/api/src/app.tsapps/api/src/middlewares/auth.tsapps/api/src/middlewares/org-member.tsapps/api/src/middlewares/org-admin.tspackages/db/src/schema.tspackages/db/src/queries/organization/organization.tsapps/api/src/services/account.tsapps/api/src/services/organization/invite.tsapps/api/src/services/course/invite.tsapps/dashboard/src/lib/utils/services/auth/client.tsapps/dashboard/src/lib/utils/services/auth/session.tsapps/dashboard/src/routes/(auth)/login/+page.svelteapps/dashboard/src/lib/features/ui/auth-ui.svelteapps/dashboard/src/lib/features/app/init.svelte.tsapps/dashboard/src/lib/features/ui/navigation/org-navigation.tsapps/docs/content/docs/quickstart/self-hosting.mdxapps/docs/content/docs/meta.jsonapps/docs/content/docs/quickstart/meta.json
Functional Requirements
1. Per-Organization SSO Connection Management
- Org admins can create/update/disable one SSO connection per org.
- Supported providers: Auth0, Google Workspace, Okta.
- Supported protocols: OIDC and SAML 2.0.
- Connection supports test/verify before activation.
2. SSO Discovery and Login Start
- On org domains (
{org}.domain.comor custom domain), login should use that org context directly. - On shared app domain, user can enter email to discover SSO route by org policy/domain mapping.
- Discovery response should indicate:
- SSO required or optional
- Provider type
- Whether password login is allowed
3. OIDC Flow (Better Auth SSO Plugin)
Better Auth handles the OIDC flow:
- Authorization code flow with PKCE,
state, andnonce. - Auto-discovery from
.well-known/openid-configuration. - Token validation and userinfo retrieval.
- Claim mapping to user fields.
Our layer handles:
- Provider registration via
auth.api.registerSSOProvider. - Post-sign-in org membership provisioning via
dbHooks. - Role mapping from
groupsclaim.
4. SAML 2.0 Flow (v2)
- Deferred to v2 - will be implemented once Better Auth's SAML support is stable.
5. JIT Provisioning and Membership Linking
- On successful SSO callback:
- Find or create user/profile
- Upsert org membership in
organizationmember - Link external identity (
connection + subject) to local user
- If invited member row exists by email, bind
profileIdand mark verified - Default JIT role for new users:
ROLE.STUDENT
6. Role Mapping
- Simple role mapping from IdP
groupsclaim:- Map group names to
ROLE.ADMIN,ROLE.TUTOR,ROLE.STUDENT - If no mapping matched, fallback to
ROLE.STUDENT
- Map group names to
- Configuration: simple key-value mapping in connection settings
7. Force SSO
- Org-level
forceSso=truedisables email/password login for that org context - Enforce server-side, not only UI-level
- Users attempting password login for a force-SSO org receive structured error + SSO redirect hints
- Existing email/password sessions: remain valid until expiry (no forced logout)
- Break-glass: pre-configured emergency admin can bypass (audited)
8. Audit and Observability
- Use existing audit/logging infrastructure with structured event types:
sso.connection_created,sso.connection_updated,sso.connection_disabledsso.login_success,sso.login_failuresso.provisioned,sso.role_assignedsso.force_sso_block
- Include orgId, connectionId, actor/profile (when available), IP, user agent
9. Domain Auto-Join Policy
- Simple toggle:
auto_join_sso_domains(boolean) - When enabled, users with matching email domain can auto-join org via SSO
- When disabled, users must have pending invite to join via SSO
- Trust IdP-verified email domains
10. Enterprise Plan Entitlement
- SSO configuration and login endpoints must verify org entitlement to
PLAN.ENTERPRISE - Non-enterprise orgs receive explicit upgrade-required responses
Technical Design
Architecture Summary
Leverage Better Auth SSO plugin (@better-auth/sso) for OIDC protocol handling. Our custom layer provides:
- Admin management - CRUD SSO connections (stored in our schema for UI)
- Enterprise gating - Verify
PLAN.ENTERPRISEbefore allowing SSO - Force SSO enforcement - Block email/password when policy enabled
- JIT provisioning - Create org membership post-authentication via
dbHooks
Better Auth handles:
- OIDC discovery, authorization, token exchange
- Session creation and management
- User creation/linking
Data Model
organization_auth_policy
organization_id(uuid, pk/fk)force_sso(boolean, defaultfalse)default_role_id(bigint, defaultROLE.STUDENT)allow_email_password_fallback(boolean, defaulttrue)auto_join_sso_domains(boolean, defaultfalse)break_glass_enabled(boolean, defaulttrue)created_at,updated_at
organization_sso_connection
id(uuid, pk)organization_id(uuid, fk, indexed, unique)provider(OKTA|GOOGLE_WORKSPACE|AUTH0)protocol(OIDC) - enum for future SAML extensiondisplay_name(text)is_active(boolean, defaultfalse)issuer(text) - IdP issuer URLdomain(text) - email domain for discoveryoidc_config(jsonb) - clientId, scopes, etc (clientSecret stored in Better Auth)role_mapping(jsonb) - simple key-value: group name → rolebetter_auth_provider_id(text) - reference to Better Auth's stored providercreated_by_profile_id,updated_by_profile_id(uuid)created_at,updated_at
sso_identity_link
id(uuid, pk)organization_id(uuid, indexed)connection_id(uuid, fk)user_id(uuid, fk touser.id)external_subject(text)email_at_link(text)last_login_at(timestamp)created_at,updated_at
Constraints:
- unique
(connection_id, external_subject) - unique
(organization_id, user_id, connection_id)
API and Route Plan
Better Auth Integration
The SSO plugin provides these endpoints automatically:
POST /api/auth/sso/register- Register OIDC provider (admin only)GET/POST /api/auth/sso/authorize/:providerId- Start SSO flowGET/POST /api/auth/sso/callback/:providerId- OIDC callback
Our Custom Layer
Validation Layer
packages/utils/src/validation/organization/sso.tsZCreateSsoConnectionZUpdateSsoConnectionZSsoDiscoveryQuery
Query Layer
packages/db/src/queries/organization/sso.ts- connection CRUD
- org auth policy read/write
Service Layer
apps/api/src/services/organization/sso.ts- Admin CRUD with Enterprise plan check
- Call
auth.api.registerSSOProvideron activation - Call
auth.api.deleteSSOProvideron deactivation
apps/api/src/services/auth/sso.ts- Discovery logic
- Force SSO enforcement
Route Layer
apps/api/src/routes/organization/sso.ts- Admin CRUD endpointsapps/api/src/routes/sso/discovery.ts- Public discovery endpoint- Register in:
apps/api/src/routes/organization/index.tsapps/api/src/app.ts
Better Auth Hooks
dbHooks.user.afterCreate- JIT org membership provisioning
Frontend Plan (Dashboard)
Login UX
- Update:
apps/dashboard/src/routes/(auth)/login/+page.svelteapps/dashboard/src/lib/features/ui/auth-ui.svelte
- Add SSO discovery step:
- org-site context: direct SSO action for current org
- shared app login: email-based discovery before method selection
- If Force SSO for org, hide password fields and show SSO-only CTA
Org Settings UX
- Add new page:
apps/dashboard/src/routes/org/[slug]/settings/sso/+page.svelte - Add settings feature page:
apps/dashboard/src/lib/features/settings/pages/sso.svelte - Export page in
apps/dashboard/src/lib/features/settings/pages/index.ts - Add org navigation nested route in
apps/dashboard/src/lib/features/ui/navigation/org-navigation.ts - Add controls for:
- Provider selection (Auth0, Google Workspace, Okta)
- Protocol selection (OIDC, SAML)
- Force SSO toggle
- Auto-join toggle
- Simple role mapping
- Break-glass enable/disable
- Add translation keys in
apps/dashboard/src/lib/utils/translations/en.json
Admin SSO Configuration UI Spec
Page Information Architecture
Connectionsection:- Current SSO connection status (provider, protocol, active/inactive)
- Actions:
Configure,Edit,Disable,Test,Activate
Policiessection:- Force SSO toggle
- Auto-join toggle
- Break-glass toggle
Role Mappingsection:- Simple table: IdP group name → ClassroomIO role
Setup Wizard (Create/Edit Connection)
- Step 1
Choose Provider:- Provider:
Auth0,Google Workspace,Okta - Protocol:
OIDCorSAML
- Provider:
- Step 2
Configure Identity Provider:- Render provider/protocol-specific fields
- Show generated callback values to copy into IdP
- Step 3
Test Connection(optional):- Run live test with state/nonce checks
- Display pass/fail results with remediation hints
- Step 4
Activate:- Summary of config
- Activate now or save as draft
- If Force SSO enabled, require explicit confirmation
Provider-Specific Form Fields (OIDC Only)
- Common fields:
display_name(required)domain(required) - email domain for discovery (e.g.,company.com)
- OIDC fields:
issuer(required URL) - e.g.,https://company.okta.comclient_id(required)client_secret(required) - sent to Better Auth, not stored locallyscopes(defaultopenid profile email)- Read-only: callback URL (
/api/auth/sso/callback/{providerId})
Validation Rules and Error UX
- Field-level validation:
- URLs must be valid HTTPS (localhost exception for dev)
- Required fields present before activation
- Claim mapping must include
emailandsub/NameID
- Cross-field validation:
force_sso=truerequires active connection- Connection can be saved as draft without full validation
- Error presentation:
- Inline field errors for input validation
- Structured backend errors for: issuer mismatch, invalid cert, callback mismatch, missing claims
Safety and Recovery UX
- Draft mode supported; drafts cannot be used for login
- Disable/rollback action always available to org admins
- All admin actions write visible audit entries
Client Types/API Class
- Add request types in
apps/dashboard/src/lib/features/org/utils/types.ts - Add API class in
apps/dashboard/src/lib/features/org/api/sso.svelte.ts - Use
this.execute<RequestType>()pattern only
Documentation Plan (apps/docs)
Required Documentation Updates
- Add core feature documentation:
apps/docs/content/docs/enterprise-sso.mdx- feature overview
- Add how-to guides:
apps/docs/content/docs/how-to/sso-auth0.mdxapps/docs/content/docs/how-to/sso-google-workspace.mdxapps/docs/content/docs/how-to/sso-okta.mdx
- Register pages in root docs nav:
apps/docs/content/docs/meta.jsonunder---Core Features---
- Update self-hosting reference:
apps/docs/content/docs/quickstart/self-hosting.mdx- Include SSO-related env vars and callback URL guidance
Required Topics in Docs
- SSO prerequisites and Enterprise plan requirement
- Provider-by-provider setup checklist (Auth0, Google Workspace, Okta)
- Force SSO behavior and user experience
- JIT behavior and invite interactions
- Break-glass policy
- Troubleshooting: callback mismatch, certificate issues, entitlement errors
Security Requirements
- Encrypt all SSO secrets at rest
- Strict signature/issuer/audience checks for SAML/OIDC
- Anti-CSRF and replay protection via
state/nonceand one-time callback state - Rate-limit discovery/start/callback endpoints
- Full audit trail for admin config and auth outcomes via existing logging
- No trust of frontend-enforced Force SSO alone; must be validated on backend
Rollout Plan
Phase 1: Foundation + OIDC + JIT
- Install
@better-auth/ssoplugin - Schema + policy/connection management
- Integration with Better Auth SSO plugin
- OIDC flows for Auth0/Google Workspace/Okta via Better Auth
- SSO discovery + login UI
- Force SSO enforcement
- Domain auto-join policy + admin settings UI
- Enterprise plan entitlement checks
- JIT org membership via
dbHooks - Publish docs updates
Phase 2: SAML 2.0
- Enable when Better Auth SAML is stable
- SAML flows for supported providers
- Force SSO parity for SAML
Phase 3: Future Enhancements
- SCIM provisioning (if customer demand)
- Multiple connections per org (if customer demand)
- Advanced claim mapping (if customer demand)
Acceptance Criteria
- Org admin can configure an active SSO connection (OIDC).
- User can successfully login through Auth0, Google Workspace, and Okta.
- Successful SSO login creates/links user and org membership via JIT.
- Force SSO org cannot authenticate through email/password for org-context access.
- Auto-join policy is configurable in UI and enforced server-side.
- SSO access is blocked for non-enterprise orgs.
- Existing non-SSO orgs keep current auth behavior unchanged.
- Audit events are logged for config changes and SSO auth events.
apps/docsincludes SSO feature docs and provider how-to guides before GA.- Org admins can configure Auth0, Google Workspace, and Okta through a setup wizard.
- Connection can be saved as draft without full validation.
- UI surfaces actionable errors for provider setup and configuration issues.
Risks and Mitigations
- Risk: Force SSO lockout due to bad config.
- Mitigation: connection can be disabled by any org admin + break-glass emergency access.
- Risk: role escalation by incorrect claim mapping.
- Mitigation: simple mapping validation + default least privilege (
ROLE.STUDENT).
- Mitigation: simple mapping validation + default least privilege (
- Risk: callback replay attacks.
- Mitigation: one-time state, timestamp windows, assertion ID tracking.
Finalized Decisions
- OIDC only for v1 - SAML deferred to v2 (Better Auth SAML in active development).
- Use Better Auth SSO plugin (
@better-auth/sso) for OIDC flow handling. - Break-glass local admin access is included with strict auditing.
- Domain enforcement simplified to auto-join toggle.
- SSO is gated to
PLAN.ENTERPRISE. - SCIM deferred to future phase.
- Single connection per org for v1.
- Standard claims only, no custom claim mapping UI.