devHọc Dev

Week 1 - Day 3: Building the authorization server, the devcli login CLI client, and using an existing IdP

Week 1 – Day 3

This lesson combines 3 topics: Building an authorization server that supports the device flow, Building the devcli login CLI 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_code as a hash, map user_code, TTL equal to expires_in
  • Implement the state machine pending → approved | denied | expired → consumed and guarantee tokens are issued only once
  • Enforce interval and slow_down on 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 login command in TypeScript on Node 22+, using only the built-in fetch and one keychain library
  • Implement a polling loop that respects interval, slow_down, expires_in and correctly handles every terminal error code
  • Support Ctrl+C, network timeouts, and the --no-browser flag (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 whoami and devcli 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 login to 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.

┌──────────────┐(1)POST/device/code┌─────────────────────────┐│devcli│─────────────────────────────────►│auth.example.com││(devmachine)│◄─────────────────────────────────││││device_code,user_code,...│┌───────────────────┐│││││Redis││││(4)POST/token(polling)││dc:{hash}││││─────────────────────────────────►││uc:{code}││││◄─────────────────────────────────│└───────────────────┘│└──────────────┘pending/slow_down/token│││(2)GET/device│┌──────────────┐(2)enteruser_code│(3)POST/device/approve││Browser│─────────────────────────────────►│(SSOsignedin)││(laptop/│◄─────────────────────────────────│││phone)│consentpage└─────────────────────────┘└──────────────┘
EndpointCalled byPurpose
POST /device/codeCLICreate a device authorization session, return device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval
GET /deviceBrowserPage for entering the user_code (or prefilled from verification_uri_complete)
POST /device/approveBrowser (signed in)The user approves or denies
POST /tokenCLIPolling 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

┌─────────────────────────────────────────────────────────┐│dc:{sha256(device_code)}HASHTTL=expires_in││client_iddevcli││scopeopenidoffline_accessdeploy:read││user_codeBDFH-KLMN(displayonly)││statuspending|approved|denied││user_id(filledinwhenapproved)││interval5││last_poll_atepochms││created_ip203.0.113.10││created_uadevcli/2.4.0(darwinarm64)│├─────────────────────────────────────────────────────────┤│uc:{BDFHKLMN}STRINGTTL=expires_in││key=normalizeduser_code(uppercase,nodash)││value=sha256(device_code);deletedonapprove/deny│├─────────────────────────────────────────────────────────┤│used:{sha256(device_code)}STRINGTTL=expires_in││"tokenissued"key,SETNXsoonlyonerequestwins│└─────────────────────────────────────────────────────────┘

Design decisions:

DecisionReason
Store sha256(device_code) instead of plaintextdevice_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_inSessions disappear on their own, no cleanup job needed; the expired state is inferred from "key not found"
Store created_ip, created_uaShown 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 recordThe 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

POST/device/code│▼┌──────────┐userclicks"Deny"┌──────────┐│pending│───────────────────────────►│denied│└────┬─────┘└────┬─────┘│userclicks"Allow"│nextpoll▼▼┌──────────┐access_denied,deletekey│approved│└────┬─────┘│POST/tokenwinsSETNXused:{hash}▼┌──────────┐│consumed│issuetokens,deletedc:{hash}└──────────┘Anystate+TTLexpired─►keydisappears─►expired_token

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 statePOST /token returns
dc:{hash} not found400 expired_token (or invalid_grant if you do not want to distinguish "wrong" from "expired")
pending, polled at the right pace400 authorization_pending
pending, polled earlier than interval400 slow_down, increase interval by 5 seconds
denied400 access_denied, delete key
approved, wins used200 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_id returns invalid_client. RFC 6749 §5.2 allows 401 for this error; for a public client that does not send an Authorization header, 400 is also valid. Pick one and write it into the spec.
  • If user_code still 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 borrows temporarily_unavailable from §4.1.2.1 (authorization endpoint) with HTTP 503 and Retry-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_id so an attacker cannot "fill up" the user_code space.
  • Cache-Control: no-store on 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:

  1. GET /device?user_code=BDFH-KLMN: normalize() (uppercase, drop characters outside the charset such as dashes and spaces) gives BDFHKLMN, look up uc:BDFHKLMN → dcHash → dc:{dcHash}.
  2. 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".
  3. POST /device/approve with user_code, decision=allow|deny and 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".

BranchBehaviorHTTP
Not signed inRedirect to login, keeping user_code in a return_to parameter checked for same origin302
Missing or wrong CSRF tokenReject403
user_code does not exist or has expired"Invalid or expired code" page, without saying whether it is wrong or expired404
Too many wrong attempts within the time windowTemporary lock per session and IP429
Session already approved/denied"Code already used" page409

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:

  1. Check that client_id matches the record. Otherwise, another client holding the device_code (leaked log) could exchange it for a token.
  2. Issue tokens once with SET NX. Two overlapping poll requests (the CLI retrying after a network timeout) can both see approved; only the request that wins the used key gets the tokens.
  3. slow_down increases interval permanently 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)

EndpointConditionerrorHTTP
/device/codeclient_id does not existinvalid_client401
/device/codeScope outside the allowed listinvalid_scope400
/device/codeRate limit exceeded per IP or clientNo standard OAuth code; return {"error":"rate_limited"} with Retry-After429
/device/codeuser_code collided 5 times in a rowOutside §5.2; convention temporarily_unavailable (borrowed from §4.1.2.1) with Retry-After503
/tokengrant_type other than device_codeunsupported_grant_type400
/tokenMissing device_codeinvalid_request400
/tokenSession not foundexpired_token400
/tokenclient_id does not match the sessioninvalid_grant400
/tokenPolled earlier than intervalslow_down400
/tokenNot yet approvedauthorization_pending400
/tokenDeniedaccess_denied400
/tokenTokens already issuedinvalid_grant400

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)
┌─────────────────────────────────────────────────────────┐│devclilogin--device││││1.POST/device/code──►getdevice_code,user_code││2.Printuser_code+URL,trytoopenthebrowser││3.Loop:││sleepinterval──►POST/token││authorization_pending──►continue││slow_down──►interval+=5,continue││200──►storetokens,call/userinfo,print││othererror──►printmessage,exit1││4.expires_inelapsed──►"Codeexpired,runagain"│└─────────────────────────────────────────────────────────┘

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.
  • interval is 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 {}
ScenarioClient behaviorReason
authorization_pendingContinue with the current intervalRFC 8628 §3.5
slow_downAdd 5 seconds to interval for all subsequent requestsRFC 8628 §3.5, MUST
access_denied, expired_token, other codesStop, print a message, non-zero exit codeOnly the two codes above allow further polling
Timeout or connection errorBack off (exponential backoff), still within deadlineRFC 8628 §3.5 recommends backoff on connection errors
Ctrl+CCancel the sleep and the in-flight request immediatelyDo 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, not cmd /c start: cmd.exe is 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_uri and user_code to 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_complete automatically on a machine with a display. With --no-browser or an SSH session, only print the URL so the user opens it on another device.
  • If process.env.CI is set, refuse to run interactive login and 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/keyring tries 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: 1 and a profiles{} map, matching the schema in Day 2, Part 2 (section 3); expiresAt is epoch ms. logout --profile work deletes only the work profile.
  • Atomic writes: write a temp file with 0600 permissions → fsync → rename over auth.json; on failure at any step, delete the temp file. Overwriting directly and then running chmod exposes the token while the old file still has 0644 permissions, and a process killed midway leaves half a JSON. rename within the same directory is atomic on POSIX; on Windows it can fail with EPERM/EBUSY when auth.json is held open by another process, so renameWithRetry retries a few times.
  • A shared lock for auth.json: all profiles live in the same file, so saveAuth (file branch) and clearAuth wrap their read-modify-write in withFileLock(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. withFileLock lives in lock.ts, explained in Day 4, Part 1.
  • Corrupted file: rename it to auth.json.bak and tell the user, rather than silently returning { profiles: {} }. Swallowing the error means the next saveAuth overwrites 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

MistakeConsequenceCorrect approach
Polling immediately, without waiting interval the first timeThe server returns slow_down from the very first requestSleep interval before every request
Printing tokens to stdout with --verboseTokens leak into CI logs and terminal historyMask 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 JSONTemp file with mode: 0o600 → fsync → rename
logout only deletes locallyThe refresh token is still usable if it was copiedCall revoke (RFC 7009) with a timeout, warn on failure, then delete locally
Opening the URL with cmd /c start on Windowscmd.exe treats & in the URL as a command separatorrundll32 url.dll,FileProtocolHandler <url>
Opening the browser automatically in an SSH sessionIt opens on the remote server, the user never sees itDetect headless, only print the URL
Not distinguishing access_denied from expired_tokenThe user does not know what to doOne 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 modelConsent page, MFA, SSO, Conditional Access out of the box
You own security, auditing, rate limitingThe 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

IdPDevice authorization endpointHow to enableDeviations to remember
Auth0https://{domain}/oauth/device/codeApplication type Native, Grant Types include Device Code, Token Endpoint Auth Method = None, OIDC ConformantCalling your own API requires sending audience; confidential clients are not supported
Oktahttps://{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 ruleNative apps only
Microsoft Entra IDhttps://login.microsoftonline.com/{tenant}/oauth2/v2.0/devicecodePublic client flowsDoes 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/codeMust enable "Device flow" in the app settingsThe 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/deviceEnable OAuth 2.0 Device Authorization Grant on the clientClose to the RFC; the verify page can sit behind your own short URL
Amazon Cognito user poolNoneNot supported nativelySee 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/code must include audience. To get a refresh token, add the offline_access scope 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 the message as 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 is authorization_declined (not access_denied), a wrong code is bad_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_code like WDJB-MJHT, verification_uri is https://github.com/login/device, expires_in 900, interval 5.
  • 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_down adds 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 versionDefault flow of aws sso login / aws configure sso
Before 2.22.0Device authorization
From 2.22.0Authorization 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-browser disables opening the browser automatically.
  • With PKCE, the CLI runs a callback server on localhost; --redirect-port picks 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:

┌──────────────────────────────────────────────────────────┐│OptionA:loopback+PKCE(recommendedifbrowserexists)││devcli──►Cognito/oauth2/authorize(code+PKCE)││◄──redirecthttp://127.0.0.1:{port}/callback│├──────────────────────────────────────────────────────────┤│OptionB:buildyourown"deviceauthorizationservice"││devcli──►POST/device/code(yourservice)││browser─►/device──►Cognitosign-in(code+PKCE)││servicebindstheresulttothedevicesession,issues││devcli──►POST/tokenpolling(yourservice)│├──────────────────────────────────────────────────────────┤│OptionC:switchtoanIdPwithanativedeviceflow│└──────────────────────────────────────────────────────────┘

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 mistakeSymptomFix
Forgetting to enable the grant/Device flow on the appunauthorized_client, device_flow_disabled, or an equivalent error at the very first stepEnable the grant in the IdP console; add this step to the deployment runbook
Creating a Web app instead of NativeThe IdP rejects the device grantAuth0 and Okta require the Native application type
Missing offline_accessLogin works but there is no refresh token, users must log in again every hourAdd the scope and enable the setting that allows offline access
Missing audience (Auth0)The token cannot call your own APISend audience set to the API Identifier
Printing verification_uri_complete when the provider does not return itAn undefined link in the terminalFall back to verification_uri + user_code
Hardcoding error codes for one providerDoes not recognize a user denial on another providerPer-provider mapError adapter
Not sending Accept: application/jsonParse errors with GitHubAlways 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:

ScenarioBrowser actionExpected CLI result
ApproveEnter the code, click allowExit 0, tokens stored, whoami shows the right account
DenyEnter the code, click denyExit 1, message "was denied" (whatever error code the provider uses)
AbandonDo nothingExit 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

  1. Why should the server store sha256(device_code) instead of the plaintext, while user_code is stored in plaintext?

    Show answer

    device_code is a bearer secret: whoever holds it and the client_id can 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. The user_code, on the other hand, must be typed in again by the user on the /device page, 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.

  2. Two POST /token requests from the same CLI arrive almost simultaneously right after the session becomes approved. 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 gets invalid_grant. If you only rely on "read status then delete key", both requests can read approved before either has deleted it, issuing two token sets for a single approval.

  3. The server receives a poll request 2 seconds after the previous one while the session's interval is 5 seconds. What must the server do, and how must the client react?

    Show answer

    The server returns 400 with error=slow_down and increases the session's interval by 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_down is not a terminal error; only authorization_pending and slow_down allow polling to continue.

  4. Why does the /device/approve endpoint need a CSRF token, even though this flow has no redirect back to the client?

    Show answer

    /device/approve is a state-changing action performed by a signed-in user via the session cookie. A malicious page can build a self-submitting form with decision=allow and an attacker-generated user_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.

  5. What message should the /device page return when the user_code is 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.

  6. Why must the CLI sleep interval before the first /token request, instead of calling right after printing the code?

    Show answer

    RFC 8628 §3.5 requires the client to wait at least interval seconds before each token request. The user also cannot approve within the first few hundred milliseconds. Calling immediately only creates a wasted request and may get slow_down, increasing the whole session's interval by 5 seconds.

  7. 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_in deadline. expired_token is an official response that the session is over; the client must stop immediately, inform the user, and suggest running login again.

  8. Why does the example use @napi-rs/keyring instead of keytar, and what must happen when the keychain is unavailable?

    Show answer

    The keytar repository has been archived since 12/2022 and is no longer maintained. @napi-rs/keyring is a Node binding of keyring-rs and still ships new releases. On Linux you must pin store: "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.json with 0600 permissions (directory 0700), stored under profiles{}, and prints a warning so the user knows.

  9. devcli logout calls 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.

  10. Why should devcli login refuse to run when the CI variable 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.

  1. 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.

  1. Why did AWS CLI v2, from version 2.22.0, switch aws sso login to 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.

  1. 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.

  1. Calling Auth0's /oauth/device/code succeeds, but the access token cannot call https://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.

  1. Why should the CLI send Accept: application/json when 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


Next lesson →