// auth-cli-callback.mjs, 25.01.11 // OAuth callback endpoint for CLI authentication // Receives authorization code and returns tokens via simple HTML page import { respond } from "../../backend/http.mjs"; export async function handler(event, context) { const params = new URLSearchParams(event.rawQuery || ""); const code = params.get("code"); const state = params.get("state"); const error = params.get("error"); const errorDescription = params.get("error_description"); // Handle OAuth errors if (error) { return respond(400, null, ` Auth Failed - Aesthetic Computer

❌ Authentication Failed

Error: ${error}

Description: ${errorDescription || "Unknown error"}


You can close this window and try again in your terminal.

`, { "content-type": "text/html" }); } // Validate required parameters if (!code || !state) { return respond(400, null, ` Invalid Request - Aesthetic Computer

⚠️ Invalid Request

Missing required parameters (code or state).

This endpoint should only be accessed via OAuth redirect.

`, { "content-type": "text/html" }); } // Exchange code for tokens const AUTH0_DOMAIN = process.env.AUTH0_DOMAIN; const AUTH0_CLIENT_ID = process.env.AUTH0_CLIENT_ID; const AUTH0_CLIENT_SECRET = process.env.AUTH0_CLIENT_SECRET; const REDIRECT_URI = `https://aesthetic.computer/api/auth/cli-callback`; try { const tokenResponse = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ grant_type: "authorization_code", client_id: AUTH0_CLIENT_ID, client_secret: AUTH0_CLIENT_SECRET, code: code, redirect_uri: REDIRECT_URI, }), }); if (!tokenResponse.ok) { const errorData = await tokenResponse.text(); console.error("Token exchange failed:", errorData); return respond(500, null, ` Token Exchange Failed - Aesthetic Computer

❌ Token Exchange Failed

Failed to exchange authorization code for tokens.

Please try again or check the server logs.

`, { "content-type": "text/html" }); } const tokens = await tokenResponse.json(); // Get user info const userResponse = await fetch(`https://${AUTH0_DOMAIN}/userinfo`, { headers: { Authorization: `Bearer ${tokens.access_token}` }, }); const user = userResponse.ok ? await userResponse.json() : {}; // Return HTML page with tokens embedded (CLI will parse this) return respond(200, null, ` Authentication Success - Aesthetic Computer

✅ Authentication Successful

Welcome! ${user.email || user.name || "User"}

You are now logged in to Aesthetic Computer.


You can now close this window and return to your terminal.

Your CLI tool has received the authentication tokens.

${JSON.stringify({ tokens, user, state }, null, 2)}
`, { "content-type": "text/html" }); } catch (err) { console.error("Callback error:", err); return respond(500, null, ` Server Error - Aesthetic Computer

❌ Server Error

An unexpected error occurred during authentication.

Please try again or contact support.

`, { "content-type": "text/html" }); } }