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: rewrite Google OAuth auto-config with exact selectors from Playwright walkthrough
Adam Eivyb21d3464a605
diff --git a/client/src/components/calendar/ConfigTab.jsx b/client/src/components/calendar/ConfigTab.jsxindex f6d9f1a517..0d20ed3148 100644--- a/client/src/components/calendar/ConfigTab.jsx+++ b/client/src/components/calendar/ConfigTab.jsx@@ -80,7 +80,10 @@ export default function ConfigTab({ accounts, setAccounts }) {const handleAutoConfigContinue = async () => {setAutoConfigBusy(true);setAutoConfigStep('running');- const result = await api.runGoogleAutoConfig().catch(() => null);+ // Find the google account's email to pass as test user+ const googleAccount = accounts.find(a => a.type === 'google-calendar');+ const email = googleAccount?.email || '';+ const result = await api.runGoogleAutoConfig(email).catch(() => null);setAutoConfigBusy(false);if (!result || result.status === 'error') {setAutoConfigStep('login');diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 21074a3752..c118f885c9 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -1744,7 +1744,7 @@ export const apiDiscoverCalendars = (accountId) => request(`/calendar/sync/${accexport 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 runGoogleAutoConfig = () => request('/calendar/google/auto-configure/run', { method: 'POST' });+export const runGoogleAutoConfig = (email) => request('/calendar/google/auto-configure/run', { method: 'POST', body: JSON.stringify({ email }) });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 23cbcc9c6e..23c039fa31 100644--- a/server/routes/calendar.js+++ b/server/routes/calendar.js@@ -283,7 +283,8 @@ router.post('/google/auto-configure/capture', asyncHandler(async (req, res) => {router.post('/google/auto-configure/run', asyncHandler(async (req, res) => {const io = req.app.get('io');- const result = await googleOAuthAutoConfig.runAutomatedSetup(io);+ const email = req.body?.email || '';+ const result = await googleOAuthAutoConfig.runAutomatedSetup(email, io);if (result.status === 'error') return res.status(500).json(result);res.json(result);}));diff --git a/server/services/googleOAuthAutoConfig.js b/server/services/googleOAuthAutoConfig.jsindex 23abe0f361..0d69946849 100644--- a/server/services/googleOAuthAutoConfig.js+++ b/server/services/googleOAuthAutoConfig.js@@ -5,17 +5,20 @@* 1. User clicks "Setup with Browser" → opens Google Cloud Console* 2. User logs in and selects/creates a project manually* 3. User clicks "Continue" → automated script handles:- * - Enable Google Calendar API- * - Configure OAuth consent screen- * - Create OAuth credentials with redirect URI- * - Extract client ID + secret- * - Save to PortOS+ * a. Enable Google Calendar API+ * b. Configure OAuth consent screen (Google Auth Platform wizard)+ * c. Add user as test user+ * d. Create OAuth Web client with redirect URI+ * e. Extract client ID + secret from "Information and summary" panel+ * f. Save to PortOS+ *+ * Selectors derived from live Playwright MCP walkthrough of Google Cloud Console (2026-03-14).+ * Google Auth Platform uses Angular Material components — selectors target ARIA roles and text.*/import { findOrOpenPage, evaluateOnPage, getPages } from './messagePlaywrightSync.js';-import { saveCredentials, getAuthUrl } from './googleAuth.js';import { navigateToUrl } from './browserService.js';+import { saveCredentials, getAuthUrl } from './googleAuth.js';-const GCP_CONSOLE_URL = 'https://console.cloud.google.com';const REDIRECT_URI = 'http://localhost:5555/api/calendar/google/oauth/callback';function sleep(ms) {@@ -27,7 +30,7 @@ async function getGcpPage() {return pages.find(p => p.url?.includes('console.cloud.google.com'));}-async function waitForPageReady(maxWait = 15000) {+async function waitForPageLoad(maxWait = 15000) {const start = Date.now();while (Date.now() - start < maxWait) {const page = await getGcpPage();@@ -40,32 +43,32 @@ async function waitForPageReady(maxWait = 15000) {return null;}-async function navigateAndWait(url, waitMs = 3000) {+async function navAndWait(url, waitMs = 4000) {await navigateToUrl(url);await sleep(waitMs);- return waitForPageReady();+ return waitForPageLoad();}-async function clickButtonByText(page, textPatterns, maxWait = 10000) {- const patterns = Array.isArray(textPatterns) ? textPatterns : [textPatterns];+/**+ * Click a button/link by matching its text content (case-insensitive).+ * Polls until found or timeout.+ */+async function clickByText(page, texts, maxWait = 10000) {+ const patterns = Array.isArray(texts) ? texts : [texts];const start = Date.now();while (Date.now() - start < maxWait) {const clicked = await evaluateOnPage(page, `(function() {const patterns = ${JSON.stringify(patterns)};- // Check buttons, a tags, and elements with role=button- const candidates = [...document.querySelectorAll('button, a, [role="button"], [role="menuitem"]')];+ const candidates = [...document.querySelectorAll('button, a, [role="button"], [role="menuitem"], [role="option"], [role="radio"]')];for (const pattern of patterns) {const lp = pattern.toLowerCase();const match = candidates.find(el => {const text = (el.textContent || '').trim().toLowerCase();const aria = (el.getAttribute('aria-label') || '').toLowerCase();- return text === lp || text.includes(lp) || aria.includes(lp);+ return (text === lp || text.startsWith(lp) || aria.includes(lp)) && !el.disabled;});- if (match && !match.disabled) {- match.click();- return pattern;- }+ if (match) { match.click(); return pattern; }}return null;})()@@ -76,18 +79,29 @@ async function clickButtonByText(page, textPatterns, maxWait = 10000) {return null;}-async function fillInput(page, selector, value) {+/**+ * Fill a textbox found by its accessible name.+ */+async function fillByName(page, name, value) {return evaluateOnPage(page, `(function() {- const input = document.querySelector('${selector}');- if (!input) return false;- input.focus();- input.value = '';- const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;- nativeInputValueSetter.call(input, '${value}');- input.dispatchEvent(new Event('input', { bubbles: true }));- input.dispatchEvent(new Event('change', { bubbles: true }));- return true;+ const inputs = document.querySelectorAll('input[type="text"], input:not([type]), textarea');+ for (const input of inputs) {+ const label = input.getAttribute('aria-label') || '';+ const placeholder = input.getAttribute('placeholder') || '';+ const id = input.id || '';+ const formLabel = input.closest('[class*="form"]')?.querySelector('label')?.textContent || '';+ if ([label, placeholder, formLabel].some(t => t.toLowerCase().includes('${name.toLowerCase()}'))) {+ input.focus();+ const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;+ if (setter) { setter.call(input, '${value}'); }+ else { input.value = '${value}'; }+ input.dispatchEvent(new Event('input', { bubbles: true }));+ input.dispatchEvent(new Event('change', { bubbles: true }));+ return true;+ }+ }+ return false;})()`);}@@ -98,277 +112,398 @@ 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...' });- const page = await findOrOpenPage(GCP_CONSOLE_URL);+ const page = await findOrOpenPage('https://console.cloud.google.com');if (!page) {return { error: 'Failed to open browser. Ensure portos-browser is running.', status: 503 };}io?.emit('calendar:google:autoconfig', { step: 'login', message: 'Google Cloud Console opened. Log in and select a project, then click Continue.' });console.log('📅 Google Cloud Console opened in CDP browser');-- return {- status: 'started',- message: 'Google Cloud Console opened. Log in and select your project, then click Continue.'- };+ return { status: 'started', message: 'Log in and select your project, then click Continue.' };}-export async function runAutomatedSetup(io) {+export async function runAutomatedSetup(userEmail, io) {console.log('📅 Running automated Google OAuth setup via CDP');- const errors = [];-const emit = (step, message) => {io?.emit('calendar:google:autoconfig', { step, message });console.log(`📅 Auto-config: ${message}`);};- // Verify GCP Console is open and user is logged inlet page = await getGcpPage();if (!page) return { error: 'Google Cloud Console not open. Click "Setup with Browser" first.', status: 400 };- // Step 1: Enable Google Calendar API+ // Detect the project from the current URL+ const projectMatch = page.url?.match(/project=([^&]+)/);+ const project = projectMatch ? projectMatch[1] : '';+ const projectParam = project ? `?project=${project}` : '';++ // === Step 1: Enable Google Calendar API ===emit('enable-api', 'Enabling Google Calendar API...');- page = await navigateAndWait('https://console.cloud.google.com/apis/library/calendar-json.googleapis.com', 4000);- if (!page) { errors.push('Failed to load Calendar API page'); }- else {- // Check if already enabled+ page = await navAndWait(`https://console.cloud.google.com/apis/library/calendar-json.googleapis.com${projectParam}`, 5000);+ if (page) {const alreadyEnabled = await evaluateOnPage(page, `- (function() {- const text = document.body.innerText;- return text.includes('API enabled') || text.includes('MANAGE') || text.includes('Manage');- })()+ document.body.innerText.includes('API enabled') || document.body.innerText.includes('MANAGE') || document.body.innerText.includes('Manage')`);-if (!alreadyEnabled) {- const clicked = await clickButtonByText(page, ['Enable', 'ENABLE']);+ // Button text is "Enable" with aria-label "enable this API"+ const clicked = await clickByText(page, ['enable this api', 'Enable']);if (clicked) {emit('enable-api', 'Calendar API enable clicked, waiting...');- await sleep(5000);- } else {- errors.push('Could not find Enable button for Calendar API');+ await sleep(6000);}} else {emit('enable-api', 'Calendar API already enabled');}}- // Step 2: Configure OAuth Consent Screen+ // === Step 2: Configure OAuth consent / Google Auth Platform ===emit('consent', 'Configuring OAuth consent screen...');- page = await navigateAndWait('https://console.cloud.google.com/apis/credentials/consent', 4000);- if (!page) { errors.push('Failed to load consent screen page'); }- else {- // Check if consent screen is already configured- const consentState = await evaluateOnPage(page, `- (function() {- const text = document.body.innerText;- if (text.includes('Edit App') || text.includes('EDIT APP')) return 'configured';- if (text.includes('External') || text.includes('Internal')) return 'needs-setup';- return 'unknown';- })()+ page = await navAndWait(`https://console.cloud.google.com/auth/overview${projectParam}`, 5000);+ if (page) {+ const needsSetup = await evaluateOnPage(page, `+ document.body.innerText.includes('not configured yet') || document.body.innerText.includes('Get started')`);- if (consentState === 'needs-setup') {- // Select External and click Create- await evaluateOnPage(page, `- (function() {- // Find and click External radio- const labels = [...document.querySelectorAll('label, [role="radio"], mat-radio-button')];- const external = labels.find(l => (l.textContent || '').toLowerCase().includes('external'));- if (external) external.click();- })()- `);- await sleep(1000);- await clickButtonByText(page, ['Create', 'CREATE']);- await sleep(3000);- page = await waitForPageReady();+ if (needsSetup) {+ // Click "Get started" link+ await clickByText(page, ['Get started']);+ await sleep(4000);+ page = await waitForPageLoad();if (page) {- // Fill in app name+ // Step 1/4: App Information — fill app name, select email+ emit('consent', 'Filling app information...');+ await fillByName(page, 'app name', 'PortOS');+ await sleep(500);++ // Open the support email combobox and select the first optionawait evaluateOnPage(page, `(function() {- const inputs = document.querySelectorAll('input[type="text"]');- for (const input of inputs) {- const label = input.closest('[class*="form"]')?.querySelector('label')?.textContent || '';- if (label.toLowerCase().includes('app name') || label.toLowerCase().includes('application name')) {- input.focus();- const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;- setter.call(input, 'PortOS');- input.dispatchEvent(new Event('input', { bubbles: true }));- input.dispatchEvent(new Event('change', { bubbles: true }));+ const combo = document.querySelector('[role="combobox"][aria-label*="support"]') ||+ document.querySelector('cfc-select[formcontrolname="userSupportEmail"]');+ if (combo) combo.click();+ })()+ `);+ await sleep(1000);+ // Click the first email option+ await evaluateOnPage(page, `+ (function() {+ const options = document.querySelectorAll('[role="option"]');+ for (const opt of options) {+ if (opt.textContent.includes('@') && !opt.hasAttribute('disabled')) {+ opt.click();return true;}}- // Fallback: fill the first empty text input- const first = [...inputs].find(i => !i.value);- if (first) {- first.focus();- const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;- setter.call(first, 'PortOS');- first.dispatchEvent(new Event('input', { bubbles: true }));- first.dispatchEvent(new Event('change', { bubbles: true }));+ return false;+ })()+ `);+ await sleep(500);++ // Click Next+ await clickByText(page, ['Next']);+ await sleep(2000);++ // Step 2/4: Audience — select External+ emit('consent', 'Setting audience to External...');+ await clickByText(page, ['External']);+ await sleep(500);+ await clickByText(page, ['Next']);+ await sleep(2000);++ // Step 3/4: Contact Information — fill email+ emit('consent', 'Filling contact email...');+ const email = userEmail || 'portos@localhost';+ await evaluateOnPage(page, `+ (function() {+ const inputs = document.querySelectorAll('input[type="text"], input:not([type])');+ const emailInput = [...inputs].find(i => {+ const ph = i.placeholder || '';+ const label = i.closest('[class*="form"]')?.querySelector('label')?.textContent || '';+ return !i.value && (ph.includes('email') || label.toLowerCase().includes('email'));+ }) || [...inputs].find(i => !i.value);+ if (emailInput) {+ emailInput.focus();+ const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;+ if (setter) setter.call(emailInput, '${email}');+ else emailInput.value = '${email}';+ emailInput.dispatchEvent(new Event('input', { bubbles: true }));+ emailInput.dispatchEvent(new Event('change', { bubbles: true }));return true;}return false;})()`);await sleep(500);+ await clickByText(page, ['Next']);+ await sleep(2000);- // Click Save and Continue through each page (up to 4 times)- for (let i = 0; i < 4; i++) {- await sleep(2000);- const saved = await clickButtonByText(page, ['Save and Continue', 'SAVE AND CONTINUE', 'Save and continue'], 5000);- if (!saved) {- // Try just Continue or Back to Dashboard- const alt = await clickButtonByText(page, ['Continue', 'CONTINUE', 'Back to Dashboard', 'BACK TO DASHBOARD'], 3000);- if (!alt) break;- }- await sleep(2000);- page = await waitForPageReady();- if (!page) break;- }+ // Step 4/4: Finish — check agreement, click Continue then Create+ emit('consent', 'Accepting terms...');+ await evaluateOnPage(page, `+ (function() {+ const cb = document.querySelector('[role="checkbox"]') || document.querySelector('input[type="checkbox"]');+ if (cb && !cb.checked) cb.click();+ })()+ `);+ await sleep(500);+ await clickByText(page, ['Continue', 'Create']);+ await sleep(3000);+ await clickByText(page, ['Create']);+ await sleep(3000);++ // Close any notification+ await clickByText(page, ['Close message'], 3000);+ await sleep(1000);}- emit('consent', 'OAuth consent screen configured');- } else if (consentState === 'configured') {- emit('consent', 'OAuth consent screen already configured');} else {- emit('consent', 'Could not determine consent screen state, continuing...');+ emit('consent', 'OAuth consent already configured');}}- // Step 3: Create OAuth Client- emit('credentials', 'Creating OAuth credentials...');- page = await navigateAndWait('https://console.cloud.google.com/apis/credentials', 4000);- if (!page) { errors.push('Failed to load credentials page'); }- else {- // Click "+ Create Credentials" then "OAuth client ID"- const createClicked = await clickButtonByText(page, ['Create credentials', 'CREATE CREDENTIALS', '+ Create Credentials']);- if (createClicked) {+ // === Step 3: Add test user ===+ emit('test-user', 'Adding test user...');+ page = await navAndWait(`https://console.cloud.google.com/auth/audience${projectParam}`, 5000);+ if (page) {+ const hasUser = await evaluateOnPage(page, `+ document.body.innerText.includes('${userEmail || ''}') && !'${userEmail}'.includes('portos')+ `);+ if (!hasUser && userEmail) {+ await clickByText(page, ['Add users']);+ await sleep(2000);+ // Fill email in the dialog+ await evaluateOnPage(page, `+ (function() {+ const dialog = document.querySelector('[role="dialog"]');+ if (!dialog) return false;+ const input = dialog.querySelector('input[type="text"], input:not([type])');+ if (!input) return false;+ input.focus();+ const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;+ if (setter) setter.call(input, '${userEmail}');+ else input.value = '${userEmail}';+ input.dispatchEvent(new Event('input', { bubbles: true }));+ input.dispatchEvent(new Event('change', { bubbles: true }));+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));+ return true;+ })()+ `);+ await sleep(1500);+ await clickByText(page, ['Save']);await sleep(2000);- // Click "OAuth client ID" from dropdown menu- const oauthClicked = await clickButtonByText(page, ['OAuth client ID', 'OAuth Client ID']);- if (oauthClicked) {- await sleep(3000);- page = await waitForPageReady();- }}+ }- if (!page) {- // Fallback: navigate directly to create page- page = await navigateAndWait('https://console.cloud.google.com/apis/credentials/oauthclient', 4000);- }+ // === Step 4: Create OAuth client ===+ emit('credentials', 'Creating OAuth client...');+ page = await navAndWait(`https://console.cloud.google.com/auth/clients/create${projectParam}`, 5000);+ if (page) {+ // Select "Web application" from Application type dropdown+ await evaluateOnPage(page, `+ (function() {+ const combo = document.querySelector('[role="combobox"]');+ if (combo) combo.click();+ })()+ `);+ await sleep(1500);+ await clickByText(page, ['Web application']);+ await sleep(2000);+ // Add redirect URI — click "Add URI" in the redirect URIs section+ await evaluateOnPage(page, `+ (function() {+ // Find the "Add URI" button in the redirect URIs fieldset+ const fieldsets = document.querySelectorAll('fieldset');+ for (const fs of fieldsets) {+ if (fs.textContent.includes('redirect URI')) {+ const btn = fs.querySelector('button');+ if (btn) { btn.click(); return true; }+ }+ }+ // Fallback: click the last "Add URI" button+ const buttons = [...document.querySelectorAll('button')].filter(b => b.textContent.trim() === 'Add URI');+ if (buttons.length > 0) { buttons[buttons.length - 1].click(); return true; }+ return false;+ })()+ `);+ await sleep(1000);++ // Fill the redirect URI (the last empty input)+ await evaluateOnPage(page, `+ (function() {+ const inputs = [...document.querySelectorAll('input[type="text"], input:not([type])')];+ const empty = inputs.reverse().find(i => !i.value && i.placeholder?.includes('example'));+ if (!empty) return false;+ empty.focus();+ const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;+ if (setter) setter.call(empty, '${REDIRECT_URI}');+ else empty.value = '${REDIRECT_URI}';+ empty.dispatchEvent(new Event('input', { bubbles: true }));+ empty.dispatchEvent(new Event('change', { bubbles: true }));+ return true;+ })()+ `);+ await sleep(1000);++ // Click Create+ emit('credentials', 'Submitting OAuth client...');+ await clickByText(page, ['Create']);+ await sleep(5000);+ page = await waitForPageLoad();+ }++ // === Step 5: Extract credentials ===+ emit('capturing', 'Extracting credentials...');+ await sleep(2000);++ // First try: capture from the creation dialog (shows client ID, might have secret)+ let credentials = await extractFromDialog(page);++ if (!credentials?.clientSecret) {+ // Close dialog and navigate to client detail to get secret from "Information and summary"+ await clickByText(page, ['OK', 'Close'], 3000);+ await sleep(2000);++ // Find and click the client in the list+ page = await getGcpPage();if (page) {- // Select "Web application" type- await sleep(2000);+ // Click on the client linkawait evaluateOnPage(page, `(function() {- // Look for application type dropdown/select and choose "Web application"- const selects = document.querySelectorAll('select, [role="listbox"], mat-select');- for (const sel of selects) {- sel.click();+ const links = document.querySelectorAll('a');+ for (const link of links) {+ if (link.href?.includes('/auth/clients/') && link.textContent.includes('Web client')) {+ link.click();+ return true;+ }}- // Also try clicking any dropdown that mentions "Application type"- const dropdowns = [...document.querySelectorAll('[aria-label*="pplication type"], [class*="select"], [class*="dropdown"]')];- for (const d of dropdowns) d.click();+ return false;})()`);- await sleep(1500);- await clickButtonByText(page, ['Web application', 'Web Application']);- await sleep(2000);- page = await waitForPageReady();+ await sleep(3000);+ page = await waitForPageLoad();if (page) {- // Add redirect URI- emit('credentials', 'Adding redirect URI...');-- // Click "Add URI" button in the redirect URIs section- await clickButtonByText(page, ['Add URI', 'ADD URI', '+ Add URI']);- await sleep(1000);+ // Click "Information and summary" button+ await clickByText(page, ['Information and summary']);+ await sleep(2000);- // Fill in the redirect URI- await evaluateOnPage(page, `+ // Extract from the summary panel — secret is in a copy button's aria-label+ credentials = await evaluateOnPage(page, `(function() {- const redirectUri = '${REDIRECT_URI}';- // Find input fields - look for the one near "Authorized redirect URIs"- const inputs = [...document.querySelectorAll('input[type="text"], input[type="url"]')];- // Find empty inputs (the newly added one)- const emptyInput = inputs.reverse().find(i => !i.value);- if (emptyInput) {- emptyInput.focus();- const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;- setter.call(emptyInput, redirectUri);- emptyInput.dispatchEvent(new Event('input', { bubbles: true }));- emptyInput.dispatchEvent(new Event('change', { bubbles: true }));- return true;+ const allText = document.body.innerText;+ const clientIdMatch = allText.match(/([0-9]+-[a-zA-Z0-9_]+\\.apps\\.googleusercontent\\.com)/);++ // Secret is in a button aria-label: "Copy to clipboard: GOCSPX-..."+ const buttons = document.querySelectorAll('button[aria-label*="GOCSPX"]');+ let clientSecret = null;+ for (const btn of buttons) {+ const label = btn.getAttribute('aria-label') || '';+ const secretMatch = label.match(/(GOCSPX-[a-zA-Z0-9_-]+)/);+ if (secretMatch) { clientSecret = secretMatch[1]; break; }}- return false;++ // Also check text content+ if (!clientSecret) {+ const secretTextMatch = allText.match(/(GOCSPX-[a-zA-Z0-9_-]+)/);+ if (secretTextMatch) clientSecret = secretTextMatch[1];+ }++ if (clientIdMatch && clientSecret) {+ return { clientId: clientIdMatch[1], clientSecret };+ }+ return clientIdMatch ? { clientId: clientIdMatch[1], partial: true } : null;})()`);- await sleep(1000);-- // Click Create- emit('credentials', 'Creating OAuth client...');- await clickButtonByText(page, ['Create', 'CREATE']);- await sleep(5000);- page = await waitForPageReady();}}}- // Step 4: Capture credentials from the creation dialog- emit('capturing', 'Capturing OAuth credentials...');- await sleep(2000);- const captureResult = await captureCredentials(io);-- if (captureResult.error) {- errors.push(captureResult.error);+ if (!credentials?.clientId || !credentials?.clientSecret) {+ emit('error', 'Could not capture credentials automatically');return {- status: errors.length > 0 ? 'partial' : 'error',- errors,- message: 'Automated setup completed with issues. You may need to manually complete some steps.'+ status: 'partial',+ error: 'Automation completed but could not extract the client secret. Use "Download JSON" from the Google Cloud Console client page and paste the credentials manually.',+ clientId: credentials?.clientId || null};}- emit('done', 'Google OAuth setup complete!');+ // Save credentials+ await saveCredentials(credentials);+ emit('done', 'Credentials captured and saved!');+ console.log(`📅 OAuth credentials captured: ${credentials.clientId}`);++ const authResult = await getAuthUrl();return {status: 'success',- clientId: captureResult.clientId,- authUrl: captureResult.authUrl,- errors: errors.length > 0 ? errors : undefined+ clientId: credentials.clientId,+ authUrl: authResult.url || null};}+async function extractFromDialog(page) {+ if (!page) return null;+ return evaluateOnPage(page, `+ (function() {+ const dialog = document.querySelector('[role="dialog"]');+ if (!dialog) return null;+ const text = dialog.innerText;+ const clientIdMatch = text.match(/([0-9]+-[a-zA-Z0-9_]+\\.apps\\.googleusercontent\\.com)/);+ const secretMatch = text.match(/(GOCSPX-[a-zA-Z0-9_-]+)/);++ // Also check button aria-labels+ let secret = secretMatch?.[1] || null;+ if (!secret) {+ const btns = dialog.querySelectorAll('button[aria-label*="GOCSPX"]');+ for (const btn of btns) {+ const m = btn.getAttribute('aria-label')?.match(/(GOCSPX-[a-zA-Z0-9_-]+)/);+ if (m) { secret = m[1]; break; }+ }+ }++ if (clientIdMatch) return { clientId: clientIdMatch[1], clientSecret: secret };+ return null;+ })()+ `);+}+export async function captureCredentials(io) {const page = await getGcpPage();if (!page) return { error: 'Google Cloud Console not open in browser', status: 404 };io?.emit('calendar:google:autoconfig', { step: 'capturing', message: 'Scanning for credentials...' });+ // Try dialog first, then page text, then summary panel button labelsconst credentials = await evaluateOnPage(page, `(function() {const allText = document.body.innerText;const clientIdMatch = allText.match(/([0-9]+-[a-zA-Z0-9_]+\\.apps\\.googleusercontent\\.com)/);- const secretMatch = allText.match(/(GOCSPX-[a-zA-Z0-9_-]+)/);- if (clientIdMatch && secretMatch) return { clientId: clientIdMatch[1], clientSecret: secretMatch[1] };- const inputs = document.querySelectorAll('input[readonly], input[type="text"], textarea');- let clientId = null, 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();+ // Check button aria-labels for secret (Google hides it there)+ const buttons = document.querySelectorAll('button[aria-label*="GOCSPX"]');+ let clientSecret = null;+ for (const btn of buttons) {+ const label = btn.getAttribute('aria-label') || '';+ const m = label.match(/(GOCSPX-[a-zA-Z0-9_-]+)/);+ if (m) { clientSecret = m[1]; break; }}- if (clientId && clientSecret) return { clientId, clientSecret };- return clientId ? { clientId, clientSecret: null, partial: true } : null;+ if (!clientSecret) {+ const secretMatch = allText.match(/(GOCSPX-[a-zA-Z0-9_-]+)/);+ if (secretMatch) clientSecret = secretMatch[1];+ }++ if (clientIdMatch && clientSecret) return { clientId: clientIdMatch[1], clientSecret };+ if (clientIdMatch) return { clientId: clientIdMatch[1], partial: true };+ return null;})()`);- if (!credentials) {- return { error: 'Could not find credentials on the page. The OAuth creation dialog may not be visible.', status: 404 };+ if (!credentials?.clientId) {+ return { error: 'Could not find credentials on the page.', status: 404 };}-if (!credentials.clientSecret) {- return { error: 'Found Client ID but not secret. You may need to create a new OAuth client.', clientId: credentials.clientId, status: 404 };+ return { error: 'Found Client ID but not secret. Click "Information and summary" on the client detail page first.', clientId: credentials.clientId, status: 404 };}await saveCredentials(credentials);