惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
博客园 - 三生石上(FineUI控件)
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
V
Visual Studio Blog
小众软件
小众软件
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
The Cloudflare Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
L
LangChain Blog
Martin Fowler
Martin Fowler
GbyAI
GbyAI
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Building GitHub OAuth device flow in a Node.js CLI
Berat Bozkurt · 2026-06-18 · via DEV Community
Cover image for Building GitHub OAuth device flow in a Node.js CLI

Berat Bozkurt

When building a CLI tool that needs GitHub access, you have three options:

  1. Ask users to create a personal access token manually (bad UX)
  2. Redirect to a web page (requires a server)
  3. Use the OAuth device flow

The device flow is what the GitHub CLI itself uses. Users run one command, a URL and code appear, they open it in any browser. No server, no copy-pasting tokens. Here's how to implement it cleanly.


The flow in three steps

1. POST /login/device/code
   → returns: device_code, user_code, verification_uri, expires_in, interval

2. Show the user:
   "Open https://github.com/login/device/activate and enter: XXXX-YYYY"

3. Poll POST /login/oauth/access_token every {interval} seconds
   → returns: access_token (when user completes) or error codes (keep polling)

The implementation is ~100 lines. Most of the complexity is in handling the polling responses correctly.


Polling response codes

This is the part most tutorials skip. The responses aren't HTTP errors — they come back as 200 OK with an error field:

type PollResponse =
  | { access_token: string; token_type: string }
  | { error: 'authorization_pending' }   // user hasn't authorized yet — keep polling
  | { error: 'slow_down'; interval: number }  // increase interval by 5s
  | { error: 'expired_token' }           // time's up — restart the flow
  | { error: 'access_denied' }           // user denied — stop

Treating all of these as errors breaks the UX. authorization_pending just means "not yet" — keep the spinner going.


The polling loop

async function pollForToken(deviceCode: string, intervalSecs: number): Promise<string> {
  let interval = intervalSecs;

  while (true) {
    await sleep(interval * 1000);

    const response = await fetch('https://github.com/login/oauth/access_token', {
      method: 'POST',
      headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
      body: JSON.stringify({
        client_id: CLIENT_ID,
        device_code: deviceCode,
        grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
      }),
    });

    const data = await response.json();

    if ('access_token' in data) return data.access_token;
    if (data.error === 'slow_down') interval += 5;
    if (data.error === 'expired_token') throw new Error('Authorization timed out. Run auth login again.');
    if (data.error === 'access_denied') throw new Error('Authorization denied.');
    // authorization_pending: continue loop
  }
}


Token storage

Write to ~/.toolname/config.json and immediately chmod:

import { writeFileSync, chmodSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';

const configPath = join(homedir(), '.releasehub', 'config.json');
writeFileSync(configPath, JSON.stringify({ githubToken: token }), 'utf-8');
chmodSync(configPath, 0o600);  // owner read/write only

Most CLIs skip the chmod and leave the token world-readable. Don't.


The full implementation is in ReleaseHub — a CLI for generating release notes from GitHub PRs. The auth module is standalone if you want to adapt it.