This lesson combines 3 topics: Building an authorization server that supports the device flow, Building the
devcli loginCLI client, Device flow with an existing IdP.
Learning Objectives
- Design all four server-side endpoints for DevCLI's device flow:
/device/code,/device,/device/approve,/token - Build the data model on Redis: store
device_codeas a hash, mapuser_code, TTL equal toexpires_in - Implement the state machine
pending → approved | denied | expired → consumedand guarantee tokens are issued only once - Enforce
intervalandslow_downon the server instead of trusting the client to pace itself - List every error branch with the correct OAuth error code and HTTP status per RFC 6749 §5.2 and RFC 8628 §3.5
- Write a complete
devcli logincommand in TypeScript on Node 22+, using only the built-infetchand one keychain library - Implement a polling loop that respects
interval,slow_down,expires_inand correctly handles every terminal error code - Support Ctrl+C, network timeouts, and the
--no-browserflag (only print the URL, do not open the browser automatically; the flow does not change) - Store tokens in the OS keychain with
@napi-rs/keyring(Linux pinned to Secret Service), falling back to a 0600 file per profile - Write
devcli whoamianddevcli logout(revoke on the server per RFC 7009, then delete locally) - Know how to enable and call the device flow on popular IdPs: Auth0, Okta, Microsoft Entra ID, GitHub, Keycloak
- Spot where IdPs deviate from RFC 8628 (endpoint names, error codes, omitted fields) so the CLI is not hardcoded to one provider
- Understand why AWS CLI v2 switched
aws sso loginto Authorization Code + PKCE by default while keeping--use-device-code - Know that Amazon Cognito user pools do not support the device flow natively and pick an alternative pattern
- Write a "provider adapter" layer in DevCLI to switch IdPs without changing the polling loop
Part 1: Building an authorization server that supports the device flow
1. The big picture on the server side
In Day 1, Part 2 (RFC 8628) we went through the protocol from the client's point of view. Today we stand on the side of ACME Cloud's authorization server https://auth.example.com and build that part ourselves.
| Endpoint | Called by | Purpose |
|---|---|---|
POST /device/code | CLI | Create a device authorization session, return device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval |
GET /device | Browser | Page for entering the user_code (or prefilled from verification_uri_complete) |
POST /device/approve | Browser (signed in) | The user approves or denies |
POST /token | CLI | Polling with grant_type=urn:ietf:params:oauth:grant-type:device_code |
The difference from Authorization Code: there is no redirect_uri, and the two "channels" (CLI and browser) only meet through data in Redis. The entire security of the flow relies on the server keeping the state correct.
2. Data model on Redis
Design decisions:
| Decision | Reason |
|---|---|
Store sha256(device_code) instead of plaintext | device_code is the CLI's bearer secret. If Redis is read by someone else (backup, log, dump), the attacker cannot get a token. Same as how refresh tokens are stored |
user_code stored in plaintext, the uc: key in normalized form (uppercase, no dash) | Users may type bdfh klmn or BDFH-KLMN; every variant must map to the same key. The user has to type it in again; its entropy is low, so it is protected by rate limiting and a short TTL (Day 1, Part 3), not by hashing |
Redis TTL = expires_in | Sessions disappear on their own, no cleanup job needed; the expired state is inferred from "key not found" |
Store created_ip, created_ua | Shown on the consent page so the user can recognize an unfamiliar session (against device code phishing, Day 2, Part 3) |
last_poll_at + interval in the record | The server decides on its own when to return slow_down, without depending on the client |
Common mistake: using user_code as the only primary key. user_code is short, so it can collide between two live sessions; always regenerate when SET NX fails.
3. State machine
uc:{code} is deleted right at the approve or deny step (section 5), not at consume time. From then on the user_code is useless; the CLI keeps polling with the device_code.
| Current state | POST /token returns |
|---|---|
dc:{hash} not found | 400 expired_token (or invalid_grant if you do not want to distinguish "wrong" from "expired") |
pending, polled at the right pace | 400 authorization_pending |
pending, polled earlier than interval | 400 slow_down, increase interval by 5 seconds |
denied | 400 access_denied, delete key |
approved, wins used | 200 with access_token, refresh_token, expires_in |
approved, loses used (duplicate request) | 400 invalid_grant |
Per RFC 8628 §3.5, only authorization_pending and slow_down allow the client to keep polling; on every other code the client must stop.
4. The POST /device/code endpoint
import express from "express";
import { createClient } from "redis";
import { createHash, randomBytes, randomInt } from "node:crypto";
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const app = express();
app.use(express.urlencoded({ extended: false }));
const EXPIRES_IN = 600; // 10 minutes
const INTERVAL = 5; // seconds, RFC 8628 default
const ALPHABET = "BCDFGHJKLMNPQRSTVWXZ"; // base-20, RFC 8628 §6.1
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
function newUserCode(): string {
let s = "";
for (let i = 0; i < 8; i++) s += ALPHABET[randomInt(ALPHABET.length)];
return `${s.slice(0, 4)}-${s.slice(4)}`; // display form XXXX-XXXX
}
// Form used as the Redis key: uppercase, drop every character outside the charset (dashes, spaces)
const normalize = (s: string) =>
[...s.toUpperCase()].filter((c) => ALPHABET.includes(c)).join("");
const CLIENTS: Record<string, { scopes: string[] }> = {
devcli: { scopes: ["openid", "offline_access", "deploy:read", "deploy:write"] },
};
const DEFAULT_SCOPE = "openid offline_access deploy:read";
app.post("/device/code", async (req, res) => {
const clientId = String(req.body.client_id ?? "");
const client = CLIENTS[clientId];
if (!client) return res.status(401).json({ error: "invalid_client" });
// RFC 8628 §3.1: empty parameters are treated as omitted, so `scope=` also gets the default scope
const scope = String(req.body.scope ?? "").trim() || DEFAULT_SCOPE;
if (!scope.split(" ").every((s) => client.scopes.includes(s)))
return res.status(400).json({ error: "invalid_scope" });
const deviceCode = randomBytes(32).toString("base64url");
const dcHash = sha256(deviceCode);
const dcKey = `dc:${dcHash}`;
// Write dc: FIRST, hSet + expire in one MULTI: uc: never points to a session that does not exist yet
await redis.multi()
.hSet(dcKey, {
client_id: clientId, scope, status: "pending",
interval: String(INTERVAL), last_poll_at: "0",
created_ip: req.ip ?? "", created_ua: String(req.get("user-agent") ?? ""),
})
.expire(dcKey, EXPIRES_IN)
.exec();
let userCode = "";
for (let attempt = 0; attempt < 5 && !userCode; attempt++) {
const candidate = newUserCode();
const ok = await redis.set(`uc:${normalize(candidate)}`, dcHash, { EX: EXPIRES_IN, NX: true });
if (ok) userCode = candidate;
}
if (!userCode) {
await redis.del(dcKey);
// §5.2 has no code for transient errors; borrow temporarily_unavailable from RFC 6749 §4.1.2.1
return res.status(503).set("Retry-After", "5").json({ error: "temporarily_unavailable" });
}
await redis.hSet(dcKey, { user_code: userCode });
res.set("Cache-Control", "no-store").json({
device_code: deviceCode,
user_code: userCode,
verification_uri: "https://example.com/device",
verification_uri_complete: `https://example.com/device?user_code=${userCode}`,
expires_in: EXPIRES_IN,
interval: INTERVAL,
});
});
Notes:
- A wrong
client_idreturnsinvalid_client. RFC 6749 §5.2 allows 401 for this error; for a public client that does not send anAuthorizationheader, 400 is also valid. Pick one and write it into the spec. - If
user_codestill collides after 5 attempts: RFC 6749 §5.2 (which RFC 8628 §3.2 reuses for this endpoint) has no error code for a "temporarily overloaded" situation. This lesson borrowstemporarily_unavailablefrom §4.1.2.1 (authorization endpoint) with HTTP 503 andRetry-After; this is a custom convention and must be written into the spec. The client only needs to treat every unknown code as a terminal error. - Rate-limit this endpoint per IP and per
client_idso an attacker cannot "fill up" theuser_codespace. Cache-Control: no-storeon every response containing a secret, same as the token endpoint.
5. The /device page and POST /device/approve
The code entry page is shown only after the user has signed in through normal SSO (the example.com session cookie). Flow:
GET /device?user_code=BDFH-KLMN:normalize()(uppercase, drop characters outside the charset such as dashes and spaces) givesBDFHKLMN, look upuc:BDFHKLMN→dcHash→dc:{dcHash}.- Show the consent page: client name "DevCLI", list of scopes, the IP and User-Agent that initiated it, creation time, and the warning "Only continue if you yourself just ran
devcli login". POST /device/approvewithuser_code,decision=allow|denyand the form's CSRF token.
app.post("/device/approve", requireSession, verifyCsrf, async (req, res) => {
const code = normalize(String(req.body.user_code ?? ""));
const dcHash = await redis.get(`uc:${code}`);
if (!dcHash) return res.status(404).render("device-invalid");
const allow = req.body.decision === "allow";
// Read-check-write in one Lua script so concurrent allow and deny cannot both get through
const changed = await redis.eval(APPROVE_SCRIPT, {
keys: [`dc:${dcHash}`, `uc:${code}`],
arguments: [allow ? "approved" : "denied", allow ? String(req.session.userId) : ""],
});
if (changed === -1) return res.status(404).render("device-invalid"); // session expired/disappeared
if (changed !== 1) return res.status(409).render("device-already-used");
res.render("device-done", { allowed: allow });
});
// KEYS[1] = dc:{hash}, KEYS[2] = uc:{code}; ARGV[1] = new status, ARGV[2] = user_id
const APPROVE_SCRIPT = `
local status = redis.call("HGET", KEYS[1], "status")
if not status then redis.call("DEL", KEYS[2]) return -1 end
if status ~= "pending" then return 0 end
redis.call("HSET", KEYS[1], "status", ARGV[1], "user_id", ARGV[2])
redis.call("DEL", KEYS[2])
return 1
`;
redis.eval(script, { keys, arguments }) is the node-redis v4 API, the same createClient client as in section 4. The Lua script runs atomically in Redis: only the first request that sees pending can change the state and delete uc:, the other request gets 409. If uc: still exists but dc: is gone (its TTL expired a few milliseconds earlier), the script cleans up uc: and returns -1 so the page reports "invalid or expired code" (404), not a misleading "already used".
| Branch | Behavior | HTTP |
|---|---|---|
| Not signed in | Redirect to login, keeping user_code in a return_to parameter checked for same origin | 302 |
| Missing or wrong CSRF token | Reject | 403 |
user_code does not exist or has expired | "Invalid or expired code" page, without saying whether it is wrong or expired | 404 |
| Too many wrong attempts within the time window | Temporary lock per session and IP | 429 |
| Session already approved/denied | "Code already used" page | 409 |
Why delete uc:{code} right on approval? If you keep it, someone who guesses the code during the remaining time can still open the consent page and see the session details. Once deleted, the user_code is useless; the CLI keeps polling with the device_code.
6. The POST /token endpoint with polling
app.post("/token", async (req, res) => {
res.set("Cache-Control", "no-store");
if (req.body.grant_type !== "urn:ietf:params:oauth:grant-type:device_code")
return res.status(400).json({ error: "unsupported_grant_type" });
const clientId = String(req.body.client_id ?? "");
if (!CLIENTS[clientId]) return res.status(401).json({ error: "invalid_client" });
const deviceCode = String(req.body.device_code ?? "");
if (!deviceCode) return res.status(400).json({ error: "invalid_request" });
const dcHash = sha256(deviceCode);
const key = `dc:${dcHash}`;
const rec = await redis.hGetAll(key);
if (!rec.status) return res.status(400).json({ error: "expired_token" });
if (rec.client_id !== clientId) return res.status(400).json({ error: "invalid_grant" });
// The server enforces the polling pace itself
const now = Date.now();
const interval = Number(rec.interval);
if (now - Number(rec.last_poll_at) < interval * 1000) {
await redis.hSet(key, { interval: String(interval + 5), last_poll_at: String(now) });
return res.status(400).json({ error: "slow_down" });
}
await redis.hSet(key, { last_poll_at: String(now) });
if (rec.status === "pending") return res.status(400).json({ error: "authorization_pending" });
if (rec.status === "denied") {
await redis.del(key);
return res.status(400).json({ error: "access_denied" });
}
// approved: only one request gets the tokens
const won = await redis.set(`used:${dcHash}`, "1", { EX: 600, NX: true });
if (!won) return res.status(400).json({ error: "invalid_grant" });
await redis.del(key);
const tokens = await issueTokens({ userId: rec.user_id, clientId, scope: rec.scope });
res.json({ token_type: "Bearer", ...tokens });
});
Three easy-to-miss points:
- Check that
client_idmatches the record. Otherwise, another client holding thedevice_code(leaked log) could exchange it for a token. - Issue tokens once with
SET NX. Two overlapping poll requests (the CLI retrying after a network timeout) can both seeapproved; only the request that wins theusedkey gets the tokens. slow_downincreasesintervalpermanently for that session. RFC 8628 §3.5: the interval must increase by 5 seconds for this and all subsequent requests.
7. Consolidated error branch table (for the spec)
| Endpoint | Condition | error | HTTP |
|---|---|---|---|
/device/code | client_id does not exist | invalid_client | 401 |
/device/code | Scope outside the allowed list | invalid_scope | 400 |
/device/code | Rate limit exceeded per IP or client | No standard OAuth code; return {"error":"rate_limited"} with Retry-After | 429 |
/device/code | user_code collided 5 times in a row | Outside §5.2; convention temporarily_unavailable (borrowed from §4.1.2.1) with Retry-After | 503 |
/token | grant_type other than device_code | unsupported_grant_type | 400 |
/token | Missing device_code | invalid_request | 400 |
/token | Session not found | expired_token | 400 |
/token | client_id does not match the session | invalid_grant | 400 |
/token | Polled earlier than interval | slow_down | 400 |
/token | Not yet approved | authorization_pending | 400 |
/token | Denied | access_denied | 400 |
/token | Tokens already issued | invalid_grant | 400 |
RFC 6749 §5.2: token endpoint errors default to HTTP 400, except that for invalid_client the server may return 401 (mandatory 401 if the client authenticated via the Authorization header). The codes authorization_pending, slow_down, access_denied, expired_token are added by RFC 8628 §3.5.
Do not forget to declare the endpoint in the metadata (RFC 8414): device_authorization_endpoint, and grant_types_supported including urn:ietf:params:oauth:grant-type:device_code.
Part 2: Building the devcli login CLI client
1. Command structure and user experience
Scope of this lesson: the --device branch. devcli login uses loopback + PKCE by default (Day 2, Part 1) and switches to the device branch automatically when it detects headless/SSH; devcli login --device forces the device flow. Today we build the device branch; the loopback branch already exists in Day 2, Part 1.
Target output:
$ devcli login --device
! Open your browser at https://example.com/device
and enter the code: BDFH-KLMN
(code expires in 10 minutes)
Waiting for confirmation... (Ctrl+C to cancel)
✓ Logged in: dev@example.com (profile: default, team: team-platform)
Split the code into four modules: oauth.ts (server calls), poll.ts (the loop), store.ts (token storage), commands.ts (loginDevice, whoami, logout). The devcli login command calls loginDevice() when --device is passed or when headless, otherwise it calls the loopback branch from Day 2, Part 1.
2. Calling the device authorization endpoint
// oauth.ts
export const AUTH = "https://auth.example.com";
export const CLIENT_ID = "devcli"; // public client: no client_secret
export interface DeviceCodeResponse {
device_code: string;
user_code: string;
verification_uri: string;
verification_uri_complete?: string;
expires_in: number;
interval?: number;
}
export async function requestDeviceCode(scope: string, signal: AbortSignal): Promise<DeviceCodeResponse> {
const res = await fetch(`${AUTH}/device/code`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ client_id: CLIENT_ID, scope }),
signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]), // Ctrl+C cancels immediately
});
// Read text first: a failing proxy often returns an HTML 502 page, and res.json() would throw a confusing SyntaxError
const text = await res.text();
let body: any = null;
try { body = JSON.parse(text); } catch { /* not JSON */ }
if (!res.ok || !body) throw new Error(`device/code failed: ${body?.error ?? `HTTP ${res.status}`}`);
return body as DeviceCodeResponse;
}
Two details:
- The body is
application/x-www-form-urlencoded, not JSON. RFC 8628 §3.1 uses the same format as the RFC 6749 token endpoint. intervalis optional; if the server does not return it, the client uses 5 seconds (RFC 8628 §3.5).
3. The polling loop
// poll.ts
import { setTimeout as sleep } from "node:timers/promises";
import { AUTH, CLIENT_ID, type DeviceCodeResponse } from "./oauth.js";
export interface TokenSet {
access_token: string;
refresh_token?: string;
expires_in: number;
token_type: string;
scope?: string;
}
export async function pollForToken(dc: DeviceCodeResponse, signal: AbortSignal): Promise<TokenSet> {
let interval = (dc.interval ?? 5) * 1000;
const deadline = Date.now() + dc.expires_in * 1000;
while (Date.now() < deadline) {
await sleep(interval, undefined, { signal }); // Ctrl+C throws AbortError
let res: Response;
try {
res = await fetch(`${AUTH}/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: dc.device_code,
client_id: CLIENT_ID,
}),
signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]),
});
} catch (e) {
if (signal.aborted) throw e;
interval = Math.min(interval * 2, 60_000); // network error: back off, do not give up
continue;
}
const body = await res.json().catch(() => ({}));
if (res.ok) return body as TokenSet;
switch (body.error) {
case "authorization_pending":
continue;
case "slow_down":
interval += 5_000;
continue;
case "access_denied":
throw new LoginError("The login request was denied in the browser.");
case "expired_token":
throw new LoginError("The code has expired. Run `devcli login` again.");
default:
throw new LoginError(`Login failed: ${body.error ?? `HTTP ${res.status}`}`);
}
}
throw new LoginError("The code has expired. Run `devcli login` again.");
}
export class LoginError extends Error {}
| Scenario | Client behavior | Reason |
|---|---|---|
authorization_pending | Continue with the current interval | RFC 8628 §3.5 |
slow_down | Add 5 seconds to interval for all subsequent requests | RFC 8628 §3.5, MUST |
access_denied, expired_token, other codes | Stop, print a message, non-zero exit code | Only the two codes above allow further polling |
| Timeout or connection error | Back off (exponential backoff), still within deadline | RFC 8628 §3.5 recommends backoff on connection errors |
| Ctrl+C | Cancel the sleep and the in-flight request immediately | Do not leave the process hanging |
Common mistake: resetting interval to its initial value after slow_down. The server will keep returning slow_down, and strict servers may treat it as abuse.
4. Opening the browser and no-browser mode
// commands.ts (excerpt)
import { spawn } from "node:child_process";
function openBrowser(url: string): void {
const [cmd, args]: [string, string[]] =
process.platform === "darwin" ? ["open", [url]]
: process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
: ["xdg-open", [url]];
const child = spawn(cmd, args, { stdio: "ignore", detached: true });
// spawn reports ENOENT via the 'error' event (asynchronous), try/catch cannot catch it
child.on("error", () => console.error("(Could not open the browser, please open the URL above manually.)"));
child.unref();
}
function isHeadless(): boolean {
return Boolean(process.env.SSH_CONNECTION || process.env.CI)
|| (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY);
}
Display rules:
- Print the URL first, then try to open the browser. If opening fails (missing
xdg-open), the user still has the URL on screen. - On Windows use
rundll32 url.dll,FileProtocolHandler, notcmd /c start:cmd.exeis a shell, it treats&in the URL as a command separator, which cuts the URL and runs the rest as a command. - Always print
verification_urianduser_codeto stderr, even when the browser opened. The user needs to compare the code on the consent page (anti-phishing, Day 2, Part 3). - Only open
verification_uri_completeautomatically on a machine with a display. With--no-browseror an SSH session, only print the URL so the user opens it on another device. - If
process.env.CIis set, refuse to run interactiveloginand point to a CI token or OIDC federation (Day 4, Part 1).
5. Storing tokens: keychain first, 0600 file second
keytar used to be the popular choice, but the repository has been archived since 12/2022. Today we use @napi-rs/keyring, a Node binding of the Rust library keyring-rs, with a synchronous Entry.setPassword/getPassword/deletePassword API.
// store.ts
import { Entry } from "@napi-rs/keyring";
import { mkdir, readFile, rename, open, rm } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { homedir } from "node:os";
import { join } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { withFileLock } from "./lock.js"; // cross-process file lock, explained in Day 4, Part 1 (section 3)
const SERVICE = "devcli";
export const DIR = process.platform === "win32"
? join(process.env.APPDATA ?? homedir(), "devcli")
: join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "devcli");
const FILE = join(DIR, "auth.json");
const FILE_LOCK = join(DIR, "auth.json.lock"); // all profiles share one auth.json, so they share one lock
const MAX_STORE_CHARS = 1_200; // Windows Credential Manager limits blobs to ~2560 bytes: keep a safety margin
export interface StoredAuth {
issuer: string;
userId: string;
email: string;
team: string;
scope: string;
refreshToken: string;
accessToken?: string; // may be absent when the store cannot hold it; the next run refreshes
expiresAt: number; // accessToken expiry, epoch ms
}
export type AuthFile = { version: 1; profiles: Record<string, StoredAuth> };
export const ensureDir = () => mkdir(DIR, { recursive: true, mode: 0o700 });
// Linux: pin Secret Service; unpinned, the library silently falls back to kernel keyutils (lost on reboot)
const entry = (profile: string) =>
new Entry(SERVICE, profile, { linux: { store: "secret-service" } });
function forStore(a: StoredAuth): string {
const full = JSON.stringify(a);
if (full.length <= MAX_STORE_CHARS) return full;
const { accessToken: _omit, ...small } = a; // keep only the refresh token + metadata
return JSON.stringify({ ...small, expiresAt: 0 });
}
async function readFileStore(): Promise<AuthFile> {
let raw: string;
try { raw = await readFile(FILE, "utf8"); }
catch (e: any) { if (e.code === "ENOENT") return { version: 1, profiles: {} }; throw e; }
let f: AuthFile;
try { f = JSON.parse(raw); }
catch {
// Do not silently overwrite: keep the corrupted copy for inspection, tell the user, treat as logged out
await rename(FILE, `${FILE}.bak`).catch(() => {});
console.error("Warning: auth.json is corrupted, renamed to auth.json.bak. Run `devcli login` again.");
return { version: 1, profiles: {} };
}
if (f.version > 1) throw new Error("The login file was created by a newer DevCLI version, please upgrade the CLI.");
return f;
}
async function writeFileStore(f: AuthFile): Promise<void> {
await ensureDir();
const tmp = `${FILE}.${randomUUID()}.tmp`;
try {
// Freshly created temp file ("wx") with 0600: the token never sits in a file with broader permissions
const fh = await open(tmp, "wx", 0o600);
try {
await fh.writeFile(JSON.stringify(f, null, 2));
await fh.sync(); // data hits the disk before the rename
} finally {
await fh.close();
}
await renameWithRetry(tmp, FILE);
} catch (e) {
await rm(tmp, { force: true }); // never leave a temp file holding tokens behind (for example ENOSPC midway)
throw e;
}
}
// POSIX: rename within the same directory is atomic. Windows: a target held open (antivirus,
// another process reading it) can make rename fail with a transient EPERM/EBUSY, so retry a few times
async function renameWithRetry(from: string, to: string): Promise<void> {
for (let i = 0; ; i++) {
try { return await rename(from, to); }
catch (e: any) {
if (i >= 4 || !["EPERM", "EBUSY", "EACCES"].includes(e.code)) throw e;
await sleep(50 * (i + 1));
}
}
}
export async function saveAuth(profile: string, a: StoredAuth): Promise<"keychain" | "file"> {
try {
entry(profile).setPassword(forStore(a));
return "keychain";
} catch {
// Read-modify-write under a shared lock: without it two profiles write in parallel and the later write clobbers the earlier
await withFileLock(FILE_LOCK, async () => {
const f = await readFileStore();
f.profiles[profile] = a;
await writeFileStore(f);
});
return "file";
}
}
export async function loadAuth(profile: string): Promise<StoredAuth | null> {
try {
const v = entry(profile).getPassword();
if (v) return JSON.parse(v);
} catch { /* no store: try the file */ }
return (await readFileStore()).profiles[profile] ?? null;
}
export async function clearAuth(profile: string): Promise<void> {
try { entry(profile).deletePassword(); } catch { /* ignore */ }
await withFileLock(FILE_LOCK, async () => {
const f = await readFileStore();
if (profile in f.profiles) {
delete f.profiles[profile]; // delete only this profile, leave the others alone
await writeFileStore(f);
}
});
}
Notes:
- Linux: if not pinned,
@napi-rs/keyringtries Secret Service first and then silently falls back to kernel keyutils. Keyutils lives in kernel memory and is lost after a reboot, so the developer gets "mysteriously logged out". Pinning{ linux: { store: "secret-service" } }makes the constructor throw a clear error when there is no Secret Service (containers, SSH servers), and we fall back to a file with a one-line warning "token stored in ~/.config/devcli/auth.json, permissions 0600". - Windows: Credential Manager limits the blob size to about 2560 bytes. A JWT access token plus a refresh token easily exceeds it, so
forStore()drops the access token when it is too large; the next command refreshes to get a new access token (Day 4, Part 1). - The fallback file has
version: 1and aprofiles{}map, matching the schema in Day 2, Part 2 (section 3);expiresAtis epoch ms.logout --profile workdeletes only theworkprofile. - Atomic writes: write a temp file with 0600 permissions →
fsync→renameoverauth.json; on failure at any step, delete the temp file. Overwriting directly and then runningchmodexposes the token while the old file still has 0644 permissions, and a process killed midway leaves half a JSON.renamewithin the same directory is atomic on POSIX; on Windows it can fail withEPERM/EBUSYwhenauth.jsonis held open by another process, sorenameWithRetryretries a few times. - A shared lock for
auth.json: all profiles live in the same file, sosaveAuth(file branch) andclearAuthwrap their read-modify-write inwithFileLock(auth.json.lock). Without the lock, if two profiles refresh at the same time, the later write clobbers the earlier one; the other profile's freshly rotated refresh token is lost, and next time the CLI sends the old token and triggers reuse detection.withFileLocklives inlock.ts, explained in Day 4, Part 1. - Corrupted file: rename it to
auth.json.bakand tell the user, rather than silently returning{ profiles: {} }. Swallowing the error means the nextsaveAuthoverwrites the file and wipes out every other profile. - Never log the contents of
StoredAuth. When debugging, print only the profile,expiresAt, and the last 4 characters of the token (…a1b2). A JWT prefix is just the header and does not help identify which token it is.
6. Putting it together: loginDevice, whoami, logout
// commands.ts
import { AUTH, CLIENT_ID, requestDeviceCode } from "./oauth.js";
import { pollForToken, LoginError } from "./poll.js";
import { saveAuth, loadAuth, clearAuth } from "./store.js";
const DEFAULT_SCOPE = "openid offline_access deploy:read"; // deploy:write is requested via step-up (Day 4, Part 1)
export async function loginDevice(opts: { profile: string; noBrowser: boolean }) {
if (process.env.CI) {
console.error("Do not use `devcli login` in CI. Set DEVCLI_TOKEN or use OIDC federation.");
process.exit(2);
}
const ac = new AbortController();
const onSigint = () => ac.abort();
process.once("SIGINT", onSigint);
try {
const dc = await requestDeviceCode(DEFAULT_SCOPE, ac.signal);
const url = dc.verification_uri_complete ?? dc.verification_uri;
console.error(`! Open your browser at ${dc.verification_uri}\n and enter the code: ${dc.user_code}`);
if (!opts.noBrowser && !isHeadless()) openBrowser(url); // the URL was already printed on the line above
console.error("\nWaiting for confirmation... (Ctrl+C to cancel)");
const t = await pollForToken(dc, ac.signal);
process.off("SIGINT", onSigint); // polling done: restore default Ctrl+C for the userinfo/saveAuth steps
if (!t.refresh_token) throw new LoginError("The server did not return a refresh token (missing offline_access scope?).");
const me = await userinfo(t.access_token);
const where = await saveAuth(opts.profile, {
issuer: AUTH, userId: me.id, email: me.email, team: me.team, scope: t.scope ?? DEFAULT_SCOPE,
refreshToken: t.refresh_token, accessToken: t.access_token,
expiresAt: Date.now() + t.expires_in * 1000,
});
console.error(`✓ Logged in: ${me.email} (profile: ${opts.profile}, team: ${me.team})`);
if (where === "file") console.error(" Warning: the token is stored in auth.json (permissions 0600), not in the keychain.");
} catch (e) {
if (ac.signal.aborted) { console.error("\nCancelled."); process.exit(130); }
if (e instanceof LoginError) { console.error(e.message); process.exit(1); }
// Network errors, 5xx, store write errors: print a message instead of an unhandled rejection
console.error(`Login failed: ${(e as Error).message}`);
process.exit(1);
}
}
export async function whoami(profile: string) {
const a = await loadAuth(profile);
if (!a) { console.error(`Profile ${profile} is not logged in. Run \`devcli login\`.`); process.exit(1); }
// No refresh in this lesson yet; Day 4, Part 1 replaces the two lines below with getValidAuth(profile)
if (!a.accessToken || a.expiresAt - Date.now() < 60_000) { console.error("Access token expired, a refresh is needed (Day 4, Part 1)."); process.exit(1); }
const me = await userinfo(a.accessToken);
console.log(`${me.email} profile=${profile} team=${a.team} token=…${a.refreshToken.slice(-4)}`);
}
export async function logout(profile: string) {
if (process.env.DEVCLI_TOKEN) console.error("Warning: DEVCLI_TOKEN is set, logout does not affect this token.");
const a = await loadAuth(profile);
if (a?.refreshToken) {
// RFC 7009: revoke the refresh token; servers usually revoke the related access tokens too
try {
const res = await fetch(`${AUTH}/revoke`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ token: a.refreshToken, token_type_hint: "refresh_token", client_id: CLIENT_ID }),
signal: AbortSignal.timeout(5_000),
});
if (!res.ok) console.error(`Warning: the server returned HTTP ${res.status}, the token was not revoked on the server.`);
} catch {
console.error("Warning: could not reach the server, the token was not revoked on the server.");
}
}
await clearAuth(profile); // still delete locally even if revocation failed
console.error(`Logged out of profile ${profile}.`);
}
userinfo() calls GET https://api.example.com/v1/me with the header Authorization: Bearer <token> and returns { id, email, team }. whoami must clearly print the team/scope in use: it is the first command users run when they hit Not authorized (Day 4, Part 2).
Exit codes should be stable so wrapper scripts can rely on them: 0 success, 1 login error, 2 usage error, 130 interrupted by Ctrl+C.
7. Common mistakes when writing the CLI client
| Mistake | Consequence | Correct approach |
|---|---|---|
Polling immediately, without waiting interval the first time | The server returns slow_down from the very first request | Sleep interval before every request |
Printing tokens to stdout with --verbose | Tokens leak into CI logs and terminal history | Mask tokens, print only the last 4 characters (…a1b2) |
| Overwriting the token file directly (default 0644 permissions) | Other users can read it; a kill midway leaves half a JSON | Temp file with mode: 0o600 → fsync → rename |
logout only deletes locally | The refresh token is still usable if it was copied | Call revoke (RFC 7009) with a timeout, warn on failure, then delete locally |
Opening the URL with cmd /c start on Windows | cmd.exe treats & in the URL as a command separator | rundll32 url.dll,FileProtocolHandler <url> |
| Opening the browser automatically in an SSH session | It opens on the remote server, the user never sees it | Detect headless, only print the URL |
Not distinguishing access_denied from expired_token | The user does not know what to do | One message and instruction per code |
Part 3: Device flow with an existing IdP
1. When to use an existing IdP instead of building your own
In Part 1 of this lesson we built an authorization server ourselves to understand the mechanics. In practice, if your company already has an IdP (Auth0, Okta, Entra ID, Keycloak), enable the device flow there:
| Build your own (Part 1) | Use an existing IdP |
|---|---|
| Full control over the consent page and data model | Consent page, MFA, SSO, Conditional Access out of the box |
| You own security, auditing, rate limiting | The IdP handles most of it; you configure policy |
| Fits when your product is the IdP (like a cloud platform) | Fits when the CLI is just one client of the company IdP |
ACME Cloud's decision: DevCLI uses its own IdP (built in Part 1) for external customers, while the internal acme-ops tool for employees uses the enterprise IdP. So DevCLI needs an adapter layer.
2. Quick comparison table
| IdP | Device authorization endpoint | How to enable | Deviations to remember |
|---|---|---|---|
| Auth0 | https://{domain}/oauth/device/code | Application type Native, Grant Types include Device Code, Token Endpoint Auth Method = None, OIDC Conformant | Calling your own API requires sending audience; confidential clients are not supported |
| Okta | https://{okta-domain}/oauth2/default/v1/device/authorize (custom AS) | Native OIDC app, Device Authorization grant; with a custom authorization server you must enable the grant in the policy rule | Native apps only |
| Microsoft Entra ID | https://login.microsoftonline.com/{tenant}/oauth2/v2.0/devicecode | Public client flows | Does not return verification_uri_complete; returns an extra message; error codes authorization_declined, bad_verification_code |
| GitHub (OAuth app, GitHub App) | POST https://github.com/login/device/code | Must enable "Device flow" in the app settings | The token endpoint is https://github.com/login/oauth/access_token; has its own errors device_flow_disabled, incorrect_device_code; codes live 900 seconds |
| Keycloak | /realms/{realm}/protocol/openid-connect/auth/device | Enable OAuth 2.0 Device Authorization Grant on the client | Close to the RFC; the verify page can sit behind your own short URL |
| Amazon Cognito user pool | None | Not supported natively | See section 6 |
The information in the table has been checked against the official docs in the References section. Each IdP's console UI changes over time and menu names may differ, so check the current docs when configuring.
3. Auth0 and Okta
Auth0 requires:
- Application type Native, OIDC Conformant enabled, Token Endpoint Authentication Method set to None.
- The application's Grant Types include Device Code (and Refresh Token if you need refresh).
- When requesting a token to call your own API (
https://api.example.com), the request to/oauth/device/codemust includeaudience. To get a refresh token, add theoffline_accessscope and enable Allow Offline Access on the API.
POST https://{yourDomain}/oauth/device/code
Content-Type: application/x-www-form-urlencoded
client_id=<client_id>&scope=openid%20offline_access%20deploy:write&audience=https%3A%2F%2Fapi.example.com
The Auth0 docs also list limitations: clients created via Dynamic Client Registration are not supported, Rules/Actions cannot read the login page query string in this flow, and account linking is not supported.
Okta:
- Create an OIDC → Native Application app, select the Device Authorization and Refresh Token grants.
- If you use a custom authorization server (for example
default), go to Access Policies, edit the rule and tick Device Authorization; with the org authorization server, skip this step. - Request:
POST https://{yourOktaDomain}/oauth2/default/v1/device/authorize.
Both return responses in RFC 8628 form (device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval), so the polling loop in Part 2 of this lesson is reused as is.
4. Microsoft Entra ID and GitHub: where they deviate from the standard
Entra ID:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/devicecode
client_id=<client_id>&scope=user.read%20openid%20profile
→ { "user_code", "device_code", "verification_uri", "expires_in", "interval", "message" }
- No
verification_uri_complete: the CLI cannot open a link with the code prefilled. Print both the URL and the code, or print themessageas is (it is already localized). - The token request uses the standard
grant_type=urn:ietf:params:oauth:grant-type:device_code, but the error codes differ: a user denial isauthorization_declined(notaccess_denied), a wrong code isbad_verification_code. By default the user has 15 minutes. - Microsoft classifies device code flow as a high-risk flow because it is often abused in phishing, and recommends blocking it with Conditional Access (Authentication flows) wherever possible, allowing it only when truly needed. See Day 2, Part 3.
GitHub (OAuth app or GitHub App):
- You must enable "Device flow" in the app settings; if you forget, the token endpoint returns
device_flow_disabled. - Sample response:
user_codelikeWDJB-MJHT,verification_uriishttps://github.com/login/device,expires_in900,interval5. - Send the header
Accept: application/json, because by default GitHub's token endpoint may return form-encoded data. - It has extra error codes of its own such as
incorrect_client_credentials,incorrect_device_code,device_flow_disabled.slow_downadds 5 seconds to the interval, same as the RFC.
Design lesson: the polling loop should treat every unknown code as a terminal error (RFC 8628 §3.5), and keep a per-provider error code mapping table to show understandable messages.
5. AWS IAM Identity Center and aws sso login
This is a good example of a major CLI changing its default flow:
| AWS CLI v2 version | Default flow of aws sso login / aws configure sso |
|---|---|
| Before 2.22.0 | Device authorization |
| From 2.22.0 | Authorization Code + PKCE, needs a browser on the same machine |
- To use the device flow on newer versions, add
--use-device-code(for example when SSHed into a machine without a browser). --no-browserdisables opening the browser automatically.- With PKCE, the CLI runs a callback server on localhost;
--redirect-portpicks a specific port, by default a free random port is used. This is exactly the loopback redirect from Day 2, Part 1.
Why the change? Loopback + PKCE forces the login session to complete on the very machine running the CLI, so an attacker cannot send the victim a code to enter remotely as in device code phishing. The device flow is kept for headless cases. DevCLI follows suit: loopback by default when a browser is available, device flow when running devcli login --device or when headless is detected (the --use-device-code flag belongs to AWS CLI, DevCLI uses --device).
6. Amazon Cognito: no native device flow
The Cognito docs list three grant types for user pools: authorization code, implicit, and client credentials. There is no device authorization grant. The options:
Option B is exactly the server from Part 1, only replacing the "user is already signed in" step with a Cognito sign-in in the browser. Consider it carefully: you are responsible for the state machine, rate limiting, and anti-phishing, and the tokens issued to the CLI are your service's tokens (or Cognito tokens forwarded by the service, in which case the service holds user tokens, which widens the risk scope).
7. Provider adapter in DevCLI
export interface DeviceProvider {
name: string;
deviceCodeUrl: string;
tokenUrl: string;
extraParams?: Record<string, string>; // for example audience for Auth0
mapError(error: string): "pending" | "slow_down" | "denied" | "expired" | "fatal";
}
export const entra: DeviceProvider = {
name: "entra",
deviceCodeUrl: "https://login.microsoftonline.com/<tenant>/oauth2/v2.0/devicecode",
tokenUrl: "https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token",
mapError: (e) =>
e === "authorization_pending" ? "pending"
: e === "slow_down" ? "slow_down"
: e === "authorization_declined" ? "denied"
: e === "expired_token" ? "expired"
: "fatal",
};
export const github: DeviceProvider = {
name: "github",
deviceCodeUrl: "https://github.com/login/device/code",
tokenUrl: "https://github.com/login/oauth/access_token",
mapError: (e) =>
e === "authorization_pending" ? "pending"
: e === "slow_down" ? "slow_down"
: e === "access_denied" ? "denied"
: e === "expired_token" ? "expired"
: "fatal", // device_flow_disabled, incorrect_device_code, ...
};
The polling loop in Part 2 of this lesson only needs to call provider.mapError(body.error) instead of a switch directly on the string. Requests always send Accept: application/json so GitHub returns JSON.
8. Endpoint discovery and common integration mistakes
Instead of hardcoding URLs, the CLI should read the authorization server metadata. RFC 8628 registers the device_authorization_endpoint field in the RFC 8414 metadata, and many OIDC IdPs publish it in /.well-known/openid-configuration.
async function discover(issuer: string) {
const res = await fetch(new URL("/.well-known/openid-configuration", issuer));
const meta = await res.json();
if (!meta.device_authorization_endpoint) {
throw new Error(`${issuer} does not publish device_authorization_endpoint`);
}
return { deviceCodeUrl: meta.device_authorization_endpoint, tokenUrl: meta.token_endpoint };
}
Note: not every IdP publishes this field (GitHub is not an OIDC provider for users and has its own endpoints). The adapter should prefer discovery, then fall back to manually configured URLs.
| Common mistake | Symptom | Fix |
|---|---|---|
| Forgetting to enable the grant/Device flow on the app | unauthorized_client, device_flow_disabled, or an equivalent error at the very first step | Enable the grant in the IdP console; add this step to the deployment runbook |
| Creating a Web app instead of Native | The IdP rejects the device grant | Auth0 and Okta require the Native application type |
Missing offline_access | Login works but there is no refresh token, users must log in again every hour | Add the scope and enable the setting that allows offline access |
Missing audience (Auth0) | The token cannot call your own API | Send audience set to the API Identifier |
Printing verification_uri_complete when the provider does not return it | An undefined link in the terminal | Fall back to verification_uri + user_code |
| Hardcoding error codes for one provider | Does not recognize a user denial on another provider | Per-provider mapError adapter |
Not sending Accept: application/json | Parse errors with GitHub | Always send this header |
9. End-to-end testing with multiple IdPs
Each adapter needs at least three test scenarios on a test tenant of the corresponding IdP:
| Scenario | Browser action | Expected CLI result |
|---|---|---|
| Approve | Enter the code, click allow | Exit 0, tokens stored, whoami shows the right account |
| Deny | Enter the code, click deny | Exit 1, message "was denied" (whatever error code the provider uses) |
| Abandon | Do nothing | Exit 1 after expires_in, message "code has expired" |
Run this suite every time you upgrade the CLI or when the IdP announces API changes. The test tenant must be separate from the production tenant and must not use real employee accounts.
Review Questions
-
Why should the server store
sha256(device_code)instead of the plaintext, whileuser_codeis stored in plaintext?Show answer
device_codeis a bearer secret: whoever holds it and theclient_idcan exchange it for a token after the user approves. Storing a hash means a Redis dump, backup, or leaked log is not enough to exchange for a token, just like how refresh tokens are stored. Theuser_code, on the other hand, must be typed in again by the user on the/devicepage, and the server needs to look it up directly by its normalized value. Its entropy is low, so it is protected by a short TTL, rate limiting of wrong entries, and deletion right after use, not by hashing. -
Two
POST /tokenrequests from the same CLI arrive almost simultaneously right after the session becomesapproved. Which design guarantees only one token is issued?Show answer
Use a one-time key such as
SET used:{hash} 1 NX EX 600. This command is atomic in Redis, so only one request wins; the other getsinvalid_grant. If you only rely on "read status then delete key", both requests can readapprovedbefore either has deleted it, issuing two token sets for a single approval. -
The server receives a poll request 2 seconds after the previous one while the session's
intervalis 5 seconds. What must the server do, and how must the client react?Show answer
The server returns
400witherror=slow_downand increases the session'sintervalby 5 seconds (to 10). Per RFC 8628 §3.5, the client must increase its wait by 5 seconds for this and all subsequent requests, then keep polling.slow_downis not a terminal error; onlyauthorization_pendingandslow_downallow polling to continue. -
Why does the
/device/approveendpoint need a CSRF token, even though this flow has no redirect back to the client?Show answer
/device/approveis a state-changing action performed by a signed-in user via the session cookie. A malicious page can build a self-submitting form withdecision=allowand an attacker-generateduser_code, making the victim's browser approve the attacker's session without ever seeing the consent page. A CSRF token (or SameSite=Strict on the session cookie for this page) blocks that attack. -
What message should the
/devicepage return when theuser_codeis wrong, and why should it not distinguish "wrong" from "expired"?Show answer
Return one generic message such as "Invalid or expired code", HTTP 404, and count wrong attempts for a temporary lock (429). If you distinguish "expired" from "does not exist", someone guessing codes learns which codes existed, narrowing the guessing space and leaking information about other people's activity.
-
Why must the CLI sleep
intervalbefore the first/tokenrequest, instead of calling right after printing the code?Show answer
RFC 8628 §3.5 requires the client to wait at least
intervalseconds before each token request. The user also cannot approve within the first few hundred milliseconds. Calling immediately only creates a wasted request and may getslow_down, increasing the whole session'sintervalby 5 seconds. -
While polling, a request hits a network timeout. What should the client do, and how does that differ from receiving
expired_token?Show answer
A network timeout is not a response from the server, so the client keeps polling but backs off its wait time (exponential backoff), still within the
expires_indeadline.expired_tokenis an official response that the session is over; the client must stop immediately, inform the user, and suggest runningloginagain. -
Why does the example use
@napi-rs/keyringinstead ofkeytar, and what must happen when the keychain is unavailable?Show answer
The
keytarrepository has been archived since 12/2022 and is no longer maintained.@napi-rs/keyringis a Node binding ofkeyring-rsand still ships new releases. On Linux you must pinstore: "secret-service": otherwise the library silently falls back to kernel keyutils (lost on reboot) instead of reporting an error. When pinned and Secret Service is missing (containers, SSH servers), the constructor throws; the CLI falls back to the file~/.config/devcli/auth.jsonwith 0600 permissions (directory 0700), stored underprofiles{}, and prints a warning so the user knows. -
devcli logoutcalls the revoke endpoint but the server does not respond. Should the CLI keep the local token to retry later?Show answer
No. The user's intent is "this machine is no longer logged in", so the CLI still deletes the local token while printing a warning that it could not revoke on the server. If the token is suspected to be leaked, the user revokes the session from the account management page on the web. Keeping the local token just to retry revocation goes against expectations and prolongs the risk.
-
Why should
devcli loginrefuse to run when theCIvariable is set?
Show answer
The device flow needs a real person to open a browser and approve. In CI nobody does that, so the job hangs until the code expires. Worse, someone could be tricked into approving a code printed in the CI log. CI should use machine tokens or OIDC federation (Day 4, Part 1), and the CLI should fail clearly right away.
- A CLI hardcodes
case "access_denied"to report that the user denied. After switching to Entra ID, what happens when the user clicks deny?
Show answer
Entra ID returns authorization_declined, not access_denied. If the CLI follows RFC 8628 correctly (every code other than authorization_pending/slow_down is terminal), it still stops but shows a generic message. If the CLI wrongly does "unknown code means keep polling", it polls until expiry. The correct approach is an adapter that maps error codes per provider.
- Why did AWS CLI v2, from version 2.22.0, switch
aws sso loginto Authorization Code + PKCE by default?
Show answer
With a loopback redirect, the authorization code is returned to a callback server on the very machine running the CLI, so the login session is bound to that machine. The device flow allows completion on any device, which is exactly the property device code phishing exploits. The device flow is still kept via --use-device-code for environments without a browser.
- Your team uses an Amazon Cognito user pool and wants the CLI to log in while SSHed into a server. Which approach fits?
Show answer
Cognito user pools have no device authorization grant (only authorization code, implicit, client credentials). There are three directions: (1) if a browser can be opened on the local machine, use loopback + PKCE combined with port forwarding; (2) build your own device authorization service like Part 1, where the browser approval step is a Cognito sign-in; (3) switch to an IdP with a native device flow. Option (2) takes effort and you own the security.
- Calling Auth0's
/oauth/device/codesucceeds, but the access token cannot callhttps://api.example.com. What is missing?
Show answer
The audience parameter set to the API Identifier in Auth0 is missing. Without audience, Auth0 only issues a token for fetching user information (userinfo), not for your own API. If you need a refresh token, add the offline_access scope and enable Allow Offline Access on the API.
- Why should the CLI send
Accept: application/jsonwhen calling GitHub's token endpoint?
Show answer
GitHub's token endpoint supports several response formats, chosen by the Accept header. Without this header, the CLI may receive non-JSON data and res.json() will fail. Explicitly sending Accept: application/json lets the polling loop be shared across all providers.
Hands-on Exercises
Exercise 1: Observe slow_down
Run the server from sections 4 and 6 with a local Redis (docker run -p 6379:6379 redis:7). Call POST /device/code with curl, then poll /token every 2 seconds.
Expected output: from the second poll onward you get slow_down; HGET dc:{hash} interval increases to 10, 15, 20.
Exercise 2: Race on token issuance
Write a test for the race condition: after setting status=approved, fire 20 parallel /token requests (Promise.all).
Expected output: exactly 1 response 200 containing tokens. The other 19 responses are 400 with invalid_grant, slow_down, or expired_token (requests that arrived after dc:{hash} was deleted).
Exercise 3: Rate-limit the code entry page
Add rate limiting to the code entry page: at most 5 wrong attempts per 15 minutes per session.
Expected output: the 6th wrong attempt gets 429; recompute the probability of guessing an 8-character base-20 user_code under this limit within expires_in = 600 seconds (using the formula from Day 1, Part 3).
Exercise 4: End-to-end login with the Part 1 server
Run devcli login --device against the Part 1 server. In another window, set status=approved with redis-cli HSET dc:{hash} status approved user_id u_123.
Expected output: the CLI prints "Logged in", the keychain (Keychain Access on macOS) has a devcli entry, and devcli whoami prints the email and team.
Exercise 5: Verify slow_down
Change the server to always return slow_down for the first 3 polls, then return the token. Measure the actual time between requests.
Expected output: gaps of roughly 5, 10, 15, 20 seconds; never dropping back to 5 seconds.
Exercise 6: File fallback in a container
Run devcli login --device in a Linux container without Secret Service (store pinned to secret-service), then also log in with --profile work and run devcli logout --profile work.
Expected output: the CLI prints a fallback warning; ~/.config/devcli/auth.json has permissions -rw-------, the directory drwx------; the file contains profiles.default, and after logout profiles.work is gone while profiles.default is intact.
Exercise 7: GitHub adapter without Device flow enabled
Create a test GitHub OAuth app, do not enable Device flow yet, and run DevCLI's polling loop with the github adapter.
Expected output: the CLI stops immediately with a message translated from device_flow_disabled; after enabling Device flow in the settings, login succeeds.
Exercise 8: Auth0 and Keycloak adapters
Write an auth0 adapter (with extraParams.audience) and a keycloak adapter (endpoint /realms/{realm}/protocol/openid-connect/auth/device).
Expected output: the same pollForToken function works with three providers; unit tests for each adapter's mapError.
Exercise 9: Propose a default flow for DevCLI
Write a 1-page proposal for ACME: should DevCLI default to loopback + PKCE or to the device flow?
Expected output: a comparison table of phishing risk, SSH/container experience, IdP configuration requirements; a reasoned conclusion, referencing the choice AWS CLI v2 made.
References
- RFC 8628 — OAuth 2.0 Device Authorization Grant
- RFC 6749 §5.2 — Error Response
- RFC 8414 — OAuth 2.0 Authorization Server Metadata
- Redis SET command (NX, EX)
- RFC 9700 — OAuth 2.0 Security Best Current Practice
- RFC 8628 §3.4–3.5 — Device Access Token Request/Response
- RFC 7009 — OAuth 2.0 Token Revocation
- @napi-rs/keyring (keyring-node)
- atom/node-keytar (archived)
- AWS CLI
sso login—--no-browser,--use-device-codeoptions - Auth0 — Device Authorization Flow
- Auth0 — Call Your API Using the Device Authorization Flow
- Okta — Configure Device Authorization Grant Flow
- Microsoft Entra — OAuth 2.0 device authorization grant
- Microsoft Entra — Conditional Access: Authentication flows
- GitHub — Authorizing OAuth apps (Device flow)
- GitHub — Generating a user access token for a GitHub App
- Keycloak Server Administration Guide — Device authorization grant
- AWS CLI — Configure IAM Identity Center authentication
- AWS CLI —
aws sso login - Amazon Cognito — OAuth 2.0 grants