Skip to content

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

feat(messages): Outlook API sync with token extraction from browser session

Adam Eivy4470a8b6fb1b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f1381da827..49d9337591 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +1,9 @@
# Unreleased Changes
## Added
+- Outlook API sync — extracts bearer token from authenticated browser session via CDP, calls REST API directly instead of Playwright scraping (1.7s vs 5-10min), with automatic Playwright fallback
+- Token extraction for Teams (localStorage MSAL cache) — infrastructure ready for when Teams exposes usable REST APIs
+- Debug endpoints for token status, extraction testing, and cache management (`/api/messages/debug/token-status`, `test-token`, `clear-token`)
- Messages Full Sync now reconciles cache against inbox, pruning messages that were archived/deleted/replied outside PortOS
- MeatSpace Life Calendar tab — "4000 Weeks" mortality-aware time grid with weeks from birth to death, remaining Saturdays/Sundays/sleep/seasons stats, and customizable activity budgets (coffees, showers, workouts, etc.)
- Life Calendar tile on MeatSpace Overview linking to full calendar view
diff --git a/server/routes/messages.js b/server/routes/messages.js
index 2202d5edf1..6b7fca99bc 100644
--- a/server/routes/messages.js
+++ b/server/routes/messages.js
@@ -10,6 +10,7 @@ import { getSelectors, updateSelectors, testSelectors, launchProvider } from '..
import { evaluateMessages, generateReplyBody } from '../services/messageEvaluator.js';
import { executeAction } from '../services/messageActions.js';
import { listRules, deleteRule } from '../services/messageTriageRules.js';
+import { getToken, getTokenStatus, testApi, clearTokenCache } from '../services/messageTokenExtractor.js';
const router = express.Router();
@@ -400,6 +401,40 @@ router.post('/:accountId/:messageId/action', asyncHandler(async (req, res) => {
res.json(result);
}));
+// === Debug: Token Extraction & API Testing ===
+const ALLOWED_TOKEN_PROVIDERS = ['outlook', 'teams'];
+
+router.get('/debug/token-status', asyncHandler(async (req, res) => {
+ const statuses = ALLOWED_TOKEN_PROVIDERS.map(p => getTokenStatus(p));
+ res.json({ providers: statuses });
+}));
+
+router.post('/debug/test-token', asyncHandler(async (req, res) => {
+ const provider = ALLOWED_TOKEN_PROVIDERS.includes(req.body?.provider) ? req.body.provider : 'outlook';
+ const tokenResult = await getToken(provider);
+ if (tokenResult.error) return res.status(503).json(tokenResult);
+
+ const decoded = tokenResult.decoded || {};
+ const tokenInfo = {
+ provider,
+ fresh: tokenResult.fresh,
+ length: tokenResult.token.length,
+ expires: decoded.exp ? new Date(decoded.exp * 1000).toISOString() : 'unknown',
+ audience: decoded.aud || 'unknown',
+ scopes: decoded.scp || decoded.roles || 'unknown'
+ };
+
+ const apiResult = await testApi(provider, tokenResult.token, parseInt(req.query?.top, 10) || 5);
+
+ res.json({ token: tokenInfo, api: apiResult });
+}));
+
+router.post('/debug/clear-token', asyncHandler(async (req, res) => {
+ const provider = ALLOWED_TOKEN_PROVIDERS.includes(req.body?.provider) ? req.body.provider : null;
+ clearTokenCache(provider);
+ res.json({ cleared: true, provider: provider || 'all' });
+}));
+
// === Message Detail Route (last to avoid capturing /launch, /selectors paths) ===
router.get('/:accountId/:messageId', asyncHandler(async (req, res) => {
diff --git a/server/services/messageApiSync.js b/server/services/messageApiSync.js
new file mode 100644
index 0000000000..4e9166222b
--- /dev/null
+++ b/server/services/messageApiSync.js
@@ -0,0 +1,137 @@
+/**
+ * API-based message sync for Outlook and Teams.
+ * Uses bearer tokens extracted from the browser session to call REST APIs directly.
+ * Falls back to Playwright scraping if token extraction fails.
+ */
+
+import { v4 as uuidv4 } from 'uuid';
+import crypto from 'crypto';
+import { getToken } from './messageTokenExtractor.js';
+
+function makeExternalId(prefix, id) {
+ // For API sync, use a stable ID from the API response
+ const hash = crypto.createHash('md5').update(id).digest('hex').slice(0, 12);
+ return `api-${prefix}-${hash}`;
+}
+
+/**
+ * Fetch Outlook inbox messages via the REST API.
+ * @param {object} account - Account config
+ * @param {object} cache - Existing cache
+ * @param {object} io - Socket.IO instance
+ * @param {object} options - { mode: 'unread' | 'full' }
+ * @returns {{ messages, status, syncMethod }} or null if token unavailable
+ */
+export async function syncOutlookApi(account, cache, io, options = {}) {
+ const mode = options.mode || 'unread';
+ const tokenResult = await getToken('outlook');
+
+ if (tokenResult.error) {
+ console.log(`📧 API sync unavailable for ${account.email}: ${tokenResult.message}`);
+ return null; // Signal to fall back to Playwright
+ }
+
+ const token = tokenResult.token;
+ const maxMessages = mode === 'full' ? 200 : 100;
+ console.log(`📧 API sync (${mode}) for ${account.email}`);
+
+ // Build query — unread mode filters to unread only
+ let filter = '';
+ if (mode === 'unread') {
+ filter = '&$filter=IsRead eq false';
+ }
+
+ const select = '$select=Subject,From,ToRecipients,CcRecipients,ReceivedDateTime,IsRead,BodyPreview,Body,Flag,Categories,ConversationId,Importance,IsDeliveryReceiptRequested';
+ const orderBy = '$orderby=ReceivedDateTime desc';
+ const baseUrl = `https://outlook.office.com/api/v2.0/me/mailfolders/inbox/messages?${select}&${orderBy}&$top=${maxMessages}${filter}`;
+
+ const messages = [];
+ let url = baseUrl;
+ let page = 0;
+
+ while (url && messages.length < maxMessages) {
+ page++;
+ io?.emit('messages:sync:progress', { accountId: account.id, current: messages.length, total: maxMessages, page });
+
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 30000);
+
+ const response = await fetch(url, {
+ headers: { Authorization: `Bearer ${token}`, Prefer: 'outlook.body-content-type="Text"' },
+ signal: controller.signal
+ }).finally(() => clearTimeout(timeout));
+
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ console.log(`📧 API sync failed (${response.status}): ${text.slice(0, 200)}`);
+ if (response.status === 401) {
+ // Token expired — clear cache so next sync re-extracts
+ const { clearTokenCache } = await import('./messageTokenExtractor.js');
+ clearTokenCache('outlook');
+ return null; // Fall back to Playwright
+ }
+ return { messages: [], status: 'api-error' };
+ }
+
+ const data = await response.json();
+ const items = data.value || [];
+
+ for (const m of items) {
+ const extId = makeExternalId('ol', m.Id);
+ const msg = {
+ id: uuidv4(),
+ externalId: extId,
+ apiId: m.Id,
+ conversationId: m.ConversationId || null,
+ threadId: m.ConversationId ? `conv-${crypto.createHash('md5').update(m.ConversationId).digest('hex').slice(0, 12)}` : null,
+ from: {
+ name: m.From?.EmailAddress?.Name || '',
+ email: m.From?.EmailAddress?.Address || ''
+ },
+ to: (m.ToRecipients || []).map(r => r.EmailAddress?.Address || r.EmailAddress?.Name || ''),
+ cc: (m.CcRecipients || []).map(r => r.EmailAddress?.Address || r.EmailAddress?.Name || ''),
+ subject: m.Subject || '',
+ bodyText: m.Body?.Content || m.BodyPreview || '',
+ bodyFull: !!(m.Body?.Content),
+ date: m.ReceivedDateTime || new Date().toISOString(),
+ isRead: m.IsRead ?? true,
+ isUnread: !(m.IsRead ?? true),
+ isPinned: false,
+ isFlagged: m.Flag?.FlagStatus === 'Flagged',
+ isReplied: false, // Not directly available in this endpoint
+ hasMeetingInvite: (m.Subject || '').toLowerCase().includes('meeting') || false,
+ importance: m.Importance || 'Normal',
+ categories: m.Categories || [],
+ labels: m.Categories || [],
+ source: 'outlook',
+ syncMethod: 'api',
+ syncedAt: new Date().toISOString()
+ };
+ messages.push(msg);
+ }
+
+ // Follow @odata.nextLink for pagination
+ url = data['@odata.nextLink'] || null;
+ if (messages.length >= maxMessages) break;
+ }
+
+ // Emit messages in real-time
+ if (io && messages.length > 0) {
+ io.emit('messages:sync:message', { accountId: account.id, messages });
+ }
+
+ console.log(`📧 API sync complete: ${messages.length} messages fetched in ${page} page(s)`);
+ return { messages, status: 'success', syncMethod: 'api' };
+}
+
+/**
+ * Teams API sync is not yet available.
+ * Teams v2 is a fully offline-first PWA using service workers and WebSocket (SignalR)
+ * for data. The Graph API token from the browser lacks Chat.Read scope, and the
+ * chatsvcagg token doesn't map to documented REST endpoints.
+ * Teams continues to use Playwright scraping for now.
+ * @returns null (signals fallback to Playwright)
+ */
+export async function syncTeamsApi() {
+ return null;
+}
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index bd40706eaa..0788980fbc 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -126,7 +126,20 @@ export async function syncAccount(accountId, io, options = {}) {
if (account.type === 'gmail') {
const { syncGmail } = await import('./messageGmailSync.js');
providerResult = await syncGmail(account, cache, io);
- } else if (account.type === 'outlook' || account.type === 'teams') {
+ } else if (account.type === 'outlook') {
+ // Try API sync first (fast), fall back to Playwright (slow)
+ const { syncOutlookApi } = await import('./messageApiSync.js');
+ providerResult = await syncOutlookApi(account, cache, io, { mode }).catch(err => {
+ console.log(`📧 API sync error, falling back to Playwright: ${err.message}`);
+ return null;
+ });
+ if (!providerResult) {
+ console.log(`📧 Falling back to Playwright sync for ${account.email}`);
+ const { syncPlaywright } = await import('./messagePlaywrightSync.js');
+ providerResult = await syncPlaywright(account, cache, io, { mode });
+ }
+ } else if (account.type === 'teams') {
+ // Teams v2 uses service workers + WebSocket — no usable REST API yet
const { syncPlaywright } = await import('./messagePlaywrightSync.js');
providerResult = await syncPlaywright(account, cache, io, { mode });
} else {
diff --git a/server/services/messageTokenExtractor.js b/server/services/messageTokenExtractor.js
new file mode 100644
index 0000000000..4878d2af9b
--- /dev/null
+++ b/server/services/messageTokenExtractor.js
@@ -0,0 +1,329 @@
+/**
+ * Token Extractor - extracts bearer tokens from Outlook/Teams browser sessions via CDP
+ *
+ * Strategy per provider:
+ * - Outlook: intercepts network requests (OWA makes frequent API calls with bearer tokens)
+ * - Teams: reads MSAL tokens from localStorage (Teams v2 uses service worker, no visible network)
+ *
+ * Tokens are cached with proactive refresh before expiry.
+ */
+
+import { getPages, evaluateOnPage } from './messagePlaywrightSync.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+
+// Per-provider token cache: { token, decoded, cachedAt }
+const tokenCache = new Map();
+
+// Refresh tokens 5 minutes before actual JWT expiry
+const EXPIRY_BUFFER_MS = 5 * 60 * 1000;
+
+// Provider configs
+const PROVIDERS = {
+ outlook: {
+ tabPattern: 'outlook.office.com',
+ extractMethod: 'network',
+ // OWA sends requests to multiple domains — match broadly
+ networkPatterns: ['outlook.office.com', 'outlook.office365.com', 'substrate.office.com'],
+ triggerScript: `(async function() {
+ const listbox = document.querySelector("[role='listbox']");
+ if (listbox) {
+ const container = listbox.closest('[role="region"]') || listbox.parentElement;
+ if (container) { container.scrollBy(0, 300); await new Promise(r => setTimeout(r, 500)); container.scrollBy(0, -300); }
+ }
+ const inboxLink = document.querySelector('div[title="Inbox"]') || document.querySelector('[data-folderid]');
+ if (inboxLink) { inboxLink.click(); }
+ return true;
+ })()`
+ },
+ teams: {
+ tabPattern: 'teams.microsoft.com',
+ extractMethod: 'localStorage',
+ // MSAL stores tokens keyed by resource; prefer Graph API token for broadest access
+ localStorageResource: 'graph.microsoft.com'
+ }
+};
+
+/**
+ * Connect to a tab's CDP WebSocket and intercept bearer tokens from network requests.
+ * Used for Outlook where OWA makes frequent API calls.
+ */
+async function extractTokenFromNetwork(page, networkPatterns, timeoutMs = 20000) {
+ const wsUrl = page.webSocketDebuggerUrl;
+ if (!wsUrl) return null;
+
+ const { default: WebSocket } = await import('ws');
+
+ return new Promise((resolve) => {
+ const ws = new WebSocket(wsUrl);
+ let msgId = 1;
+ const timer = setTimeout(() => {
+ ws.close();
+ resolve(null);
+ }, timeoutMs);
+
+ ws.on('open', () => {
+ ws.send(JSON.stringify({ id: msgId++, method: 'Network.enable', params: {} }));
+ });
+
+ ws.on('message', (data) => {
+ const msg = safeJSONParse(data.toString(), null, { context: 'cdp-token-ws' });
+ if (!msg) return;
+
+ if (msg.method === 'Network.requestWillBeSent') {
+ const request = msg.params?.request;
+ if (!request) return;
+
+ const url = request.url || '';
+ const authHeader = request.headers?.Authorization || request.headers?.authorization || '';
+
+ if (authHeader.startsWith('Bearer ') && networkPatterns.some(p => url.includes(p))) {
+ const token = authHeader.slice(7);
+ clearTimeout(timer);
+ ws.send(JSON.stringify({ id: msgId++, method: 'Network.disable', params: {} }));
+ setTimeout(() => ws.close(), 200);
+ resolve(token);
+ }
+ }
+ });
+
+ ws.on('error', () => {
+ clearTimeout(timer);
+ ws.close();
+ resolve(null);
+ });
+ });
+}
+
+/**
+ * Trigger network activity on a tab so the web app makes an API call we can intercept.
+ */
+async function triggerPageRequest(page, script) {
+ const wsUrl = page.webSocketDebuggerUrl;
+ if (!wsUrl) return;
+
+ const { default: WebSocket } = await import('ws');
+
+ return new Promise((resolve) => {
+ const ws = new WebSocket(wsUrl);
+ const timer = setTimeout(() => { ws.close(); resolve(); }, 5000);
+
+ ws.on('open', () => {
+ ws.send(JSON.stringify({
+ id: 1,
+ method: 'Runtime.evaluate',
+ params: { expression: script, returnByValue: true, awaitPromise: true }
+ }));
+ });
+
+ ws.on('message', (data) => {
+ const msg = safeJSONParse(data.toString(), null, { context: 'cdp-trigger-ws' });
+ if (msg?.id === 1) {
+ clearTimeout(timer);
+ ws.close();
+ resolve();
+ }
+ });
+
+ ws.on('error', () => { clearTimeout(timer); ws.close(); resolve(); });
+ });
+}
+
+/**
+ * Extract a token from localStorage MSAL cache (Teams v2 stores tokens here).
+ * Finds the best valid token for the given resource.
+ */
+async function extractTokenFromLocalStorage(page, resource) {
+ const script = `(function() {
+ const resource = ${JSON.stringify(resource)};
+ let best = null;
+ let bestExp = 0;
+ for (let i = 0; i < localStorage.length; i++) {
+ const key = localStorage.key(i);
+ if (!key.includes('accesstoken') || !key.includes('login.windows.net')) continue;
+ if (!key.toLowerCase().includes(resource.toLowerCase())) continue;
+ try {
+ const val = JSON.parse(localStorage.getItem(key));
+ if (!val.secret) continue;
+ const exp = parseInt(val.expiresOn || '0');
+ if (exp * 1000 < Date.now()) continue; // skip expired
+ if (exp > bestExp) {
+ bestExp = exp;
+ best = val.secret;
+ }
+ } catch(e) {}
+ }
+ return best;
+ })()`;
+
+ return evaluateOnPage(page, script);
+}
+
+/**
+ * Decode a JWT payload (no signature verification — just need expiry/scopes).
+ */
+function decodeJwt(token) {
+ const parts = token.split('.');
+ if (parts.length !== 3) return null;
+ const payload = Buffer.from(parts[1], 'base64url').toString('utf-8');
+ return safeJSONParse(payload, null, { context: 'jwt-decode' });
+}
+
+/**
+ * Check if a cached token is still valid (not expired, with buffer).
+ */
+function isTokenValid(entry) {
+ if (!entry?.token) return false;
+ const decoded = entry.decoded || decodeJwt(entry.token);
+ const exp = decoded?.exp ? decoded.exp * 1000 : 0;
+ return exp > (Date.now() + EXPIRY_BUFFER_MS);
+}
+
+/**
+ * Get a bearer token for the given provider ('outlook' or 'teams').
+ * Returns { token, decoded, fresh, provider } or { error, message, provider }.
+ */
+export async function getToken(provider) {
+ const config = PROVIDERS[provider];
+ if (!config) return { error: 'unknown-provider', message: `Unknown provider: ${provider}`, provider };
+
+ // Return cached token if still valid
+ const cached = tokenCache.get(provider);
+ if (cached && isTokenValid(cached)) {
+ return { token: cached.token, decoded: cached.decoded, fresh: false, provider };
+ }
+
+ // Find the provider's tab in the browser
+ const pages = await getPages().catch(() => []);
+ const page = pages.find(p => p.url?.includes(config.tabPattern));
+
+ if (!page) {
+ return { error: 'no-tab', message: `No ${provider} tab found in CDP browser. Open ${provider} first.`, provider };
+ }
+ if (!page.webSocketDebuggerUrl) {
+ return { error: 'no-ws', message: `${provider} tab found but no WebSocket debugger URL available.`, provider };
+ }
+
+ console.log(`📧 Extracting ${provider} bearer token via ${config.extractMethod}...`);
+
+ let token = null;
+
+ if (config.extractMethod === 'localStorage') {
+ // Teams v2: read from MSAL localStorage cache
+ token = await extractTokenFromLocalStorage(page, config.localStorageResource);
+ } else {
+ // Outlook: intercept from network requests
+ await triggerPageRequest(page, config.triggerScript);
+ token = await extractTokenFromNetwork(page, config.networkPatterns);
+ }
+
+ if (!token) {
+ return { error: 'no-token', message: `Could not capture ${provider} bearer token.`, provider };
+ }
+
+ const decoded = decodeJwt(token);
+ const exp = decoded?.exp ? new Date(decoded.exp * 1000).toISOString() : 'unknown';
+ console.log(`📧 ${provider} token captured (length: ${token.length}, expires: ${exp})`);
+
+ tokenCache.set(provider, { token, decoded, cachedAt: Date.now() });
+ return { token, decoded, fresh: true, provider };
+}
+
+// Convenience aliases
+export const getOutlookToken = () => getToken('outlook');
+export const getTeamsToken = () => getToken('teams');
+
+/**
+ * Get token info without the raw token value (for status/debug display).
+ */
+export function getTokenStatus(provider) {
+ const cached = tokenCache.get(provider);
+ if (!cached) return { provider, cached: false };
+ const decoded = cached.decoded || {};
+ const exp = decoded.exp ? decoded.exp * 1000 : 0;
+ return {
+ provider,
+ cached: true,
+ valid: isTokenValid(cached),
+ expires: exp ? new Date(exp).toISOString() : 'unknown',
+ expiresIn: exp ? Math.max(0, Math.round((exp - Date.now()) / 1000)) : 0,
+ audience: decoded.aud || 'unknown',
+ cachedAt: new Date(cached.cachedAt).toISOString()
+ };
+}
+
+/**
+ * Test a token against the provider's API.
+ */
+export async function testApi(provider, token, top = 5) {
+ const urls = {
+ outlook: `https://outlook.office.com/api/v2.0/me/mailfolders/inbox/messages?$top=${top}&$select=subject,from,receivedDateTime,isRead,bodyPreview,body,flag,categories,conversationId,importance,toRecipients,ccRecipients`,
+ // Graph token from Teams has Mail.Read — test with /me to verify token works
+ teams: `https://graph.microsoft.com/v1.0/me?$select=displayName,mail,userPrincipalName`
+ };
+
+ const url = urls[provider];
+ if (!url) return { success: false, error: `No API URL for provider: ${provider}` };
+
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15000);
+
+ const response = await fetch(url, {
+ headers: { Authorization: `Bearer ${token}` },
+ signal: controller.signal
+ }).finally(() => clearTimeout(timeout));
+
+ if (!response.ok) {
+ const text = await response.text().catch(() => '');
+ return { success: false, status: response.status, error: text.slice(0, 500) };
+ }
+
+ const data = await response.json();
+
+ if (provider === 'outlook') {
+ return {
+ success: true,
+ count: data.value?.length || 0,
+ messages: (data.value || []).map(m => ({
+ id: m.Id,
+ conversationId: m.ConversationId,
+ subject: m.Subject,
+ from: m.From?.EmailAddress?.Name || '',
+ fromEmail: m.From?.EmailAddress?.Address || '',
+ to: (m.ToRecipients || []).map(r => ({ name: r.EmailAddress?.Name, email: r.EmailAddress?.Address })),
+ cc: (m.CcRecipients || []).map(r => ({ name: r.EmailAddress?.Name, email: r.EmailAddress?.Address })),
+ receivedDateTime: m.ReceivedDateTime,
+ isRead: m.IsRead,
+ bodyPreview: m.BodyPreview || '',
+ bodyType: m.Body?.ContentType || '',
+ bodyContent: m.Body?.Content || '',
+ importance: m.Importance || 'Normal',
+ flag: m.Flag?.FlagStatus || 'NotFlagged',
+ categories: m.Categories || []
+ }))
+ };
+ }
+
+ // Teams Graph API — the token from localStorage may lack Chat.Read scope,
+ // but has Mail.Read and other useful scopes. Return whatever we get.
+ return {
+ success: true,
+ count: data.value?.length || 0,
+ items: (data.value || []).slice(0, 5).map(item => {
+ // Generic shape — works for chats, messages, etc.
+ const keys = Object.keys(item);
+ return { id: item.id, type: item.chatType || item['@odata.type'] || 'unknown', keys };
+ }),
+ note: 'Teams Graph token may lack Chat.Read scope. Token is cached for future use when API access improves.'
+ };
+}
+
+/**
+ * Clear cached token for a provider (or all).
+ */
+export function clearTokenCache(provider) {
+ if (provider) {
+ tokenCache.delete(provider);
+ } else {
+ tokenCache.clear();
+ }
+}