-
Notifications
You must be signed in to change notification settings - Fork 2
feat!: migrate to session-based auth system (v2) #98
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Adds Better Auth integration groundwork (user/session/account/verification tables, owner/share scaffolding), new env config and i18n entries, and integrates an AuthProvider + user menu in the layout. Temporarily disables legacy calendar password/lock verification across API routes and skips password-related logic to allow staged migration toward a permission-based system (Phase 0-2 → Phase 3). Preserves backward-compat types for compatibility and fixes calendar fetching resilience. Also updates dependencies and lockfile for the new auth/UI components.
Enforces the registration feature flag for OAuth/OIDC flows to block new sign-ups when user registration is disabled while still allowing existing users to sign in. Centralizes and types auth environment access, deduplicates client/server provider IDs, and updates Better Auth integration to use the unified env config (incl. session and trusted origins). Simplifies .env examples and proxy behavior accordingly. Polishes auth UI/layout (header/footer, hydration guards), wires profile actions to the auth client (password change, delete), surfaces connected accounts, adds defensive handling for remote JSON fetches, and introduces a configurable confirmation dialog control. Removes unused verification schema/migration remnants and tidies translation strings related to verification.
|
Important Review skippedToo many files! 59 files out of 209 files are above the max files limit of 150. You can disable this status message by setting the Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Adds session-backed permission checks to calendar-related APIs and UI flows, replacing legacy password gating to strengthen access control and prepare for a unified auth model. Adds a detailed plan for calendar access tokens (share links) to enable secure, token-based sharing and auditing. Introduces a verification table in the auth schema and updates migration metadata to support auth features. Refactors UI/UX: replaces SSR placeholders with consistent skeleton components, makes headers clickable, and improves auth redirects/returnUrl handling to streamline login/register flows. Expands proxy public endpoints and removes old password checks from API routes to finalize migration toward permission-based security.
…ng, and performance enhancements - Added comprehensive table of contents for better navigation - Reorganized phases to prioritize security and infrastructure improvements - Introduced detailed tasks for rate limiting, audit logging, session management, and CSRF protection - Expanded calendar sharing features with a dedicated API and UI components - Enhanced token management with security best practices and lifecycle management - Updated data migration strategy to ensure smooth transition and backwards compatibility - Improved UI/UX enhancements focusing on permission indicators and user feedback - Established admin panel features for user and calendar management - Included extensive testing and documentation requirements for all phases
- Removed password management hooks and related functions to streamline password handling. - Updated various hooks (useDialogStates, useExternalSync, useNoteActions, etc.) to eliminate password checks and parameters. - Adjusted API calls to no longer require password parameters. - Cleaned up translations by removing password-related strings. - Updated database schema to remove password-related fields from calendars. - Added new tables for user accounts and sessions to support future authentication features.
- Added @radix-ui/react-tooltip dependency to package.json. - Updated proxy.ts to support guest access for viewing calendars. - Implemented GuestBanner and ReadOnlyBanner components for guest notifications. - Created a tooltip component for enhanced UI interactions. - Introduced useCalendarPermission hook to manage calendar access permissions. - Added SQL migrations for user and calendar sharing features.
Adds a user-facing subscription/dismissal model for calendars so authenticated users can discover, subscribe, hide (dismiss), and re-subscribe to public or shared calendars. Implements new DB schema for subscriptions, updates permission logic to consider subscriptions and dismissals, and exposes APIs + client hooks and UI (discovery dialog, menu trigger, selector/settings integration) to manage visibility. Dispatches custom events and wires SSE updates so calendar lists refresh immediately. Updates account/profile flows: avatar upload support with client-side validation, profile edit UI, email update behavior, and reorders account deletion to avoid foreign-key failures. Adds translations, dependency updates, and removes an unused locked-calendar skeleton. Preserves guest behavior (guests still see public calendars automatically) and avoids automatic subscriptions/dismissals for existing data.
Adds in-memory, configurable rate limiting to protect endpoints from brute-force and abuse and integrates limits for auth, password changes, account deletion, avatar uploads, SSE, calendar creation, external syncs and PDF exports. Implements client-side helpers and UX to detect 429 responses and show friendly retry messages (with i18n), does a HEAD test for SSE before opening connections, and surfaces retry info to users. Updates migration plan to reflect completion, documents env config examples, and removes obsolete Copilot instructions. Improves security and user feedback while avoiding external dependencies.
Adds a two-tier audit/activity logging system to track security events and user actions for compliance, troubleshooting, and user transparency. Implements a new persistent audit table with indexes and typed metadata, an IP extraction helper, and an auth plugin to capture events non-blockingly. Logs key events (auth events, password changes, account deletions, calendar create/update/delete, external sync lifecycle, rate-limit hits, etc.) and exposes a user-facing activity API/UI with translations and menu integration. Also tightens redirect behavior on auth pages, increases SSE reconnect limit, and updates dependencies/migration metadata to support the changes. Benefits: provides reliable, indexed logs for admin and users, improves incident visibility, and avoids blocking request paths when recording events.
Injects server-side public configuration into the client via SSR, eliminating duplicated NEXT_PUBLIC_* env vars and preventing hydration mismatches. Adds client-facing hooks for auth/feature flags so UI reads a single source of truth, and converts server-side auth env APIs to server-only checks. Reorganizes environment example for clarity and updates validation to use raw env names. Optimizes container build with a multi-stage Dockerfile (better caching, production deps, dumb-init, healthcheck) and applies minor build/runtime tweaks (compiler target bump, console removal in production). These changes simplify config management, improve security and UX, and speed up builds/deploys.
Adds guest permission handling for calendars (persisted default "none", surfaced in create API, hooks, and UI via a GuestPermissionSelector). Updates calendar settings and creation flows to use the new selector and thread guestPermission through hooks and dialog APIs. Switches several hydration setState calls to useLayoutEffect to avoid SSR mismatches, tightens types, removes unused imports/vars, and replaces noisy catches with bare catches for robustness. Also fixes effect dependency arrays and event listener typings, and improves public config initialization/hydration to reduce edge-case fetches.
Adds server and client session utilities integrated with Better Auth to list and bulk-revoke sessions and surfaces an "Active Sessions" section in the profile so users can view devices, IPs and last activity. Uses UA parsing for readable device info, protects the current session by only allowing "revoke other sessions", updates audit metadata to include bulk revoke counts, and switches internal imports to the new session utilities. Also adds translations and package dependency for UA parsing and gates several UI pieces by the auth feature flag to keep behavior consistent when auth is disabled. Benefits: gives users visibility and control over active sessions, simplifies session logic by relying on Better Auth, and reduces accidental self-logouts by removing individual session revocation.
Strengthens CSRF and cookie security defaults, adds defense-in-depth headers/CSP, and prevents auto-sync for calendars without owners. Defaults trusted origins to the app URL to ensure origin validation and CSRF protection. Uses HTTPS detection to enable secure cookies and sets explicit cookie attributes (SameSite=Lax, secure, httpOnly). Adds security headers and a Next.js-compatible CSP in the proxy to reduce XSS, clickjacking and MIME sniffing risks. Documents the trusted-origins setting in the env example and updates the security/migration plan status. Enhances the auto-sync service to skip orphaned calendars when auth is enabled, periodically disable their auto-sync (sets interval to 0), remove jobs, and throttle cleanup runs; logs actions for auditability.
Adds a tab-based calendar share management UI and completes backend, hooks, and UX changes to centralize user shares and guest access. Adds audit-logged share APIs and user search; moves guest-permission controls into the new share sheet and defaults new calendars to private to reduce accidental public exposure. Implements client hooks, permission updates, UI components (share sheet, share list, user search), and subscription/source improvements to distinguish shared vs public calendars. Refactors activity log to use the shared Table component, updates calendar selector visuals/permission checks, enriches calendar metadata, adds translations, and includes UI/package support for tabs.
Enable authentication by default to improve security. Update environment examples and docs to reflect AUTH_ENABLED=true by default, change runtime logic to treat unspecified as enabled (only "false" disables), and gate sharing UI behind auth. Simplify migration plan to focus on orphaned-calendar handling and first-user admin flow, and remove outdated migration/phase noise.
Enables secure, low-friction calendar sharing via link-based access tokens. Implements a new calendar_access_tokens schema and migration, token generation/validation, cookie-based storage for validated tokens (httpOnly, secure, SameSite=Lax), middleware to handle /share/token links with clean redirects, permission checks that consider token grants, UI and hooks for managing tokens, rate limiting for token operations, and audit logging for token lifecycle and usage. Stores tokens as URL-safe base64 (shown once on creation) by design for improved UX while relying on DB controls and logging for security.
Adds Better Auth's admin plugin for unified role management and client support, with migrations to extend user/session schema. Auto-promotes the first registered user to superadmin via auth hooks to ensure an initial admin. Secures orphaned calendars by excluding ownerless calendars from normal APIs/UI and exposes an admin-only listing for future assignment. Enhances audit logging to record provider/method information and ensures migrations run on startup to apply schema changes.
Adds an i18n validation step to CI workflows and test scripts to catch translation issues early. Introduces a lightweight runner dependency to execute the i18n check and updates package scripts and README. Adjusts code to use correct translation keys and prunes/aligns locale files to reflect current usage, reducing stale keys and adding required ones.
Centralizes translation keys under a shared "common" namespace and adds missing locale entries to simplify and standardize UI labels across the app. Adds shared-calendar data to the admin API and client hooks (shared calendars + sharesCount), exposing sharesCount in user lists/tables with sorting and a new column to support admin views. Refactors role badge styling to use consistent utility classes and updates components to use the new translation keys and permission labels. Improves the i18n-checks script to handle template/dynamic translation keys and wildcard patterns correctly, reducing false positives when validating localization keys.
Replace scattered admin/token-specific translation keys with shared common messages and item interpolation to standardize toasts and dialogs and reduce duplication. Update UI components and hooks to use the new common keys for actions (copy, delete, fetch, create, update, revoke, transfer, ban/unban, password reset), and normalize success/error messages and clipboard feedback. Add corresponding entries and minor wording/grammar fixes to locale files (en/de/it) to support the new common message usage.
Centralizes registration control by moving signup restrictions into the auth configuration and a database hook so signups (email, OAuth, OIDC) are consistently blocked when disabled. Removes fragile pre-check logic from the auth route and keeps rate-limiting there. Adds a login banner and localized messages to inform users when registration is disabled. Updates environment examples and README/documentation to reflect auth-related env vars and deployment guidance. Improves i18n tooling to better detect dynamic/wildcard keys and report static vs. dynamic usage counts for translation audits. Benefits: simplifies route logic, ensures consistent signup enforcement across providers, improves user feedback, and cleans up docs for easier setup and migration.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This PR introduces BetterShift v2 with a comprehensive migration from password-based calendar protection to a modern session-based authentication system using Better Auth. The changes implement user authentication, role-based access control, calendar sharing capabilities, and administrative features.
Key Changes:
- Complete replacement of password-based calendar access with user authentication and sessions
- New user management system with roles (superadmin, admin, user)
- Calendar sharing features with per-user and token-based access
- Admin panel with dashboard, user management, calendar management, and audit logging
- Guest access mode for unauthenticated users when enabled
Reviewed changes
Copilot reviewed 91 out of 211 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| components/calendar-share-management-sheet.tsx | New component for managing calendar sharing with users and access tokens |
| components/calendar-share-list.tsx | Displays and manages user shares for a calendar with permission controls |
| components/calendar-settings-sheet.tsx | Refactored to remove password management and add sharing/permission features |
| components/calendar-selector.tsx | Enhanced to show ownership, share permissions, and token-based access indicators |
| components/calendar-discovery-sheet.tsx | New component for browsing and subscribing to shared/public calendars |
| components/calendar-content.tsx | Removed password-related UI elements and added guest banner |
| components/calendar-content-skeleton.tsx | Removed skeleton loading component (file deleted) |
| components/calendar-compare-view.tsx | Updated to use permission hooks instead of password checks |
| components/calendar-compare-skeleton.tsx | Removed skeleton loading component (file deleted) |
| components/auth-provider.tsx | New client-side authentication provider with session management |
| components/auth-header.tsx | Simplified header for authentication pages |
| components/app-header.tsx | Updated main header with user menu and authentication state |
| components/admin/* | Multiple new admin panel components for user management, calendar management, and audit logging |
| app/register/page.tsx | New user registration page |
| app/profile/page.tsx | New user profile page with account management |
| app/profile/activity/page.tsx | New activity log viewer for users |
| .github/workflows/release.yml | Added i18n validation check to release workflow |
| .github/workflows/pr-checks.yml | Added i18n validation check to PR workflow |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
Copilot reviewed 91 out of 211 changed files in this pull request and generated 3 comments.
… and add debug headers endpoint
BetterShift v2.0 Release Notes
Overview
BetterShift v2.0 transforms BetterShift from a single-user application into a fully-featured multi-user platform with authentication, calendar sharing, and admin management capabilities. This release maintains 100% backward compatibility - existing installations continue working without any changes.
BETTER_AUTH_SECRETandBETTER_AUTH_URLin.envbefore updating, or disable auth withAUTH_ENABLED=false. See Migration section below for details.Check out the migration guide in
docs/MIGRATION_AUTH_TOGGLE.md.Major Features
Authentication & User Management
AUTH_ENABLED=falsefor single-user modeCalendar Sharing (3 Methods)
Calendar Discovery
Admin Panel (
/admin)Full-featured interface with role-based access (Superadmin, Admin, User):
See
docs/ADMIN_PANEL.mdfor details.Security
See
docs/AUTH_SETUP.mdfor configuration.Activity Logs
Personal timeline at
/profile/activitywith merged audit + sync logs and advanced filteringUI/UX
Key Changes
NEXT_PUBLIC_duplicates)See
.env.examplefor complete configuration reference.Documentation
Complete documentation available in
/docsfolder:README.md: Quick start guide and overviewdocs/AUTH_SETUP.md: Authentication configuration (OAuth, OIDC, session management)docs/ADMIN_PANEL.md: Admin panel guide (roles, user/calendar management, audit logs)docs/PERMISSIONS.md: Permission system and sharing workflowsdocs/MIGRATION_AUTH_TOGGLE.md: Enable auth on existing installationsMigration & Compatibility
BEFORE updating to v2.0:
Add required environment variables to
.env:OR disable auth for single-user mode:
After updating:
git pull origin maindocker-compose up -d(migrations run automatically)/admin/calendars)See:
docs/MIGRATION_AUTH_TOGGLE.mdfor detailed instructions.Installation
New Installation:
Updating:
git pull origin main docker-compose up -d # Migrations run automaticallySee
README.mdanddocs/for detailed instructions.Future Enhancements
Email verification, Two-factor authentication, IP ban system, Advanced statistics, Notification system
Additional Information
Known Issues: None
Breaking Changes: Environment variables
BETTER_AUTH_SECRETandBETTER_AUTH_URLare required whenAUTH_ENABLED=true(default). Set these in.envbefore updating.License: MIT
Support: GitHub Issues | Discussions