diff --git a/system/netlify/functions/auth-cli-callback.mjs b/system/netlify/functions/auth-cli-callback.mjs new file mode 100644 index 0000000000..cf99ebf917 --- /dev/null +++ b/system/netlify/functions/auth-cli-callback.mjs @@ -0,0 +1,194 @@ +// 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" }); + } +} diff --git a/system/netlify/functions/update-tezos-address.mjs b/system/netlify/functions/update-tezos-address.mjs new file mode 100644 index 0000000000..91eca12778 --- /dev/null +++ b/system/netlify/functions/update-tezos-address.mjs @@ -0,0 +1,89 @@ +/** + * update-tezos-address - Update user's Tezos wallet address in profile + * Called when user connects their wallet via the AC interface + */ + +import { connect } from "../../backend/database.mjs"; +import { authorize } from "../../backend/authorization.mjs"; + +export async function handler(event, context) { + if (event.httpMethod !== "POST") { + return { statusCode: 405, body: "Method Not Allowed" }; + } + + try { + // Verify authentication + const authHeader = event.headers.authorization || event.headers.Authorization; + if (!authHeader) { + return { + statusCode: 401, + body: JSON.stringify({ error: "Missing authorization header" }), + }; + } + + const userInfo = await authorize({ authorization: authHeader }); + if (!userInfo || !userInfo.sub) { + return { + statusCode: 401, + body: JSON.stringify({ error: "Invalid token" }), + }; + } + + const userId = userInfo.sub; + + // Parse request body + const { address, network } = JSON.parse(event.body); + if (!address || !network) { + return { + statusCode: 400, + body: JSON.stringify({ error: "Missing address or network" }), + }; + } + + // Validate Tezos address format (tz1, tz2, tz3, or KT1) + if (!address.match(/^(tz1|tz2|tz3|KT1)[1-9A-HJ-NP-Za-km-z]{33}$/)) { + return { + statusCode: 400, + body: JSON.stringify({ error: "Invalid Tezos address format" }), + }; + } + + // Update user record + const { db } = await connect(); + const result = await db.collection("users").updateOne( + { sub: userId }, + { + $set: { + "tezos.address": address, + "tezos.network": network, + "tezos.connectedAt": new Date(), + }, + } + ); + + if (result.matchedCount === 0) { + return { + statusCode: 404, + body: JSON.stringify({ error: "User not found" }), + }; + } + + console.log(`✅ Updated Tezos address for user ${userId}: ${address} (${network})`); + + return { + statusCode: 200, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + success: true, + address, + network, + }), + }; + } catch (err) { + console.error("Error updating Tezos address:", err); + return { + statusCode: 500, + body: JSON.stringify({ error: err.message }), + }; + } +} diff --git a/tezos/DEVICE-CODE-SETUP.md b/tezos/DEVICE-CODE-SETUP.md new file mode 100644 index 0000000000..48f8794f94 --- /dev/null +++ b/tezos/DEVICE-CODE-SETUP.md @@ -0,0 +1,65 @@ +# Device Code Flow Setup for CLI Authentication + +## Current Status + +✅ Implemented Device Code Flow in `ac-login.mjs` +❌ Auth0 client needs configuration update + +## Required Auth0 Configuration + +### Enable Device Code Grant Type + +1. Visit Auth0 Dashboard: https://manage.auth0.com/dashboard/us/aesthetic/applications +2. Find application: `LVdZaMbyXctkGfZDnpzDATB5nR0ZhmMt` +3. Go to **Settings** → **Advanced Settings** → **Grant Types** +4. Check the box for **Device Code** +5. Click **Save Changes** + +## Why Device Code Flow? + +Device Code Flow is perfect for CLI tools because: + +- ✅ **No localhost required** - works in containers, SSH sessions, etc. +- ✅ **No callback URL** - user authenticates on any device +- ✅ **Production-ready** - can ship to any user +- ✅ **Better UX** - shows simple code to enter in browser + +## How It Works + +1. CLI requests a device code from Auth0 +2. Auth0 returns: + - `user_code` (e.g., "ABCD-EFGH") + - `verification_uri` (e.g., "https://auth0.com/activate") + - `device_code` (internal token for polling) +3. CLI displays code and URL to user +4. User visits URL on any device (phone, browser, etc.) +5. User enters the code and logs in +6. CLI polls Auth0 every 5 seconds +7. Once user completes auth, CLI receives tokens +8. Tokens saved to `~/.ac-token` + +## Testing After Configuration + +```bash +# Login +node ac-login.mjs + +# Check status +node ac-login.mjs status + +# View token +node ac-login.mjs token + +# Logout +node ac-login.mjs logout +``` + +## Alternative: Keep Authorization Code Flow + +If you can't enable Device Code Flow, we can use the Authorization Code Flow with the hosted callback endpoint we created: + +- `/api/auth/cli-callback` endpoint exists +- User needs to add `https://aesthetic.computer/api/auth/cli-callback` to Auth0 allowed callbacks +- Requires `AUTH0_CLIENT_SECRET` environment variable in Netlify + +Device Code Flow is cleaner for CLI usage, but both work! diff --git a/tezos/ac-login-device-code.mjs b/tezos/ac-login-device-code.mjs new file mode 100755 index 0000000000..26a2c53e43 --- /dev/null +++ b/tezos/ac-login-device-code.mjs @@ -0,0 +1,237 @@ +#!/usr/bin/env node +/** + * ac-login - CLI authentication for Aesthetic Computer + * + * Uses OAuth 2.0 Device Code Flow (no localhost needed!) + * User visits URL on any device, enters code, CLI gets token + * + * Usage: + * node ac-login.mjs - Login + * node ac-login.mjs status - Check login status + * node ac-login.mjs logout - Clear stored token + * node ac-login.mjs token - Show current token + */ + +import { promises as fs } from 'fs'; +import { fileURLToPath } from 'url'; +import { dirname, join } from 'path'; +import { exec } from 'child_process'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +// Config +const AUTH0_DOMAIN = 'aesthetic.us.auth0.com'; +const AUTH0_CLIENT_ID = 'LVdZaMbyXctkGfZDnpzDATB5nR0ZhmMt'; +const TOKEN_FILE = join(process.env.HOME, '.ac-token'); +const POLL_INTERVAL = 5000; // 5 seconds + +// Open browser (devcontainer-aware) +function openBrowser(url) { + const browserCmd = process.env.BROWSER; + if (browserCmd) { + // In devcontainer with BROWSER env var + exec(`${browserCmd} "${url}"`, (err) => { + if (err) console.error('Failed to open browser:', err.message); + }); + } else { + // Standard environment + const cmd = process.platform === 'darwin' ? 'open' : + process.platform === 'win32' ? 'start' : 'xdg-open'; + exec(`${cmd} "${url}"`, (err) => { + if (err) console.error('Failed to open browser:', err.message); + }); + } +} + +// Sleep helper +const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + +// Main login flow using Device Code Flow +async function login() { + console.log('╔══════════════════════════════════════════════════════════════╗'); + console.log('║ 🔐 Aesthetic Computer CLI Login ║'); + console.log('╚══════════════════════════════════════════════════════════════╝\n'); + + try { + // Step 1: Request device code + console.log('📱 Requesting device code...\n'); + + const deviceResponse = await fetch(`https://${AUTH0_DOMAIN}/oauth/device/code`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + client_id: AUTH0_CLIENT_ID, + scope: 'openid profile email offline_access', + audience: 'https://aesthetic.us.auth0.com/api/v2/', + }), + }); + + if (!deviceResponse.ok) { + const error = await deviceResponse.text(); + throw new Error(`Failed to get device code: ${error}`); + } + + const deviceData = await deviceResponse.json(); + + // Step 2: Display instructions to user + console.log('┌────────────────────────────────────────────────────────────┐'); + console.log('│ Please complete authentication in your browser: │'); + console.log('├────────────────────────────────────────────────────────────┤'); + console.log(`│ 1. Visit: ${deviceData.verification_uri_complete || deviceData.verification_uri}`.padEnd(61) + '│'); + console.log('│ │'); + console.log(`│ 2. Enter code: \x1b[1m${deviceData.user_code}\x1b[0m`.padEnd(71) + '│'); + console.log('└────────────────────────────────────────────────────────────┘\n'); + + // Auto-open browser if complete URI is provided + if (deviceData.verification_uri_complete) { + console.log('🌐 Opening browser...\n'); + openBrowser(deviceData.verification_uri_complete); + } + + console.log(`⏳ Waiting for authentication (expires in ${Math.floor(deviceData.expires_in / 60)} minutes)...`); + console.log(' Press Ctrl+C to cancel\n'); + + // Step 3: Poll for tokens + const startTime = Date.now(); + const expiresAt = startTime + (deviceData.expires_in * 1000); + const interval = deviceData.interval ? deviceData.interval * 1000 : POLL_INTERVAL; + + let dots = 0; + while (Date.now() < expiresAt) { + const tokenResponse = await fetch(`https://${AUTH0_DOMAIN}/oauth/token`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'urn:ietf:params:oauth:grant-type:device_code', + device_code: deviceData.device_code, + client_id: AUTH0_CLIENT_ID, + }), + }); + + const tokenData = await tokenResponse.json(); + + if (tokenResponse.ok) { + // Success! Got tokens + console.log('\n\n✅ Authentication successful!\n'); + + // Get user info + const userResponse = await fetch(`https://${AUTH0_DOMAIN}/userinfo`, { + headers: { 'Authorization': `Bearer ${tokenData.access_token}` }, + }); + + const user = await userResponse.json(); + + // Save tokens + await fs.writeFile(TOKEN_FILE, JSON.stringify({ + ...tokenData, + user, + expires_at: Date.now() + (tokenData.expires_in * 1000), + }, null, 2)); + + console.log(`👤 User: ${user.email || user.name || user.sub}`); + console.log(`💾 Token stored in: ${TOKEN_FILE}`); + console.log('\nYou can now use authenticated API calls.'); + + return tokenData; + } + + // Handle errors + if (tokenData.error === 'authorization_pending') { + // Still waiting for user to authorize + process.stdout.write('.'); + dots++; + if (dots % 10 === 0) process.stdout.write(` ${Math.floor((Date.now() - startTime) / 1000)}s\n`); + await sleep(interval); + continue; + } + + if (tokenData.error === 'slow_down') { + // We're polling too fast, increase interval + await sleep(interval + 5000); + continue; + } + + if (tokenData.error === 'expired_token') { + throw new Error('Device code expired. Please try again.'); + } + + if (tokenData.error === 'access_denied') { + throw new Error('Access denied. You cancelled the authorization.'); + } + + // Unknown error + throw new Error(`Authentication failed: ${tokenData.error} - ${tokenData.error_description || 'Unknown error'}`); + } + + throw new Error('Authentication timeout. Please try again.'); + + } catch (err) { + console.error('\n❌ Login failed:', err.message); + process.exit(1); + } +} + +// Check if already logged in +async function checkAuth() { + try { + const tokenData = await fs.readFile(TOKEN_FILE, 'utf8'); + const tokens = JSON.parse(tokenData); + + if (tokens.expires_at && Date.now() > tokens.expires_at) { + console.log('⚠️ Token expired'); + return null; + } + + console.log('✅ Logged in'); + console.log(`👤 User: ${tokens.user?.email || tokens.user?.name || tokens.user?.sub || 'Unknown'}`); + console.log(`🕐 Token expires: ${new Date(tokens.expires_at).toLocaleString()}`); + + return tokens; + } catch (err) { + return null; + } +} + +// Main +(async () => { + const command = process.argv[2]; + + if (command === 'logout') { + try { + await fs.unlink(TOKEN_FILE); + console.log('✅ Logged out successfully'); + } catch (err) { + console.log('Already logged out'); + } + return; + } + + if (command === 'status') { + const tokens = await checkAuth(); + if (!tokens) { + console.log('❌ Not logged in'); + console.log('Run: node ac-login.mjs'); + process.exit(1); + } + return; + } + + if (command === 'token') { + try { + const tokenData = await fs.readFile(TOKEN_FILE, 'utf8'); + const tokens = JSON.parse(tokenData); + console.log('Access Token:', tokens.access_token); + console.log('\nFull token data:'); + console.log(JSON.stringify(tokens, null, 2)); + } catch (err) { + console.log('❌ Not logged in'); + console.log('Run: node ac-login.mjs'); + process.exit(1); + } + return; + } + + // Default: login + await login(); +})();