* 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 <cursoragent@cursor.com> * 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 <rotimi-best@users.noreply.github.com> * 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 <rotimi-best@users.noreply.github.com> * 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 <best@classroomio.com> * 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 <rotimi-best@users.noreply.github.com> * 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 <rotimi-best@users.noreply.github.com> * fix(dashboard): self-hosted CSP uses only env vars, no defaults Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * fix(dashboard): add all classroomio.com domains to CSP defaults Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * feat(docker): pass CSP domain env vars as build args to dashboard Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * 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 <cursoragent@cursor.com> * 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 <rotimi-best@users.noreply.github.com> * docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * 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 <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> * 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 <rotimi-best@users.noreply.github.com> * 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 <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com> Co-authored-by: Abdulmuizz Hamzat <103611443+buildwithhamzat@users.noreply.github.com> Co-authored-by: Adeyemi Adetunji <tvnji01@gmail.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Course Widget Embed PRD (Org Widgets)
Purpose
Ship an organization-scoped widget system so admins can embed selected courses on external websites from /org/[slug]/widgets, with a visual editor and lightweight runtime.
Confirmed Decisions (2026-02-17)
- Editor route is in dashboard org context:
/org/[slug]/widgets(user-facing equivalent:/org/id/widgets). - Embed runtime must be plain Svelte (no SvelteKit in the embed runtime path) for minimal JS payload.
- Widget rendering supports multiple layouts:
- cards
- table
- primary single course
- carousel
- tag-filtered list (tags as top badges)
- Widget authoring UI opens an editor with left panel sections:
Select CoursesWidgetsDesign
- Published widgets deploy to Cloudflare-backed static hosting/edge delivery (R2 + Workers).
- Dashboard editing imports the widget package in dev mode for real preview parity.
- Dashboard preview does not call a preview endpoint; it uses already-fetched dashboard state and passes payload into an iframe.
- Public embed fetches computed widget payload (courses + design config) from server endpoints.
Problem Statement
Organizations currently show courses mainly on their own landing pages. There is no first-class way to publish reusable, brandable, copy-paste course widgets for external websites.
This creates gaps:
- No reusable embed snippet per organization.
- No dashboard-managed widget lifecycle (draft, publish, version rollback).
- No lightweight runtime optimized for third-party pages.
- No structured design controls for layout/theme/branding.
Product Goals
- Let org admins create and publish embeddable course widgets.
- Keep embed runtime lightweight and isolated from host-site CSS/JS conflicts.
- Reuse existing course and tag data models for content selection/filtering.
- Provide clear plan-gated design controls (free vs paid capabilities).
- Support versioned publishing with safe rollbacks.
Non-Goals (v1)
- Full website/page builder replacement.
- Server-rendered widget runtime.
- Cross-org shared widget templates marketplace.
- Arbitrary third-party JS execution inside widgets.
Data Sources Checked
apps/dashboard/src/lib/features/ui/navigation/org-navigation.tsapps/dashboard/src/routes/org/[slug]/courses/+page.server.tsapps/dashboard/src/routes/org/[slug]/tags/+page.server.tsapps/dashboard/src/lib/features/org/api/org.svelte.tsapps/dashboard/src/lib/features/org/components/landing-page/landing-page.svelteapps/dashboard/src/lib/features/course/components/card.svelteapps/api/src/routes/organization/organization.tsapps/api/src/services/organization.tspackages/db/src/schema.tspackages/db/src/queries/course/course.tspackages/db/src/queries/tag/tag.tspackages/utils/src/plans/constants.tspackages/course-app/README.md
User Roles
Admin (ROLE.ADMIN)
- Create/edit/delete/archive widgets.
- Select courses and widget layout.
- Configure design controls and plan-gated options.
- Publish widget versions and rollback.
- Copy embed snippet.
Tutor (ROLE.TUTOR)
- Create/edit widget drafts and use live preview.
- No publish, rollback, or destructive lifecycle actions in v1.
Student/Public
- No dashboard access.
- Consume published embed on external sites.
Functional Requirements
1. Widget Lifecycle
- Create widget with:
namelayoutType- selection mode (
manualcourse selection orpublished courses) - initial design config
- Status model:
DRAFTPUBLISHEDARCHIVED
- Save model:
- manual save only (
Savebutton) - no autosave in v1
- manual save only (
- Publish creates immutable version snapshot.
- Rollback can point latest published to a previous version.
2. Widget Editor UX (/org/[slug]/widgets/:widgetId)
- Left panel tabs:
Select CoursesWidgetsDesign
- Main panel:
- live preview using the same shared render package as embed
- desktop/mobile preview toggle
- embed code tab
- Live preview behavior:
- every design/content change updates a local draft state
- dashboard uses already-fetched state (courses/tags/widget draft) to build preview payload
- preview payload is passed down through iframe (
postMessage) to preview runtime - iframe mounts the same widget component contract used by public embed
- changes are preview-only until user clicks
Save
3. Select Courses
- Source modes:
- manual selected courses
- all published org courses
- Filters:
- tag include/exclude using existing org tags
- search by course title
- Ordering:
- manual order
- newest
- title A-Z
4. Widget Layout Types
cardstableprimary_coursecarouseltag_filter
Each layout supports required shared props:
showCourseImageshowCourseTypeBadgeshowLessonsCountshowPriceshowDescriptionExcerptctaLabel
5. Design Controls
Design panel is grouped as:
Content
- limit courses toggle + max count
- load more label
- hide load more toggle
- show border toggle
- border width
- shadow size + style + color
- border radius scale
- show metadata toggles (lessons/type/price)
- shorten long description toggle
- show highlighted/featured style toggle
Colors
- primary color
- background color
- text color
- badge/rating color
- border color
- highlight color
Typography
- font family selector
- font size scale
Filters
- add/remove tag filter rows
- top badge style for tag filter layout
Branding
Show Classroomio Powered Bytoggle
Advanced
- custom CSS textarea (sanitized + size-limited)
6. Plan Gating
- Free (
PLAN.BASIC):- 1 preset theme only (default Classroomio theme)
- branding forced on
- custom CSS disabled
- Paid (
PLAN.EARLY_ADOPTER,PLAN.ENTERPRISE):- All preset themes available (3-5 curated themes)
- full color controls (custom colors)
- branding toggle available
- custom CSS enabled
7. Public Embed Contract
- Copy-paste script embed:
<script async src="https://widgets.classroomio.com/v1/loader.js" data-widget="wgt_xxx"></script>
- Loader pulls published widget payload via public key and mounts Svelte widget.
- Host page should not require framework dependencies.
- Payload shape must match dashboard preview payload contract.
8. Runtime Constraints (Lightweight Requirement)
- Plain Svelte runtime package (
packages/widgets) compiled in library mode (Vitebuild.lib). - No SvelteKit runtime in embed bundle.
- Use style isolation: Shadow DOM custom element (
<widget-root>) with:hostselector support. - Performance budgets:
- loader <= 3KB gzip
- base runtime <= 35KB gzip (excluding fetched data)
- first render <= 1.2s on mid-tier 4G for <= 6 courses
- Accessibility:
- All interactive elements keyboard accessible
- ARIA labels on course cards (
aria-label="Course: ${title}") - Alt text on course images
- Focus visible indicators
9. Security and Safety
- Public widget key must be non-guessable (format:
wgt_<base58>). - Custom CSS sanitized with
css-treeparser (whitelist approach):- Max size: 5KB
- Reject:
@import,javascript:, expression(), behavior:, binding:,-moz-binding - Reject properties:
position: fixed(can overlay host page maliciously) - Allowed: standard visual styles (color, spacing, typography, flex/grid layout)
- Public endpoint returns only publish-approved fields (no internal org data).
- Rate limit public widget payload endpoint: 100 req/min per IP, 1000 req/min per widget key.
- iframe origin validation: strict
targetOriginmatching dashboard domain.
10. Analytics (Schema Reserved for Phase 2)
Deferred to Phase 2, but schema defined for forward compatibility:
// Table: widget_analytics_event
{
id: string;
widget_id: string;
widget_version_id: string;
event_type: 'impression' | 'cta_click' | 'filter_interaction';
course_id?: string; // for cta_click events
filter_tag_id?: string; // for filter_interaction events
session_id: string; // anonymous session fingerprint
timestamp: Date;
user_agent_hash: string; // privacy-preserving hash
country_code?: string; // from CF-IPCountry header
}
- Ingestion: Batch insert every 30 seconds or 1000 events
- Retention: 90 days raw, aggregated forever
- v1: No events endpoint; schema created but not populated
11. Shared Payload Contract (Hard Requirement)
- One canonical payload schema defines widget data:
- selected courses
- resolved ordering/filters
- normalized design tokens and defaults
- plan-gated fields
- Dashboard preview builds payload client-side from already-fetched state and passes it to iframe.
- Public embed builds/fetches payload server-side from persisted widget config and course queries.
- The embed renderer accepts only this payload schema + minimal runtime options.
- No separate dashboard-only renderer data shape is allowed.
11. Cloudflare Publish Pipeline (Phase E)
Artifact Generation
- Build Trigger: API call
POST /organization/widgets/:widgetId/publish - Build Process:
a. API receives publish request b. Compute final payload with resolved courses + design config c. Trigger build worker (Cloudflare Worker or GitHub Actions) d. Build @cio/widgets package with embedded design tokens e. Generate hashed filenames (e.g., `widget.a3f2b1c.js`) f. Upload to R2 bucket: `widgets/{orgId}/{widgetId}/v{version}/` g. Return manifest URLs to API h. API saves `artifact_manifest` to `widget_version` table
Artifact Manifest Format
{
"version": "v1",
"widgetId": "wgt_xxx",
"orgId": "org_yyy",
"createdAt": "2026-02-19T12:00:00Z",
"files": {
"js": {
"url": "https://cdn.classroomio.com/widgets/org_yyy/wgt_xxx/v3/widget.a3f2b1c.js",
"integrity": "sha384-abc123...",
"size": 24567
},
"css": {
"url": "https://cdn.classroomio.com/widgets/org_yyy/wgt_xxx/v3/styles.7e8d9f0.css",
"integrity": "sha384-def456...",
"size": 3456
}
},
"designHash": "sha256:abc..."
}
Cleanup Policy
- Keep last 10 versions per widget
- Delete older artifacts after 30 days (R2 lifecycle rule)
- Soft-delete in DB (set
deleted_at), hard-delete after 90 days
Delivery Architecture
User's Website Cloudflare
| |
|-- script src="loader.js" -----> |-- Worker: validate key
| |-- Check cache (KV)
| |-- Cache miss: fetch from R2
|<-- loader.js -------------------|
| |
|-- loader fetches manifest ----->|-- Return artifact_manifest
| |
|-- loader injects JS/CSS ------->|-- Serve from R2 (immutable cache)
Proposed Architecture
Package and App Boundaries
packages/widgets
- plain Svelte renderer components
- layout implementations
- shared design token mapping
- build output: ESM + browser bundle
apps/dashboard
- widget editor UI and preview
- imports renderer from
@cio/widgetsin dev/prod build
apps/api
- org-protected widget CRUD/publish routes
- public widget payload route
- shared
computeWidgetPayload(...)service used for public payload routes
- Cloudflare publish target
- stores versioned JS/CSS artifacts
- serves loader + static assets + cache headers
Render Data Flow
- Dashboard editor loads widget draft and related data into state (courses/tags/config).
- Left panel changes update local draft JSON in state.
- Dashboard builds preview payload from state and sends it to preview iframe via
postMessage. - Preview iframe mounts
@cio/widgetsrenderer with received payload. - Publish stores snapshot; public loader requests server-computed payload for published version and mounts same renderer.
Data Model (Proposed)
widget
id,organization_id,name,status,layout_typeselection_mode,public_key,latest_published_version_idcreated_by,updated_by, timestamps
widget_course
widget_id,course_id,order
widget_version
id,widget_id,versionconfig_snapshot(jsonb)artifact_manifest(jsonb: js/css URLs + integrity)published_at,published_by
API Contract Additions (Target)
Organization-Scoped (auth + org membership)
GET /organization/widgetsPOST /organization/widgetsGET /organization/widgets/:widgetIdPUT /organization/widgets/:widgetIdDELETE /organization/widgets/:widgetIdPOST /organization/widgets/:widgetId/publishPOST /organization/widgets/:widgetId/rollback
Public
GET /widgets/:publicKey/payloadPOST /widgets/:publicKey/events(optional in v1, can be deferred)
UX Flow
- Admin opens
/org/[slug]/widgets. - Clicks
Create Widget. - Editor opens with left tabs (
Select Courses,Widgets,Design). - Admin previews and adjusts design.
- Admin publishes, receives embed snippet.
- External website adds script tag; widget renders courses.
Plan Gating UX Pattern
- Free users: Show paid features as disabled with upgrade tooltip
- Theme selector shows 1 option with "Upgrade to unlock more themes" on hover
- Custom color picker disabled with "Upgrade to customize colors" tooltip
- Custom CSS textarea shows lock icon with upgrade CTA
- "Powered by Classroomio" toggle is locked ON with tooltip
- Paid users: Full access to all controls, branding toggle available
Open Questions (Resolved)
- ✅ Free plan color tweaks – 1 preset theme only (default). Paid users get all preset themes (3-5) plus custom color picker.
- ✅ Events endpoint – Deferred to Phase 2; schema reserved but not implemented in v1.
- ✅ Locale detection – Deferred to Phase 2; widgets use single-language labels from org default locale in v1.
- ✅ CSS isolation – Shadow DOM custom element preferred for strongest isolation. Fallback to scoped classes only if Shadow DOM causes critical theming issues during Phase C testing.
Additional Architecture Decisions
Widget Key Format
- Format:
wgt_<base58(16-bytes-random)> - Example:
wgt_3J98t1WpEZ73CNmYv - Includes implicit typo detection via base58 checksum behavior
- Length: 23 characters (prefix + 16 chars)
Rollback Mechanics
- Rollback is pointer-swap, not append-only
latest_published_version_idpoints to any previous version- No new version created on rollback
- Analytics remain tied to version ID (history preserved)
- UI shows version history (read-only) with "Restore to this version" action
Caching Strategy
- Public payload endpoint:
Cache-Control: public, max-age=60, stale-while-revalidate=300 - Widget JS/CSS artifacts:
Cache-Control: public, max-age=31536000, immutable - Loader script:
Cache-Control: public, max-age=3600(versioned via query param)
Expanded TODOs (Priority)
TODO-2: Iframe Protocol Spec (Detailed)
Message Types
// Parent → Iframe
type ParentMessage =
| { type: 'WIDGET_PREVIEW_RENDER'; payload: WidgetPayload; requestId: string }
| { type: 'WIDGET_PREVIEW_PING' }; // health check
// Iframe → Parent
type IframeMessage =
| { type: 'WIDGET_PREVIEW_READY'; iframeId: string; timestamp: number }
| { type: 'WIDGET_PREVIEW_RENDERED'; requestId: string; timestamp: number }
| { type: 'WIDGET_PREVIEW_ERROR'; requestId: string; error: string; timestamp: number }
| { type: 'WIDGET_PREVIEW_RESIZE'; height: number; width?: number }
| { type: 'WIDGET_PREVIEW_CTA_CLICK'; courseId: string }; // for preview interactivity
Payload Envelope
interface WidgetPayload {
version: 'v1';
widgetId: string;
layoutType: 'cards' | 'table' | 'primary_course' | 'carousel' | 'tag_filter';
courses: Course[];
design: DesignConfig;
planGatedFields: PlanGatedFields;
timestamp: number; // epoch ms for cache-busting
}
Security Rules
-
Origin Validation:
- Production:
targetOriginmust matchVITE_DASHBOARD_URL(e.g.,https://app.classroomio.com) - Development: allow
http://localhost:*with port wildcard - Never use
*in production
- Production:
-
Message Validation:
- Reject messages without
typefield - Reject unknown message types
- Validate payload schema with Zod before processing
- Reject messages without
-
iframe Sandboxing:
- Use
sandbox="allow-scripts"attribute - No
allow-same-origin(prevents cookie access)
- Use
Reliability Rules
-
Handshake Flow:
Parent: mount iframe → wait for READY (timeout: 5s) Iframe: mount complete → send READY Parent: receive READY → send RENDER with payload Iframe: render complete → send RENDERED or ERROR -
Retry Logic:
- READY timeout: 3 retry attempts, exponential backoff (1s, 2s, 4s)
- RENDERED timeout: 2 retry attempts, show error state in parent
-
Error Handling:
- Render errors: Show fallback UI in parent ("Preview unavailable")
- Log error details to console with
[WidgetPreview]prefix - Surface user-friendly error in editor UI
Sequence Diagram
Parent (Dashboard) Iframe (Widget Runtime)
| |
|--- mount iframe ------------>|
| |
|<-- WIDGET_PREVIEW_READY -----|
| (iframe ready) |
| |
|--- WIDGET_PREVIEW_RENDER --->|
| (payload + config) |
| |
|<-- WIDGET_PREVIEW_RESIZE ----|
| (dynamic height) |
| |
|<-- WIDGET_PREVIEW_RENDERED --|
| OR WIDGET_PREVIEW_ERROR |
Documentation Output
- Spec file:
prd/course-widget-embed/iframe-protocol.md(this section) - Implementation:
packages/widgets/src/preview/iframe-bridge.ts+apps/dashboard/src/lib/features/widget/preview/iframe-parent.ts
TODO-3: Preview Data Freshness (Implementation Details)
Freshness States
| State | Indicator | User Action | Behavior |
|---|---|---|---|
fresh |
Green dot + "Live" | None | Data synced with server within last 5 minutes |
stale |
Yellow dot + "Refresh suggested" | Manual refresh button | Data older than 5 minutes or tab was backgrounded |
refreshing |
Spinner + "Syncing..." | Disabled | Fetch in progress |
error |
Red dot + "Sync failed" | Retry button | Last fetch failed, using cached data |
Implementation Rules
- Initial Load:
+page.server.tsprovides hydrated data withserverTimestamp - Stale Detection:
- Check
Date.now() - lastSyncTime > 5 * 60 * 1000on mount - Listen to
visibilitychangeevent: when tab becomes visible, check staleness
- Check
- Background Sync:
- Use
navigator.sendBeaconorfetchwithkeepalivefor refresh - Debounce refresh calls (minimum 30s between requests)
- Use
- Warning UX:
- Non-blocking toast when stale data detected
- Course/tag removed warning appears in preview area (not blocking)
- Consistency:
- Draft state is never auto-refreshed; only source data (courses/tags list)
- User must explicitly refresh to see new courses/tags
State Machine
initial load
[empty] ----------> [fresh]
|
5min timeout | visibility change
v
[stale] <------.
| |
manual or | | error
auto refresh |
v |
[refreshing] ----'
|
success | | failure
| |
v v
[fresh] [error]
^ |
'-------'
retry
TODO-4: CSS Sanitizer Implementation
Library Choice
- Primary:
css-treefor parsing + whitelist validation - Backup:
reworkcssifcss-treebundle size exceeds 15KB
Validation Rules
const CSS_SANITIZER_CONFIG = {
maxSizeBytes: 5120, // 5KB
// Allowed at-rules
allowedAtRules: ['media', 'supports', 'keyframes', '-webkit-keyframes'],
// Blocked at-rules (security)
blockedAtRules: ['import', 'charset', 'namespace', 'font-face', 'page', 'document'],
// Allowed properties (whitelist approach)
allowedProperties: [
// Layout
'display', 'position', 'top', 'right', 'bottom', 'left',
'flex', 'flex-direction', 'flex-wrap', 'flex-grow', 'flex-shrink', 'flex-basis',
'justify-content', 'align-items', 'align-content', 'gap', 'row-gap', 'column-gap',
'grid', 'grid-template', 'grid-column', 'grid-row', 'grid-area',
// Box model
'width', 'height', 'min-width', 'min-height', 'max-width', 'max-height',
'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
'border', 'border-radius', 'box-sizing', 'overflow', 'overflow-x', 'overflow-y',
// Visual
'color', 'background', 'background-color', 'background-image', 'background-size',
'background-position', 'background-repeat', 'opacity', 'box-shadow',
'border-color', 'border-width', 'border-style', 'border-top', 'border-right',
// Typography
'font-family', 'font-size', 'font-weight', 'font-style', 'line-height',
'text-align', 'text-decoration', 'text-transform', 'letter-spacing', 'word-spacing',
'white-space', 'word-break', 'overflow-wrap',
// Effects
'transform', 'transition', 'animation', 'filter', 'backdrop-filter'
],
// Blocked values (regex patterns)
blockedValuePatterns: [
/javascript:/i,
/expression\s*\(/i,
/behavior\s*:/i,
/binding\s*:/i,
/-moz-binding/i,
/url\s*\(\s*["']?\s*data:/i, // data URIs (potential XSS)
],
// Special property validations
propertyValidators: {
'position': (value: string) => value !== 'fixed', // No fixed positioning
'background-image': (value: string) => !value.includes('url') || value.startsWith('url(https://')
}
};
Error Handling
- Invalid CSS is stripped silently (not rejected entirely)
- User sees warning: "Some CSS rules were removed for security"
- Log sanitized rules to console in dev mode only
TODO-5: Accessibility Requirements (v1)
Keyboard Navigation
- Tab order: logical flow through course cards
- Enter/Space: activate CTA buttons
- Escape: close any open modals/filter dropdowns
Screen Reader Support
- Course cards:
role="article"witharia-labelledbypointing to title - CTA buttons: descriptive
aria-label(e.g., "View Introduction to Python course") - Filter badges:
aria-pressedstate for active filters - Live regions: announce filter results changes (
aria-live="polite")
Visual Requirements
- Focus indicators: 2px solid outline with 2px offset (using
:focus-visible) - Color contrast: minimum 4.5:1 for text (validated in design tokens)
- Reduced motion: respect
prefers-reduced-motionfor carousel animations
TODO-6: Bundle Size Enforcement
CI Configuration
# packages/widgets/bundle-size.json
{
"limits": {
"loader.js": "3kb",
"runtime.js": "35kb",
"runtime.css": "5kb"
},
"failOnViolation": true
}
Build Script
#!/bin/bash
# packages/widgets/scripts/check-bundle-size.sh
max_size_loader=$((3 * 1024)) # 3KB
max_size_runtime=$((35 * 1024)) # 35KB
loader_size=$(gzip -c dist/loader.js | wc -c)
runtime_size=$(gzip -c dist/runtime.js | wc -c)
if [ $loader_size -gt $max_size_loader ]; then
echo "❌ Loader exceeds budget: ${loader_size}B > ${max_size_loader}B"
exit 1
fi
if [ $runtime_size -gt $max_size_runtime ]; then
echo "❌ Runtime exceeds budget: ${runtime_size}B > ${max_size_runtime}B"
exit 1
fi
echo "✅ Bundle sizes within budget"
Success Criteria
- Admin can publish a widget and embed it externally in under 5 minutes.
- Embed snippet works across static HTML, React, and WordPress hosts.
- Runtime stays within performance budget and has no host CSS collisions.
- Support tickets for “embed broken by host CSS” remain near zero.
- Dashboard live preview matches public embed rendering for the same payload and version.
- Accessibility: Widgets are keyboard-navigable (Tab order, Enter/Space to activate CTAs) and screen-reader friendly (ARIA labels on course cards, alt text on images).
- Security: Zero XSS vectors through custom CSS or malformed payloads in penetration testing.