Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: auto-configure Google OAuth via CDP browser with guided wizard
Adam Eivyca549065a75b
diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsxindex 470df9c0f8..7601c394b0 100644--- a/client/src/components/calendar/ConfigTab.jsx+++ b/client/src/components/calendar/ConfigTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect } from 'react';-import { Plus, Trash2, RefreshCw, Globe, Calendar, Eye, EyeOff, ChevronDown, ChevronRight, Search, Key, ExternalLink } from 'lucide-react';+import { Plus, Trash2, RefreshCw, Globe, Calendar, Eye, EyeOff, ChevronDown, ChevronRight, Search, Key, ExternalLink, Wand2, Monitor } from 'lucide-react';import toast from 'react-hot-toast';import * as api from '../../services/api';@@ -18,6 +18,8 @@ export default function ConfigTab({ accounts, setAccounts }) {const [showOAuthSetup, setShowOAuthSetup] = useState(null);const [oauthForm, setOauthForm] = useState({ clientId: '', clientSecret: '' });const [savingOAuth, setSavingOAuth] = useState(false);+ const [autoConfigStep, setAutoConfigStep] = useState(null); // null | 'launching' | 'login' | 'project' | 'api' | 'consent' | 'credentials' | 'capturing' | 'done'+ const [autoConfigBusy, setAutoConfigBusy] = useState(false);const fetchGoogleAuth = async () => {const status = await api.getGoogleAuthStatus().catch(() => null);@@ -64,6 +66,41 @@ export default function ConfigTab({ accounts, setAccounts }) {toast.success(`Sync method set to ${method === 'google-api' ? 'Google API' : 'Claude MCP'}`);};+ const handleAutoConfigStart = async () => {+ setAutoConfigBusy(true);+ const result = await api.startGoogleAutoConfig().catch(() => null);+ setAutoConfigBusy(false);+ if (!result || result.error) {+ return toast.error(result?.error || 'Failed to open browser');+ }+ setAutoConfigStep('login');+ toast.success('Google Cloud Console opened in PortOS browser');+ };++ const handleAutoConfigNavigate = async (step) => {+ setAutoConfigBusy(true);+ await api.navigateGoogleAutoConfig(step).catch(() => null);+ setAutoConfigBusy(false);+ setAutoConfigStep(step === 'enable-api' ? 'api' : step === 'credentials' ? 'consent' : 'credentials');+ };++ const handleAutoConfigCapture = async () => {+ setAutoConfigBusy(true);+ const result = await api.captureGoogleCredentials().catch(() => null);+ setAutoConfigBusy(false);+ if (!result || result.error) {+ return toast.error(result?.error || 'Could not capture credentials');+ }+ toast.success('OAuth credentials captured!');+ setAutoConfigStep('done');+ fetchGoogleAuth();+ // Open auth URL if available+ if (result.authUrl) {+ window.open(result.authUrl, '_blank');+ toast.success('Complete Google authorization in the opened tab');+ }+ };+const handleCreate = async () => {if (!form.name) return toast.error('Name is required');setSaving(true);@@ -328,73 +365,120 @@ export default function ConfigTab({ accounts, setAccounts }) {</button></div>) : (- <div className="space-y-2">+ <div className="space-y-3"><div className="text-xs text-gray-500">Connect directly to Google Calendar API for fast, reliable syncing without Claude.</div>- <details className="text-xs text-gray-600" open>- <summary className="cursor-pointer text-gray-400 hover:text-white font-medium">How to set up Google OAuth</summary>- <div className="mt-2 space-y-2 pl-1">- <div className="font-medium text-gray-400">Step 1: Create a Google Cloud Project</div>- <ol className="space-y-0.5 pl-4 list-decimal text-gray-600">- <li>Go to <span className="text-gray-400">console.cloud.google.com</span></li>- <li>Click the project dropdown at the top → <span className="text-gray-400">New Project</span></li>- <li>Name it anything (e.g. "PortOS Calendar") → <span className="text-gray-400">Create</span></li>- </ol>- <div className="font-medium text-gray-400">Step 2: Enable the Calendar API</div>- <ol className="space-y-0.5 pl-4 list-decimal text-gray-600">- <li>In your project, go to <span className="text-gray-400">APIs & Services → Library</span></li>- <li>Search for <span className="text-gray-400">Google Calendar API</span> → click it → <span className="text-gray-400">Enable</span></li>- </ol>+ {/* Auto-Configure with Browser */}+ {!autoConfigStep ? (+ <button+ onClick={handleAutoConfigStart}+ disabled={autoConfigBusy}+ className="flex items-center gap-1.5 w-full px-3 py-2 text-xs rounded bg-port-accent/10 text-port-accent hover:bg-port-accent/20 border border-port-accent/20 disabled:opacity-50"+ >+ {autoConfigBusy ? <RefreshCw size={14} className="animate-spin" /> : <Monitor size={14} />}+ Setup with PortOS Browser (guided)+ </button>+ ) : autoConfigStep !== 'done' && (+ <div className="space-y-2 p-2.5 bg-port-bg/80 rounded border border-port-border">+ <div className="flex items-center gap-1.5 text-xs font-medium text-port-accent">+ <Wand2 size={12} />+ Guided Setup via PortOS Browser+ </div>+ <div className="space-y-1.5 text-xs">+ <div className={`flex items-center gap-2 ${autoConfigStep === 'login' ? 'text-white' : 'text-gray-600'}`}>+ <span className={`w-4 h-4 rounded-full flex items-center justify-center text-[10px] shrink-0 ${autoConfigStep === 'login' ? 'bg-port-accent text-white' : 'bg-gray-700 text-gray-500'}`}>1</span>+ Log in to Google Cloud Console in the browser window+ </div>+ <div className={`flex items-center gap-2 ${autoConfigStep === 'project' ? 'text-white' : 'text-gray-600'}`}>+ <span className={`w-4 h-4 rounded-full flex items-center justify-center text-[10px] shrink-0 ${autoConfigStep === 'project' ? 'bg-port-accent text-white' : 'bg-gray-700 text-gray-500'}`}>2</span>+ Create a project (or select existing)+ </div>+ <div className={`flex items-center gap-2 ${autoConfigStep === 'api' ? 'text-white' : 'text-gray-600'}`}>+ <span className={`w-4 h-4 rounded-full flex items-center justify-center text-[10px] shrink-0 ${autoConfigStep === 'api' ? 'bg-port-accent text-white' : 'bg-gray-700 text-gray-500'}`}>3</span>+ Enable the Google Calendar API+ </div>+ <div className={`flex items-center gap-2 ${autoConfigStep === 'consent' ? 'text-white' : 'text-gray-600'}`}>+ <span className={`w-4 h-4 rounded-full flex items-center justify-center text-[10px] shrink-0 ${autoConfigStep === 'consent' ? 'bg-port-accent text-white' : 'bg-gray-700 text-gray-500'}`}>4</span>+ Configure OAuth consent screen (External, add yourself as test user)+ </div>+ <div className={`flex items-center gap-2 ${autoConfigStep === 'credentials' ? 'text-white' : 'text-gray-600'}`}>+ <span className={`w-4 h-4 rounded-full flex items-center justify-center text-[10px] shrink-0 ${autoConfigStep === 'credentials' ? 'bg-port-accent text-white' : 'bg-gray-700 text-gray-500'}`}>5</span>+ Create OAuth client ID (Web app) with redirect URI:+ </div>+ <code className="block px-2 py-1 bg-port-bg rounded text-gray-400 select-all text-[10px] ml-6">+ http://localhost:5555/api/calendar/google/oauth/callback+ </code>+ </div>- <div className="font-medium text-gray-400">Step 3: Configure OAuth Consent Screen</div>- <ol className="space-y-0.5 pl-4 list-decimal text-gray-600">- <li>Go to <span className="text-gray-400">APIs & Services → OAuth consent screen</span></li>- <li>Select <span className="text-gray-400">External</span> → Create</li>- <li>Fill in app name (e.g. "PortOS"), your email for support/developer contact</li>- <li>Skip scopes, add your Google email as a <span className="text-gray-400">Test user</span></li>- <li>Save and continue through the remaining steps</li>- </ol>+ <div className="flex flex-wrap gap-1.5 pt-1">+ <button+ onClick={() => { setAutoConfigStep('project'); handleAutoConfigNavigate('enable-api'); }}+ disabled={autoConfigBusy}+ className="px-2 py-1 text-[10px] rounded bg-gray-700 text-gray-300 hover:bg-gray-600 disabled:opacity-50"+ >+ Open Calendar API+ </button>+ <button+ onClick={() => handleAutoConfigNavigate('credentials')}+ disabled={autoConfigBusy}+ className="px-2 py-1 text-[10px] rounded bg-gray-700 text-gray-300 hover:bg-gray-600 disabled:opacity-50"+ >+ Open Credentials+ </button>+ <button+ onClick={() => handleAutoConfigNavigate('create-client')}+ disabled={autoConfigBusy}+ className="px-2 py-1 text-[10px] rounded bg-gray-700 text-gray-300 hover:bg-gray-600 disabled:opacity-50"+ >+ Create OAuth Client+ </button>+ <button+ onClick={handleAutoConfigCapture}+ disabled={autoConfigBusy}+ className="flex items-center gap-1 px-2 py-1 text-[10px] rounded bg-port-success/20 text-port-success hover:bg-port-success/30 disabled:opacity-50"+ >+ {autoConfigBusy ? <RefreshCw size={10} className="animate-spin" /> : <Wand2 size={10} />}+ Capture Credentials+ </button>+ </div>+ <button+ onClick={() => setAutoConfigStep(null)}+ className="text-[10px] text-gray-600 hover:text-gray-400"+ >+ Cancel guided setup+ </button>+ </div>+ )}- <div className="font-medium text-gray-400">Step 4: Create OAuth Credentials</div>- <ol className="space-y-0.5 pl-4 list-decimal text-gray-600">- <li>Go to <span className="text-gray-400">APIs & Services → Credentials</span></li>- <li>Click <span className="text-gray-400">+ Create Credentials → OAuth client ID</span></li>- <li>Application type: <span className="text-gray-400">Web application</span></li>- <li>Under <span className="text-gray-400">Authorized redirect URIs</span>, add:</li>- </ol>- <code className="block px-2 py-1 bg-port-bg rounded text-gray-400 select-all">- http://localhost:5555/api/calendar/google/oauth/callback- </code>- <ol className="space-y-0.5 pl-4 list-decimal text-gray-600" start={5}>- <li>Click <span className="text-gray-400">Create</span>, then copy the Client ID and Client Secret below</li>- </ol>+ {/* Manual setup (always available as fallback) */}+ <details className="text-xs text-gray-600">+ <summary className="cursor-pointer text-gray-400 hover:text-white font-medium">Manual setup (paste credentials)</summary>+ <div className="mt-2 space-y-1.5">+ <input+ type="text"+ value={oauthForm.clientId}+ onChange={e => setOauthForm(f => ({ ...f, clientId: e.target.value }))}+ placeholder="Client ID (e.g. 123456789-abc.apps.googleusercontent.com)"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white placeholder-gray-600"+ />+ <input+ type="password"+ value={oauthForm.clientSecret}+ onChange={e => setOauthForm(f => ({ ...f, clientSecret: e.target.value }))}+ placeholder="Client Secret (e.g. GOCSPX-...)"+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white placeholder-gray-600"+ />+ <button+ onClick={handleSaveOAuthCredentials}+ disabled={savingOAuth || !oauthForm.clientId || !oauthForm.clientSecret}+ className="flex items-center gap-1 px-2.5 py-1 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50"+ >+ {savingOAuth ? 'Saving...' : 'Save & Authorize'}+ </button></div></details>- <div className="space-y-1.5 pt-1">- <input- type="text"- value={oauthForm.clientId}- onChange={e => setOauthForm(f => ({ ...f, clientId: e.target.value }))}- placeholder="Client ID (e.g. 123456789-abc.apps.googleusercontent.com)"- className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white placeholder-gray-600"- />- <input- type="password"- value={oauthForm.clientSecret}- onChange={e => setOauthForm(f => ({ ...f, clientSecret: e.target.value }))}- placeholder="Client Secret (e.g. GOCSPX-...)"- className="w-full bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white placeholder-gray-600"- />- <button- onClick={handleSaveOAuthCredentials}- disabled={savingOAuth || !oauthForm.clientId || !oauthForm.clientSecret}- className="flex items-center gap-1 px-2.5 py-1 text-xs rounded bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50"- >- {savingOAuth ? 'Saving...' : 'Save & Authorize'}- </button>- </div></div>)}</div>diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 1f35e9b0c3..474d03084b 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1741,6 +1741,9 @@ export const getGoogleAuthUrl = () => request('/calendar/google/auth/url');export const clearGoogleAuth = () => request('/calendar/google/auth/clear', { method: 'POST' });export const apiSyncGoogleCalendar = (accountId) => request(`/calendar/sync/${accountId}/api`, { method: 'POST' });export const apiDiscoverCalendars = (accountId) => request(`/calendar/sync/${accountId}/discover-api`, { method: 'POST' });+export const startGoogleAutoConfig = () => request('/calendar/google/auto-configure/start', { method: 'POST' });+export const navigateGoogleAutoConfig = (step) => request('/calendar/google/auto-configure/navigate', { method: 'POST', body: JSON.stringify({ step }) });+export const captureGoogleCredentials = () => request('/calendar/google/auto-configure/capture', { method: 'POST' });export const getDailyReview = (date) => request(`/calendar/review/${date}`);export const confirmDailyReviewEvent = (date, data) => request(`/calendar/review/${date}/confirm`, { method: 'POST', body: JSON.stringify(data) });export const getDailyReviewHistory = (params = {}) => {diff --git a/server/routes/calendar.js b/server/routes/calendar.jsindex acead3474d..96554af005 100644--- a/server/routes/calendar.js+++ b/server/routes/calendar.js@@ -8,6 +8,7 @@ import * as calendarGoogleSync from '../services/calendarGoogleSync.js';import * as dailyReview from '../services/dailyReview.js';import * as googleAuth from '../services/googleAuth.js';import * as calendarGoogleApiSync from '../services/calendarGoogleApiSync.js';+import * as googleOAuthAutoConfig from '../services/googleOAuthAutoConfig.js';import { getToken, getTokenStatus, clearTokenCache } from '../services/messageTokenExtractor.js';const router = express.Router();@@ -256,6 +257,30 @@ router.post('/google/auth/clear', asyncHandler(async (req, res) => {res.json({ cleared: true });}));+// === Google OAuth Auto-Configure via CDP Browser ===+router.post('/google/auto-configure/start', asyncHandler(async (req, res) => {+ const io = req.app.get('io');+ const result = await googleOAuthAutoConfig.startAutoConfig(io);+ if (result.error) return res.status(result.status || 500).json({ error: result.error });+ res.json(result);+}));++router.post('/google/auto-configure/navigate', asyncHandler(async (req, res) => {+ const { step } = req.body;+ if (!step) throw new ServerError('Step is required', { status: 400, code: 'VALIDATION_ERROR' });+ const io = req.app.get('io');+ const result = await googleOAuthAutoConfig.navigateToStep(step, io);+ if (result.error) return res.status(result.status || 500).json({ error: result.error });+ res.json(result);+}));++router.post('/google/auto-configure/capture', asyncHandler(async (req, res) => {+ const io = req.app.get('io');+ const result = await googleOAuthAutoConfig.captureCredentials(io);+ if (result.error) return res.status(result.status || 500).json({ error: result.error });+ res.json(result);+}));+// === Google API Sync Routes ===router.post('/sync/:accountId/api', asyncHandler(async (req, res) => {if (!z.string().uuid().safeParse(req.params.accountId).success) {diff --git a/server/services/googleOAuthAutoConfig.js b/server/services/googleOAuthAutoConfig.jsnew file mode 100644index 0000000000..a02b3caa86--- /dev/null+++ b/server/services/googleOAuthAutoConfig.js@@ -0,0 +1,139 @@+/**+ * Google OAuth Auto-Configure via CDP Browser+ * Opens Google Cloud Console in the managed browser and guides/captures OAuth credentials.+ */+import { findOrOpenPage, evaluateOnPage, getPages } from './messagePlaywrightSync.js';+import { saveCredentials, getAuthUrl } from './googleAuth.js';++const GCP_CONSOLE_URL = 'https://console.cloud.google.com';+const GCP_CREDENTIALS_URL = 'https://console.cloud.google.com/apis/credentials';+const GCP_ENABLE_API_URL = 'https://console.cloud.google.com/apis/library/calendar-json.googleapis.com';++export async function startAutoConfig(io) {+ console.log('📅 Starting Google OAuth auto-configuration via CDP browser');+ io?.emit('calendar:google:autoconfig', { step: 'launching', message: 'Opening Google Cloud Console...' });++ // Open Google Cloud Console+ const page = await findOrOpenPage(GCP_CONSOLE_URL);+ if (!page) {+ return { error: 'Failed to open browser. Ensure portos-browser is running.', status: 503 };+ }++ io?.emit('calendar:google:autoconfig', { step: 'opened', message: 'Google Cloud Console opened. Please log in if needed.' });+ console.log('📅 Google Cloud Console opened in CDP browser');++ return {+ status: 'started',+ message: 'Google Cloud Console opened. Follow the steps in the UI to create OAuth credentials.',+ pageId: page.id+ };+}++export async function navigateToStep(step, io) {+ const urls = {+ 'enable-api': GCP_ENABLE_API_URL,+ 'credentials': GCP_CREDENTIALS_URL,+ 'create-client': `${GCP_CREDENTIALS_URL}/oauthclient`+ };++ const url = urls[step];+ if (!url) return { error: `Unknown step: ${step}`, status: 400 };++ io?.emit('calendar:google:autoconfig', { step, message: `Navigating to ${step}...` });+ const page = await findOrOpenPage(url);+ if (!page) return { error: 'Browser not available', status: 503 };++ console.log(`📅 Auto-config navigated to ${step}`);+ return { status: 'navigated', step, pageId: page.id };+}++export async function captureCredentials(io) {+ console.log('📅 Attempting to capture OAuth credentials from browser');+ io?.emit('calendar:google:autoconfig', { step: 'capturing', message: 'Scanning for credentials...' });++ // Find the Google Cloud Console page+ const pages = await getPages();+ const gcpPage = pages.find(p => p.url?.includes('console.cloud.google.com'));+ if (!gcpPage) {+ return { error: 'Google Cloud Console not open in browser', status: 404 };+ }++ // Try to extract credentials from the OAuth client creation dialog+ // Google shows a modal with Client ID and Client Secret after creating+ const credentials = await evaluateOnPage(gcpPage, `+ (function() {+ // Strategy 1: Look for the "OAuth client created" dialog+ // The dialog contains two copyable text fields with client ID and secret+ const allText = document.body.innerText;++ // Look for client ID pattern (ends with .apps.googleusercontent.com)+ const clientIdMatch = allText.match(/([0-9]+-[a-zA-Z0-9_]+\\.apps\\.googleusercontent\\.com)/);++ // Look for client secret pattern (GOCSPX- prefix)+ const secretMatch = allText.match(/(GOCSPX-[a-zA-Z0-9_-]+)/);++ if (clientIdMatch && secretMatch) {+ return { clientId: clientIdMatch[1], clientSecret: secretMatch[1] };+ }++ // Strategy 2: Look in input/textarea fields that might contain the values+ const inputs = document.querySelectorAll('input[readonly], input[type="text"], textarea');+ let clientId = null;+ let clientSecret = null;++ for (const input of inputs) {+ const val = input.value || input.textContent || '';+ if (val.includes('.apps.googleusercontent.com')) clientId = val.trim();+ if (val.startsWith('GOCSPX-')) clientSecret = val.trim();+ }++ if (clientId && clientSecret) {+ return { clientId, clientSecret };+ }++ // Strategy 3: Look in any element with aria-label or data attributes+ const elements = document.querySelectorAll('[aria-label*="client"], [aria-label*="secret"], [data-value]');+ for (const el of elements) {+ const val = el.getAttribute('data-value') || el.textContent || '';+ if (val.includes('.apps.googleusercontent.com')) clientId = val.trim();+ if (val.startsWith('GOCSPX-')) clientSecret = val.trim();+ }++ if (clientId && clientSecret) {+ return { clientId, clientSecret };+ }++ // Return what we found (partial or null)+ return clientId ? { clientId, clientSecret: null, partial: true } : null;+ })()+ `);++ if (!credentials) {+ return {+ error: 'Could not find credentials on the page. Make sure the OAuth client creation dialog is visible.',+ status: 404+ };+ }++ if (credentials.partial || !credentials.clientSecret) {+ return {+ error: 'Found Client ID but not Client Secret. The secret is only shown once after creation. You may need to create a new OAuth client.',+ clientId: credentials.clientId,+ status: 404+ };+ }++ // Save the credentials+ await saveCredentials(credentials);+ io?.emit('calendar:google:autoconfig', { step: 'captured', message: 'Credentials captured and saved!' });+ console.log('📅 OAuth credentials captured from browser and saved');++ // Generate the auth URL for the next step+ const authResult = await getAuthUrl();++ return {+ status: 'captured',+ clientId: credentials.clientId,+ authUrl: authResult.url || null+ };+}