UNPKG

@spectrumsense/spectrum-chat-dev

Version:

Embeddable AI Widget - Add trusted, evidence-based answers directly to your website. Simple installation, enterprise-grade security.

576 lines (404 loc) 15.4 kB
# Migration Guide: Legacy to Security-Enhanced Spectrum Chat **Version:** 1.0 **Migration Date:** October 6, 2025 --- ## Table of Contents 1. [Overview](#overview) 2. [Migration Checklist](#migration-checklist) 3. [Phase 0: Basic Security (Required)](#phase-0-basic-security-required) 4. [Phase 1: Enhanced Security (Optional)](#phase-1-enhanced-security-optional) 5. [Testing Your Migration](#testing-your-migration) 6. [Rollback Plan](#rollback-plan) 7. [FAQ](#faq) --- ## Overview This guide helps you migrate from the legacy Spectrum Chat implementation to the new security-enhanced version with: - **Phase 0**: Site-key + Origin validation (Required) - **Phase 1**: JWT session tokens (Optional) ### What's Changing? | Feature | Legacy | New (Phase 0) | New (Phase 1) | |---------|--------|---------------|---------------| | Authentication | `tenant_id` only | `siteKey` + Origin | `siteKey` + Origin + JWT | | Origin validation | None | Automatic | Automatic | | Token management | None | Not used | Auto-managed | | Conversation binding | None | Origin-bound | Origin-bound | | Error handling | Basic | Enhanced | Enhanced | | Auto-retry | None | Yes | Yes | ### Backward Compatibility **Good news!** The `tenant_id` parameter is still supported for backward compatibility. You can migrate gradually. --- ## Migration Checklist ### Pre-Migration - [ ] **Get your site key** from the API administrator - [ ] **Verify allowed origins** are configured server-side - [ ] **Review current implementation** (custom element or global mode) - [ ] **Plan testing** on staging environment - [ ] **Backup current implementation** (version control) - [ ] **Review error handling** requirements ### Migration Steps - [ ] **Update to latest version** of Spectrum Chat - [ ] **Add site key** to configuration - [ ] **Test on staging** environment - [ ] **Monitor for errors** in browser console - [ ] **Test all user flows** (open widget, send message, continue conversation) - [ ] **Deploy to production** during low-traffic period - [ ] **Monitor production** for 24-48 hours - [ ] **(Optional) Enable JWT** for Phase 1 ### Post-Migration - [ ] **Verify functionality** across all pages - [ ] **Check analytics** for any drop in usage - [ ] **Monitor error logs** for any issues - [ ] **Update documentation** for your team - [ ] **Remove tenant_id** if no longer needed (optional) --- ## Phase 0: Basic Security (Required) ### Step 1: Get Your Site Key Contact your API administrator or check the Django admin panel to get your site key. **Site key format:** `pub_customer_a1b2c3d4` ### Step 2: Verify Allowed Origins Ensure your domain(s) are added to the allowed origins list on the server: ```python # Server-side configuration (example) organization.allowed_origins = [ "https://www.yoursite.com", "https://app.yoursite.com", "https://yoursite.com", "http://localhost:3000" # For development ] ``` ### Step 3: Update Widget Configuration #### Option A: Custom Element (Plain HTML) **Before:** ```html <spectrum-chat api-url="https://api.yoursite.com/api/v1/conversations" tenant-id="your-tenant-id" title="AI Assistant"> </spectrum-chat> ``` **After:** ```html <spectrum-chat api-url="https://api.yoursite.com/api/v1/conversations" site-key="pub_customer_a1b2c3d4" tenant-id="your-tenant-id" title="AI Assistant" citations="true"> </spectrum-chat> ``` **Changes:** - Added `site-key` attribute (required) - Kept `tenant-id` for backward compatibility - Added `citations="true"` (recommended) #### Option B: Global Script (Template Integration) **Before:** ```html <script> window.SpectrumChatConfig = { apiUrl: 'https://api.yoursite.com/api/v1/conversations', tenantId: 'your-tenant-id', title: 'AI Assistant' }; </script> <script src="https://unpkg.com/@spectrumsense/spectrum-chat@latest/dist/spectrum-chat.js"></script> ``` **After:** ```html <script> window.SpectrumChatConfig = { apiUrl: 'https://api.yoursite.com/api/v1/conversations', siteKey: 'pub_customer_a1b2c3d4', tenantId: 'your-tenant-id', // Optional, for backward compatibility title: 'AI Assistant', enableCitations: true, useJWT: false // Phase 0 }; </script> <script src="https://unpkg.com/@spectrumsense/spectrum-chat@latest/dist/spectrum-chat.js"></script> ``` **Changes:** - Added `siteKey` property (required) - Kept `tenantId` for backward compatibility - Added `enableCitations: true` (recommended) - Added `useJWT: false` (explicit Phase 0) ### Step 4: Test on Staging Deploy to staging environment and test: 1. **Open the widget** - Should load without errors 2. **Send a message** - Should receive response 3. **Continue conversation** - Should maintain context 4. **Check browser console** - No errors 5. **Test from different pages** - Should work consistently 6. **Test on mobile** - Should work on all devices #### Enable Debug Mode for Testing ```html <spectrum-chat api-url="..." site-key="..." debug="true"> </spectrum-chat> ``` Check browser console for: ``` Sending message: ... API URL: https://... Request body: {...} Response data: {...} New conversation started: c_abc123... ``` ### Step 5: Deploy to Production 1. **Choose low-traffic time** (e.g., late night, weekend) 2. **Deploy the update** 3. **Monitor immediately** after deployment 4. **Test from production URL** 5. **Check error logs** ### Step 6: Monitor Monitor for 24-48 hours: - Widget loading successfully - Messages being sent and received - No 403 errors (origin validation) - No 404 errors (site key issues) - Conversations continuing properly --- ## Phase 1: Enhanced Security (Optional) After successfully migrating to Phase 0, you can optionally enable JWT tokens for enhanced security. ### Why Enable Phase 1? - Better audit trails - Server-side token revocation - Time-limited access (1 hour default) - Enhanced security posture ### Step 1: Update Configuration #### Custom Element ```html <spectrum-chat api-url="https://api.yoursite.com/api/v1/conversations" site-key="pub_customer_a1b2c3d4" use-jwt="true" title="AI Assistant" citations="true"> </spectrum-chat> ``` #### Global Script ```html <script> window.SpectrumChatConfig = { apiUrl: 'https://api.yoursite.com/api/v1/conversations', siteKey: 'pub_customer_a1b2c3d4', useJWT: true, // Enable JWT title: 'AI Assistant', enableCitations: true }; </script> <script src="https://unpkg.com/@spectrumsense/spectrum-chat@latest/dist/spectrum-chat.js"></script> ``` ### Step 2: Test JWT Flow Enable debug mode and verify: ```javascript // Check token status const chat = window.SpectrumChatGlobal; console.log('Token valid:', chat.isTokenValid()); console.log('Session ID:', chat.getSessionId()); console.log('Token data:', chat.getTokenData()); ``` Expected console output: ``` Creating session with API URL: https://api.yoursite.com/api/v1/sessions Session created: {session_id: "...", expires_at: "..."} Saved token data: {session_id: "...", expires_at: "..."} Token valid: true ``` ### Step 3: Test Token Refresh JWT tokens expire after 1 hour (default). Test auto-refresh: 1. **Open widget** - Token created 2. **Wait 56+ minutes** - Token should auto-refresh 3. **Send message** - Should work without error Or manually test token expiration: ```javascript // Simulate token expiration const chat = window.SpectrumChatGlobal; chat.clearSession(); // Clear token // Send a message - should create new token automatically ``` ### Step 4: Deploy and Monitor Same process as Phase 0: 1. Test on staging 2. Deploy during low-traffic time 3. Monitor for 24-48 hours 4. Verify token creation and refresh --- ## Testing Your Migration ### Test Scenarios #### Test 1: Basic Functionality 1. Open widget 2. Send message: "Hello" 3. Verify response received 4. Continue conversation: "What can you help with?" 5. Verify context maintained **Expected:** No errors, smooth conversation #### Test 2: Page Reload 1. Open widget and send message 2. Reload page 3. Open widget again 4. Send another message 5. Verify conversation continues (same conversation_id) **Expected:** Conversation persists across reloads #### Test 3: New Tab 1. Open widget and send message in Tab A 2. Open same page in Tab B 3. Open widget in Tab B 4. Send message in Tab B **Expected:** Each tab has independent conversation #### Test 4: Error Handling **Test 4a: Network Error** 1. Disconnect internet 2. Send message 3. Reconnect 4. Send message again **Expected:** User-friendly error, then success **Test 4b: Invalid Site Key** (staging only) 1. Use wrong site key 2. Try to send message **Expected:** "Chat service is currently unavailable" **Test 4c: Wrong Origin** (staging only) 1. Test from unauthorized domain **Expected:** "This domain is not authorized" #### Test 5: JWT Token Flow (Phase 1 only) 1. Open widget (token created) 2. Check console for session creation 3. Send message (uses token) 4. Wait 56 minutes (token auto-refreshes) 5. Send message (uses new token) **Expected:** Seamless operation, no user-visible refresh ### Debug Console Commands ```javascript // Get widget API const chat = window.SpectrumChatGlobal; // Check configuration console.log('Config:', chat.getConfig()); // Check conversation state console.log('Conversation ID:', chat.getConversationId()); console.log('Session ID:', chat.getSessionId()); // Check token status (Phase 1) console.log('Token valid:', chat.isTokenValid()); console.log('Token data:', chat.getTokenData()); // Clear session chat.clearSession(); console.log('Session cleared'); // Reinitialize chat.reinitialize(); ``` --- ## Rollback Plan If you encounter issues, here's how to rollback: ### Immediate Rollback (Keep Old Code) If you kept your old code in version control: ```bash # Rollback to previous version git revert HEAD git push ``` ### Temporary Fix (Disable Security) If you need time to fix issues, you can temporarily keep the old implementation: ```html <!-- Fallback to legacy if needed --> <script src="https://unpkg.com/@spectrumsense/spectrum-chat@0.1.1/dist/spectrum-chat.js"></script> ``` **Note:** This is not recommended for long-term use due to security concerns. ### Partial Rollback (Phase 1 to Phase 0) If JWT tokens cause issues, disable them: ```html <!-- Keep Phase 0, disable Phase 1 --> <spectrum-chat api-url="..." site-key="..." use-jwt="false"> </spectrum-chat> ``` --- ## FAQ ### Q: Do I need to update immediately? **A:** Yes, if you're using a public-facing application. The new security model prevents unauthorized use of your chat service. ### Q: Will this break my existing implementation? **A:** No. The widget maintains backward compatibility with `tenant_id`. However, you should add `site-key` for security. ### Q: What happens if I don't add the site key? **A:** Your widget will continue to work with `tenant_id` for backward compatibility, but you won't have origin validation security. ### Q: Can I use both tenant_id and site-key? **A:** Yes! The widget supports both for backward compatibility. However, `site-key` takes precedence for security. ### Q: How do I get a site key? **A:** Contact your API administrator or check the Django admin panel at `/admin/tenants/organization/`. ### Q: What if my domain isn't in the allowed origins list? **A:** You'll get a `403 Forbidden` error with message "This domain is not authorized". Contact your API administrator to add your domain. ### Q: Do I need HTTPS for development? **A:** No. HTTP is allowed for `localhost` and `127.0.0.1` for development purposes. ### Q: Should I enable JWT (Phase 1)? **A:** Yes, for production. Phase 1 provides better security, audit trails, and token management. However, Phase 0 is sufficient for basic needs. ### Q: How long do JWT tokens last? **A:** Default is 1 hour. The widget automatically refreshes tokens 5 minutes before expiration. ### Q: What happens when a token expires? **A:** The widget detects the 401 error, creates a new session, and retries the request automatically. The user never sees an error. ### Q: Will conversations persist across sessions? **A:** Conversations are stored server-side and persist as long as they're in the server cache (LRU). When using `sessionStorage`, the conversation ID persists for the browser session. ### Q: Can users continue conversations after closing the browser? **A:** By default, no (using `sessionStorage`). If you want conversations to persist, the server maintains them in cache, but the conversation ID is cleared from browser storage when the tab closes. ### Q: How do I clear a user's session? **A:** Call `SpectrumChatGlobal.clearSession()` which clears the conversation ID, token, and messages from storage. ### Q: What if my API endpoint is different? **A:** Just update the `api-url` attribute. The widget constructs the correct endpoints: - `/api/v1/sessions` for token creation - `/api/v1/conversations` for starting conversations - `/api/v1/conversations/{id}` for continuing conversations ### Q: Can I test on localhost with HTTP? **A:** Yes! HTTP is allowed for `localhost` and `127.0.0.1` during development. ### Q: How do I enable debug mode? **A:** Add `debug="true"` attribute: ```html <spectrum-chat debug="true"></spectrum-chat> ``` ### Q: Where can I see the debug output? **A:** Open browser Developer Tools (F12) and check the Console tab. ### Q: What browsers are supported? **A:** All modern browsers that support: - Web Crypto API (for SHA256 hashing) - sessionStorage/localStorage - Fetch API - ES6+ JavaScript ### Q: Is the site key secret? **A:** No! The site key is **public** and designed to be included in client-side code. Security comes from origin validation, not site key secrecy. ### Q: Can someone steal my site key? **A:** Yes, anyone can view your site key in the HTML source. However, they cannot use it from their domain because: 1. The API validates the `Origin` header 2. Only domains in your allowed origins list can use your site key ### Q: What if I need help? **A:** 1. Check this migration guide 2. Review [SECURITY_IMPLEMENTATION.md](./SECURITY_IMPLEMENTATION.md) 3. Enable debug mode and check console 4. Contact Spectrum Chat support --- ## Success Indicators After migration, you should see: Widget loads without errors Messages send and receive successfully Conversations persist across page reloads No 403 origin validation errors No 404 site key errors Token auto-refresh working (Phase 1) Error messages are user-friendly Debug logs show proper flow (when enabled) --- ## Next Steps After successful migration: 1. **Monitor** for 1-2 weeks 2. **Remove** `tenant_id` if no longer needed 3. **Enable Phase 1** if not already done 4. **Update documentation** for your team 5. **Review** error logs periodically 6. **Consider** additional customization --- ## Support Need help with migration? - 📧 Email: support@spectrumsense.com - 📚 Docs: [SECURITY_IMPLEMENTATION.md](./SECURITY_IMPLEMENTATION.md) - 🔧 Debug: Enable `debug="true"` in widget --- **Last Updated:** October 6, 2025 **Version:** 1.0.0