# Node.js CLI for Seamless GitHub OAuth Token Management

## Prompt

````md path="prompt.md"
https://uithub.com/janwilmake/uitx/tree/main/forgithub.oauthproxy?lines=false

make a node.js file cli.js without dependencies that:

- looks in global location .uitx for access_token 
- if available, uses GitHub api to get user info with that 
- if available but 401 returned, removes access_token from global
- if not available, or if 401 returned, opens GitHub https://github.com/login/oauth/authorize?client_id=${env.GITHUB_CLIENT_ID}&redirect_uri=http://127.0.0.1:9001/callback&scope=user:email&state=${randomState} with clientId hardcoded to Ov23liNRLqKVzCdfAhWs
- when opening that, also spawns a temporary http server at 9001 that listens for the GET /callback endpoint
- the GET /callback will confirm the state is correct, call the proxy wit the code and retrieve the access token, after which the temp http server gets closed and the access_token gets stored in the global location.

nb: use regular "fetch" to do the api calls, but use http to spawn the temporary server
````

## Context

````md path="context.md"

https://uithub.com/janwilmake/uitx/tree/main/forgithub.oauthproxy?lines=false (866 tokens) 
```plain
└── forgithub.oauthproxy
    ├── .dev.vars.example
    ├── README.md
    ├── main.ts
    └── wrangler.toml


/forgithub.oauthproxy/.dev.vars.example:
--------------------------------------------------------------------------------
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=


--------------------------------------------------------------------------------
/forgithub.oauthproxy/README.md:
--------------------------------------------------------------------------------
https://www.lmpify.com/httpsuuithubcom-ow5mjz0

Usage:

POST https://oauthproxy.forgithub.com/login/oauth/access_token with body {"code":string}



--------------------------------------------------------------------------------
/forgithub.oauthproxy/main.ts:
--------------------------------------------------------------------------------
export interface Env {
  GITHUB_CLIENT_ID: string;
  GITHUB_CLIENT_SECRET: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Enable CORS for pre-flight requests
    if (request.method === "OPTIONS") {
      return handleCORS();
    }

    // Only handle POST requests to /login/oauth/access_token endpoint
    const url = new URL(request.url);
    if (
      request.method === "POST" &&
      url.pathname === "/login/oauth/access_token"
    ) {
      return handleTokenExchange(request, env);
    }

    // Return 404 for any other routes
    return new Response("Not Found", { status: 404 });
  },
};

async function handleTokenExchange(
  request: Request,
  env: Env,
): Promise<Response> {
  try {
    // Parse the request body
    let requestBody: any;
    const contentType = request.headers.get("Content-Type");

    if (contentType?.includes("application/json")) {
      requestBody = await request.json();
    } else if (contentType?.includes("application/x-www-form-urlencoded")) {
      const formData = await request.formData();
      requestBody = Object.fromEntries(formData.entries());
    } else {
      return new Response("Unsupported content type", { status: 415 });
    }

    // Ensure code is provided
    if (!requestBody.code) {
      return new Response("Missing required parameter: code", {
        status: 400,
        headers: getCORSHeaders(),
      });
    }

    // Create the request body for GitHub
    const githubRequestBody = {
      client_id: env.GITHUB_CLIENT_ID,
      client_secret: env.GITHUB_CLIENT_SECRET,
      code: requestBody.code,
      // Pass through optional parameters if provided
      redirect_uri: requestBody.redirect_uri,
      state: requestBody.state,
    };

    // Exchange code for token with GitHub
    const tokenResponse = await fetch(
      "https://github.com/login/oauth/access_token",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
          "User-Agent": "CloudflareWorker",
        },
        body: JSON.stringify(githubRequestBody),
      },
    );

    // Return GitHub's response
    const githubData = await tokenResponse.json();

    // Create response with appropriate headers
    return new Response(JSON.stringify(githubData), {
      status: tokenResponse.status,
      headers: {
        "Content-Type": "application/json",
        ...getCORSHeaders(),
      },
    });
  } catch (error) {
    console.error("Error in token exchange:", error);
    return new Response("Internal Server Error", {
      status: 500,
      headers: getCORSHeaders(),
    });
  }
}

function handleCORS(): Response {
  return new Response(null, {
    status: 204,
    headers: getCORSHeaders(),
  });
}

function getCORSHeaders(): HeadersInit {
  return {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "POST, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type, Authorization",
    "Access-Control-Max-Age": "86400",
  };
}



--------------------------------------------------------------------------------
/forgithub.oauthproxy/wrangler.toml:
--------------------------------------------------------------------------------
name = "forgithub_oauthproxy"
compatibility_date = "2025-04-21"
dev.port = 3000
main = "main.ts"
routes = [ 
  { pattern = "oauthproxy.forgithub.com", custom_domain = true }
]


--------------------------------------------------------------------------------


```


https://github.com/login/oauth/authorize?client_id= (0 tokens) 
HTML urls are not supported. For github code, use https://uithub.com/owner/repo

http://127.0.0.1:9001/callback&scope=user:email&state= (3 tokens) 
```plain
error code: 1003

```



There were one of more URLs pasted that returned HTML. If these URLs are needed to answer the user request, please instruct the user to use the suggested alternatives.
````

## Result

````md path="result.md"
I'll create a Node.js CLI script that handles GitHub OAuth authentication as you described. Here's the implementation for `cli.js`:

```javascript
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const http = require('http');
const { exec } = require('child_process');
const crypto = require('crypto');

// Hardcoded client ID
const GITHUB_CLIENT_ID = 'Ov23liNRLqKVzCdfAhWs';
const PROXY_URL = 'https://oauthproxy.forgithub.com/login/oauth/access_token';
const PORT = 9001;

// Configuration for token storage
const HOME_DIR = process.env.HOME || process.env.USERPROFILE;
const CONFIG_DIR = path.join(HOME_DIR, '.uitx');
const TOKEN_FILE = path.join(CONFIG_DIR, 'access_token');

// Ensure config directory exists
if (!fs.existsSync(CONFIG_DIR)) {
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
}

// Generate a random state for OAuth security
const generateRandomState = () => {
  return crypto.randomBytes(16).toString('hex');
};

// Open the browser with the GitHub authorization URL
const openBrowser = (url) => {
  const command = process.platform === 'win32' ? 'start' :
                  process.platform === 'darwin' ? 'open' : 'xdg-open';
  
  exec(`${command} "${url}"`, (error) => {
    if (error) {
      console.error('Failed to open browser:', error);
    }
  });
};

// Store the access token
const storeAccessToken = (token) => {
  fs.writeFileSync(TOKEN_FILE, token, 'utf8');
  console.log('Access token stored successfully');
};

// Get the stored access token
const getStoredAccessToken = () => {
  try {
    if (fs.existsSync(TOKEN_FILE)) {
      return fs.readFileSync(TOKEN_FILE, 'utf8').trim();
    }
  } catch (error) {
    console.error('Error reading access token:', error);
  }
  return null;
};

// Remove the stored access token
const removeAccessToken = () => {
  try {
    if (fs.existsSync(TOKEN_FILE)) {
      fs.unlinkSync(TOKEN_FILE);
      console.log('Access token removed');
    }
  } catch (error) {
    console.error('Error removing access token:', error);
  }
};

// Start the OAuth flow
const startOAuthFlow = () => {
  const randomState = generateRandomState();
  
  // Start temporary HTTP server to handle the callback
  const server = http.createServer(async (req, res) => {
    const url = new URL(req.url, `http://localhost:${PORT}`);
    
    if (url.pathname === '/callback') {
      // Parse query parameters
      const code = url.searchParams.get('code');
      const state = url.searchParams.get('state');
      
      // Validate state to prevent CSRF attacks
      if (state !== randomState) {
        res.writeHead(400, { 'Content-Type': 'text/html' });
        res.end('<h1>Invalid state parameter</h1><p>Authentication failed. Please try again.</p>');
        return;
      }
      
      if (code) {
        try {
          // Exchange the code for an access token using the proxy
          const tokenResponse = await fetch(PROXY_URL, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            body: JSON.stringify({ code })
          });
          
          const tokenData = await tokenResponse.json();
          
          if (tokenData.access_token) {
            // Store the access token
            storeAccessToken(tokenData.access_token);
            
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end('<h1>Authentication Successful</h1><p>You can close this window and return to the application.</p>');
            
            // Close the server after successful authentication
            server.close(() => {
              console.log('Authentication server closed');
              // After storing the token, fetch user info
              fetchUserInfo(tokenData.access_token);
            });
          } else {
            res.writeHead(400, { 'Content-Type': 'text/html' });
            res.end('<h1>Authentication Failed</h1><p>Failed to obtain access token. Please try again.</p>');
            server.close();
          }
        } catch (error) {
          console.error('Error exchanging code for token:', error);
          res.writeHead(500, { 'Content-Type': 'text/html' });
          res.end('<h1>Server Error</h1><p>An error occurred during authentication. Please try again.</p>');
          server.close();
        }
      } else {
        res.writeHead(400, { 'Content-Type': 'text/html' });
        res.end('<h1>Missing Code</h1><p>No authorization code received from GitHub. Please try again.</p>');
        server.close();
      }
    } else {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('Not found');
    }
  });
  
  server.listen(PORT, () => {
    console.log(`Authentication server listening on port ${PORT}`);
    
    // Open the browser with the GitHub authorization URL
    const authUrl = `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&redirect_uri=http://127.0.0.1:${PORT}/callback&scope=user:email&state=${randomState}`;
    console.log(`Opening browser to authorize: ${authUrl}`);
    openBrowser(authUrl);
  });
  
  // Handle server errors
  server.on('error', (error) => {
    if (error.code === 'EADDRINUSE') {
      console.error(`Port ${PORT} is already in use. Please close the application using that port and try again.`);
    } else {
      console.error('Server error:', error);
    }
    process.exit(1);
  });
};

// Fetch user information from GitHub API
const fetchUserInfo = async (token) => {
  try {
    const response = await fetch('https://api.github.com/user', {
      headers: {
        'Authorization': `token ${token}`,
        'Accept': 'application/vnd.github.v3+json',
        'User-Agent': 'uitx-cli'
      }
    });
    
    if (response.status === 401) {
      console.error('Invalid access token');
      removeAccessToken();
      startOAuthFlow();
      return;
    }
    
    if (!response.ok) {
      throw new Error(`GitHub API returned ${response.status}: ${response.statusText}`);
    }
    
    const userData = await response.json();
    console.log('User Info:', userData);
    
    // Fetch email if not included in user data
    if (!userData.email) {
      fetchUserEmails(token);
    }
  } catch (error) {
    console.error('Error fetching user information:', error);
  }
};

// Fetch user emails from GitHub API
const fetchUserEmails = async (token) => {
  try {
    const response = await fetch('https://api.github.com/user/emails', {
      headers: {
        'Authorization': `token ${token}`,
        'Accept': 'application/vnd.github.v3+json',
        'User-Agent': 'uitx-cli'
      }
    });
    
    if (!response.ok) {
      throw new Error(`GitHub API returned ${response.status}: ${response.statusText}`);
    }
    
    const emails = await response.json();
    const primaryEmail = emails.find(email => email.primary);
    console.log('Primary Email:', primaryEmail);
  } catch (error) {
    console.error('Error fetching user emails:', error);
  }
};

// Main execution
(async function main() {
  const token = getStoredAccessToken();
  
  if (token) {
    console.log('Found existing access token, validating...');
    await fetchUserInfo(token);
  } else {
    console.log('No access token found, starting OAuth flow...');
    startOAuthFlow();
  }
})();
```

This script does the following:

1. Looks for an access token in `~/.uitx/access_token`
2. If found, it uses the token to fetch user information from the GitHub API
3. If the token is invalid (401 response), it removes the token and starts the OAuth flow
4. If no token is found, it starts the OAuth flow directly
5. The OAuth flow:
   - Generates a random state parameter for security
   - Opens the browser with the GitHub authorization URL (using the hardcoded client ID)
   - Starts a temporary HTTP server on port 9001
   - Listens for the callback from GitHub
   - Validates the state parameter
   - Exchanges the code for an access token using the proxy
   - Stores the token and closes the server
   - Fetches user information with the new token

To use the script, save it as `cli.js` and make it executable with `chmod +x cli.js`. Then run it with `./cli.js`.
````

