import { mkdir } from 'node:fs/promises'; import { dirname, join } from 'node:path'; import { homedir } from 'node:os'; import { createRouter } from '../../create-router'; import { DATA_PATH } from '@@/data-path'; import { CustomError } from '../../custom-errors'; const configDir = `${homedir()}/.config/officer.dev`; const googleConfigPath = join(configDir, 'google-oauth.json'); const GOOGLE_SCOPES = [ 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/calendar.readonly', 'https://www.googleapis.com/auth/userinfo.email', ]; const ensureDir = (filePath: string) => mkdir(dirname(filePath), { recursive: true }); export const readGoogleConfig = async () => { try { return await Bun.file(googleConfigPath).json(); } catch { return null; } }; const getUserGoogleFile = (email: string) => join(DATA_PATH, email, 'integrations', 'google.json'); const readUserGoogle = async (email: string) => { try { return await Bun.file(getUserGoogleFile(email)).json(); } catch { return null; } }; const writeUserGoogle = async (email: string, data: Record) => { const filePath = getUserGoogleFile(email); await ensureDir(filePath); await Bun.write(filePath, JSON.stringify(data, null, 2)); }; export const integrationsRouter = createRouter(); integrationsRouter.get('/', async (ctx) => { return ctx.json([]); }); // --- Enterprise: Google OAuth config (Super Admin only) --- integrationsRouter.get('/google/config', async (ctx) => { const user = ctx.get('user'); if (user.role !== 'Super Admin') throw new CustomError('Forbidden', 403); return ctx.json(await readGoogleConfig()); }); integrationsRouter.put('/google/config', async (ctx) => { const user = ctx.get('user'); if (user.role !== 'Super Admin') throw new CustomError('Forbidden', 403); const body = ctx.get('body') as { clientId?: string; clientSecret?: string }; const config = { clientId: body.clientId ?? '', clientSecret: body.clientSecret ?? '' }; await ensureDir(googleConfigPath); await Bun.write(googleConfigPath, JSON.stringify(config, null, 2)); return ctx.json(config); }); integrationsRouter.get('/google/verify', async (ctx) => { const user = ctx.get('user'); if (user.role !== 'Super Admin') throw new CustomError('Forbidden', 403); const config = await readGoogleConfig(); if (!config?.clientId || !config?.clientSecret) { return ctx.json({ valid: false, error: 'Missing credentials' }); } // Send a dummy token exchange — valid credentials return "invalid_grant", // invalid credentials return "invalid_client" const res = await fetch('https://oauth2.googleapis.com/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: config.clientId, client_secret: config.clientSecret, code: 'invalid_code', redirect_uri: 'https://localhost', grant_type: 'authorization_code', }), }); const body = await res.json(); const valid = body.error === 'invalid_grant' || body.error === 'redirect_uri_mismatch'; return ctx.json({ valid, error: valid ? null : body.error_description ?? body.error }); }); // --- Personal: Google account connection status --- integrationsRouter.get('/google/status', async (ctx) => { const email = ctx.get('user').email; const config = await readGoogleConfig(); const connection = await readUserGoogle(email); return ctx.json({ configured: !!(config?.clientId && config?.clientSecret), connected: !!connection?.accessToken, email: connection?.email ?? null, picture: connection?.picture ?? null, }); }); integrationsRouter.delete('/google/connection', async (ctx) => { const email = ctx.get('user').email; const filePath = getUserGoogleFile(email); const file = Bun.file(filePath); if (await file.exists()) { await Bun.write(filePath, '{}'); } return ctx.json({ ok: true }); }); // --- OAuth flow: authorize (protected — user must be logged in) --- integrationsRouter.get('/google/authorize', async (ctx) => { const config = await readGoogleConfig(); if (!config?.clientId || !config?.clientSecret) { throw new CustomError('Google OAuth not configured', 400); } const email = ctx.get('user').email; const origin = ctx.req.query('origin'); if (!origin) throw new CustomError('Missing origin parameter', 400); const redirectUri = `${origin}/api/integrations/google/callback`; const state = Buffer.from(JSON.stringify({ email, redirectUri })).toString('base64url'); const params = new URLSearchParams({ client_id: config.clientId, redirect_uri: redirectUri, response_type: 'code', scope: GOOGLE_SCOPES.join(' '), access_type: 'offline', prompt: 'consent', state, }); return ctx.redirect(`https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`); }); // --- OAuth callback (public — called by Google, exported for hono.ts) --- export const googleCallbackHandler = async (ctx: any) => { const code = ctx.req.query('code'); const stateParam = ctx.req.query('state'); const error = ctx.req.query('error'); if (error || !code || !stateParam) { return ctx.redirect('/settings/integrations?google=error'); } let email: string; let redirectUri: string; try { const parsed = JSON.parse(Buffer.from(stateParam, 'base64url').toString()); email = parsed.email; redirectUri = parsed.redirectUri; } catch { return ctx.redirect('/settings/integrations?google=error'); } const config = await readGoogleConfig(); if (!config?.clientId || !config?.clientSecret) { return ctx.redirect('/settings/integrations?google=error'); } // Exchange code for tokens const tokenResponse = await fetch('https://oauth2.googleapis.com/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ code, client_id: config.clientId, client_secret: config.clientSecret, redirect_uri: redirectUri, grant_type: 'authorization_code', }), }); if (!tokenResponse.ok) { console.error('Google token exchange failed:', await tokenResponse.text()); return ctx.redirect('/settings/integrations?google=error'); } const tokens = await tokenResponse.json(); // Fetch the user's Google email const userinfoResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', { headers: { Authorization: `Bearer ${tokens.access_token}` }, }); let googleEmail = email; let picture: string | null = null; if (userinfoResponse.ok) { const userinfo = await userinfoResponse.json(); googleEmail = userinfo.email ?? email; picture = userinfo.picture ?? null; } await writeUserGoogle(email, { accessToken: tokens.access_token, refreshToken: tokens.refresh_token, expiresAt: Date.now() + tokens.expires_in * 1000, email: googleEmail, picture, scope: tokens.scope, }); return ctx.redirect('/settings/integrations?google=success'); };