compassmock/docs/auth/AUTH-IMPLEMENTATION.md
Nicholai 8b34becbeb
feat(agent): AI agent harness with memory, GitHub, audio & feedback (#37)
* feat(agent): replace ElizaOS with AI SDK v6 harness

Replace custom ElizaOS sidecar proxy with Vercel AI SDK v6 +
OpenRouter provider for a proper agentic harness with multi-step
tool loops, streaming, and D1 conversation persistence.

- Add AI SDK agent library (provider, tools, system prompt, catalog)
- Rewrite API route to use streamText with 10-step tool loop
- Add server actions for conversation save/load/delete
- Migrate chat-panel and dashboard-chat to useChat hook
- Add action handler dispatch for navigate/toast/render tools
- Use qwen/qwen3-coder-next via OpenRouter (fallbacks disabled)
- Delete src/lib/eliza/ (replaced entirely)
- Exclude references/ from tsconfig build

* fix(chat): improve dashboard chat scroll and text size

- Rewrite auto-scroll: pin user message 75% out of
  frame after send, then follow bottom during streaming
- Use useEffect for scroll timing (DOM guaranteed ready)
  instead of rAF which fired before React commit
- Add user scroll detection to disengage auto-scroll
- Bump assistant text from 13px back to 14px (text-sm)
- Tighten prose spacing for headings and lists

* chore: installing new components

* refactor(chat): unify into one component, two presentations

Extract duplicated chat logic into shared ChatProvider context
and useCompassChat hook. Single ChatView component renders as
full-page hero on /dashboard or sidebar panel elsewhere. Chat
state persists across navigation.

New: chat-provider, chat-view, chat-panel-shell, use-compass-chat
Delete: agent-provider, chat-panel, dashboard-chat, 8 deprecated UI files
Fix: AI component import paths (~/  -> @/), shadcn component updates

* fix(lint): resolve eslint errors in AI components

- escape unescaped entities in demo JSX (actions, artifact,
  branch, reasoning, schema-display, task)
- add eslint-disable for @ts-nocheck in vendor components
  (file-tree, terminal, persona)
- remove unused imports in chat-view (ArrowUp, Square,
  useChatPanel)

* feat(agent): rename AI to Slab, add proactive help

rename assistant from Compass to Slab and add first
interaction guidance so it proactively offers
context-aware help based on the user's current page.

* fix(build): use HTML entity for strict string children

ReasoningContent expects children: string, so JSX
expression {"'"} splits into string[] causing type error.
Use ' HTML entity instead.

* feat(agent): add memory, github, audio, feedback

- persistent memory system (remember/recall across sessions)
- github integration (commits, PRs, issues, contributors)
- audio transcription via Whisper API
- UX feedback interview flow with auto-issue creation
- memories management table in settings
- audio waveform visualization component
- new schema tables: slab_memories, feedback_interviews
- enhanced system prompt with proactive tool usage

* feat(agent): unify chat into single morphing instance

Replaces two separate ChatView instances (page + panel) with
one layout-level component that transitions between full-page
and sidebar modes. Navigation now actually works via proper
AI SDK v6 part structure detection, with view transitions for
smooth crossfades, route validation to prevent 404s, and
auto-opening the panel when leaving dashboard.

Also fixes dark mode contrast, user bubble visibility, tool
display names, input focus ring, and system prompt accuracy.

* refactor(agent): rewrite waveform as time-series viz

Replace real-time frequency equalizer with amplitude
history that fills left-to-right as user speaks.
Bars auto-calculated from container width, with
non-linear boost and scroll when full.

* (feat): implemented architecture for plugins and skills, laying a foundation for future implementations of packages separate from the core application

* feat(agent): add skills.sh integration for slab

Skills client fetches SKILL.md from GitHub, parses
YAML frontmatter, and stores content in plugin DB.
Registry injects skill content into system prompt.
Agent tools and settings UI for skill management.

* feat(agent): add interactive UI action bridge

Wire agent-generated UIs to real server actions via
an action bridge API route. Forms submit, checkboxes
persist, and DataTable rows support CRUD operations.

- action-registry.ts: maps 19 dotted action names to
  server actions with zod validation + permissions
- /api/agent/action: POST route with auth, permission
  checks, schema validation, and action execution
- schema-agent.ts: agent_items table for user-scoped
  todos, notes, and checklists
- agent-items.ts: CRUD + toggle actions for agent items
- form-context.ts: FormIdProvider for input namespacing
- catalog.ts: Form component, value/onChangeAction props,
  DataTable rowActions, mutate/confirmDelete actions
- registry.tsx: useDataBinding on all form inputs, Form
  component, DataTable row action buttons, inline
  Checkbox/Switch mutations
- actions.ts: mutate + confirmDelete handlers that call
  the action bridge, formSubmit now collects + submits
- system-prompt.ts: interactive UI patterns section
- render/route.ts: interactive pattern custom rules

* docs: reorganize into topic subdirectories

Move docs into auth/, chat/, openclaw-principles/,
and ui/ subdirectories. Add openclaw architecture
and system prompt documentation.

* feat(agent): add commit diff support to github tools

Add fetchCommitDiff to github client with raw diff
fallback for missing patches. Wire commit_diff query
type into agent github tools.

* fix(ci): guard wrangler proxy init for dev only

initOpenNextCloudflareForDev() was running unconditionally
in next.config.ts, causing CI build and lint to fail with
"You must be logged in to use wrangler dev in remote mode".
Only init the proxy when NODE_ENV is development.

---------

Co-authored-by: Nicholai <nicholaivogelfilms@gmail.com>
2026-02-06 17:04:04 -07:00

6.6 KiB
Executable File

Authentication System Implementation

Overview

Custom authentication system integrated with WorkOS API, replacing hosted UI with mobile-first custom pages that match Compass design language.

Implemented Features

Phase 1: Foundation

  • WorkOS client wrapper (src/lib/workos-client.ts)
  • Auth layout with centered card (src/app/(auth)/layout.tsx)
  • Reusable password input with visibility toggle (src/components/auth/password-input.tsx)

Phase 2: Login Flow

  • Login API endpoint (src/app/api/auth/login/route.ts)
  • Password login form (src/components/auth/login-form.tsx)
  • Passwordless login form with 6-digit codes (src/components/auth/passwordless-form.tsx)
  • Login page with tabs (src/app/(auth)/login/page.tsx)

Phase 3: Signup & Verification

  • Signup API endpoint (src/app/api/auth/signup/route.ts)
  • Email verification API endpoint (src/app/api/auth/verify-email/route.ts)
  • Signup form with validation (src/components/auth/signup-form.tsx)
  • Email verification form (src/components/auth/verify-email-form.tsx)
  • Signup page (src/app/(auth)/signup/page.tsx)
  • Verification page (src/app/(auth)/verify-email/page.tsx)

Phase 4: Password Reset

  • Password reset request API (src/app/api/auth/password-reset/route.ts)
  • Password reset confirmation API (src/app/api/auth/reset-password/route.ts)
  • Reset request form (src/components/auth/reset-password-form.tsx)
  • Set new password form (src/components/auth/set-password-form.tsx)
  • Reset password pages (src/app/(auth)/reset-password/)

Phase 5: Invite Acceptance

  • Invite acceptance API (src/app/api/auth/accept-invite/route.ts)
  • Invite form (src/components/auth/invite-form.tsx)
  • Invite page (src/app/(auth)/invite/[token]/page.tsx)

Phase 6: Middleware & Polish

  • Route protection middleware (src/middleware.ts)
  • Security headers (X-Frame-Options, X-Content-Type-Options, HSTS)
  • Helper functions in src/lib/auth.ts (requireAuth, requireEmailVerified)
  • OAuth callback route (src/app/api/auth/callback/route.ts)
  • Updated wrangler.jsonc with WORKOS_REDIRECT_URI

Dev Mode Functionality

All authentication flows work in development mode without WorkOS credentials:

  • Login redirects to dashboard immediately
  • Signup creates mock users
  • Protected routes are accessible
  • All forms validate correctly

Production Deployment Checklist

1. WorkOS Configuration

Set these secrets via wrangler secret put:

wrangler secret put WORKOS_API_KEY
# Enter: sk_live_...

wrangler secret put WORKOS_CLIENT_ID
# Enter: client_...

wrangler secret put WORKOS_COOKIE_PASSWORD
# Enter: [32+ character random string]

Generate cookie password:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

2. Environment Variables

Already configured in wrangler.jsonc:

  • WORKOS_REDIRECT_URI: https://compass.openrangeconstruction.ltd/api/auth/callback

3. WorkOS Dashboard Setup

  1. Go to https://dashboard.workos.com
  2. Create a new organization (or use existing)
  3. Configure redirect URI: https://compass.openrangeconstruction.ltd/api/auth/callback
  4. Enable authentication methods:
    • Email/Password
    • Magic Auth (passwordless codes)
  5. Copy Client ID and API Key

4. Cloudflare Rate Limiting

Configure rate limiting rules in Cloudflare dashboard:

  • /api/auth/login: 5 attempts per 15 minutes per IP
  • /api/auth/signup: 3 attempts per hour per IP
  • /api/auth/password-reset: 3 attempts per hour per IP

5. Test Production Auth Flow

  1. Deploy to production: bun run deploy
  2. Navigate to login page
  3. Test password login
  4. Test passwordless login
  5. Test signup flow
  6. Test email verification
  7. Test password reset
  8. Verify protected routes redirect to login

6. Invite Users

Use existing People page to invite users:

  1. Go to /dashboard/people
  2. Click "Invite User"
  3. User receives WorkOS invitation email
  4. User accepts via /invite/[token] page

Security Features

  • HTTPS-only (enforced via Cloudflare)
  • CSRF protection (Next.js built-in + WorkOS)
  • Rate limiting (via Cloudflare rules - needs setup)
  • Password strength validation (8+ chars, uppercase, lowercase, number)
  • Code expiration (10 minutes for magic auth)
  • Session rotation (WorkOS handles refresh tokens)
  • Secure headers (X-Frame-Options, HSTS, nosniff)
  • Email verification enforcement (via middleware)
  • Cookie encryption (AES-GCM via WORKOS_COOKIE_PASSWORD)

Mobile Optimizations

  • 44px touch targets for primary actions
  • 16px input text (prevents iOS zoom)
  • Responsive layouts (flex-col sm:flex-row)
  • Proper keyboard types (email, password, numeric)
  • Auto-submit on 6-digit code completion
  • Full-width buttons on mobile

Known Issues

None currently. All lint errors have been fixed.

Next Steps (Future Enhancements)

  1. Add 2FA/MFA support (WorkOS supports this)
  2. Add OAuth providers (Google, Microsoft) for SSO
  3. Add audit logging for sensitive auth events
  4. Implement session timeout warnings
  5. Add "remember me" functionality
  6. Add account lockout after failed attempts
  7. Add "Login with passkey" support

Files Created

Core Infrastructure

  • src/lib/workos-client.ts
  • src/app/(auth)/layout.tsx
  • src/components/auth/password-input.tsx

Login

  • src/app/api/auth/login/route.ts
  • src/components/auth/login-form.tsx
  • src/components/auth/passwordless-form.tsx
  • src/app/(auth)/login/page.tsx

Signup & Verification

  • src/app/api/auth/signup/route.ts
  • src/app/api/auth/verify-email/route.ts
  • src/components/auth/signup-form.tsx
  • src/components/auth/verify-email-form.tsx
  • src/app/(auth)/signup/page.tsx
  • src/app/(auth)/verify-email/page.tsx

Password Reset

  • src/app/api/auth/password-reset/route.ts
  • src/app/api/auth/reset-password/route.ts
  • src/components/auth/reset-password-form.tsx
  • src/components/auth/set-password-form.tsx
  • src/app/(auth)/reset-password/page.tsx
  • src/app/(auth)/reset-password/[token]/page.tsx

Invites

  • src/app/api/auth/accept-invite/route.ts
  • src/components/auth/invite-form.tsx
  • src/app/(auth)/invite/[token]/page.tsx

OAuth

  • src/app/api/auth/callback/route.ts

Files Modified

  • src/lib/auth.ts - Added requireAuth() and requireEmailVerified()
  • src/middleware.ts - Added route protection and security headers
  • wrangler.jsonc - Added WORKOS_REDIRECT_URI variable

Testing in Dev Mode

All authentication pages are accessible at:

Dev server running on port 3004 (3000 was in use).