devHọc Dev

Week 1 - Day 1: Why CLIs need their own flow, RFC 8628, and user_code design

Week 1 – Day 1

This lesson combines 3 topics: Why a CLI needs its own login flow, RFC 8628 — Device Authorization Grant step by step, Designing the user_code and the confirmation page.

Learning Objectives

  • Understand why the "standard" Authorization Code flow of a web app cannot be used as-is for a CLI
  • List and compare 5 ways a CLI can authenticate a user or a machine
  • Read the output of a device-flow-style login command and know which step each line corresponds to
  • Know which flow popular CLIs (GitHub CLI, AWS CLI, Azure CLI, gcloud) choose and why
  • Have a decision framework for choosing the flow of a new CLI (DevCLI from ACME Cloud)
  • Know the exact request/response of the device authorization endpoint and the token endpoint per RFC 8628
  • Understand the meaning and default values of expires_in and interval
  • Correctly handle the 4 device-flow-specific error codes: authorization_pending, slow_down, access_denied, expired_token
  • Draw the complete sequence diagram of the device flow
  • Compare device flow with Authorization Code to know what is "lost" and what "makes up for it"
  • Choose the charset, length, and format of the user_code based on the recommendations in RFC 8628 §6.1
  • Calculate entropy and the probability of a correct guess given rate limiting and expiry
  • Understand why the device_code must have high entropy while the user_code does not
  • Design a verification page and consent screen with enough information for the user to spot an unexpected request
  • Know when to use verification_uri_complete and QR codes, and the risks that come with them

Part 1: Why a CLI needs its own login flow

1. The problem: a CLI is not a web app

In the Login Flow Design course, the BFF is a confidential client: it runs on a server, keeps a client_secret, and has a fixed redirect_uri on its own domain. A CLI is completely different:

┌───────────────────────────────────────────────────────────┐│Webapp(BFF)CLI(devcli)││││RunsonacompanyserverRunsonadevlaptop,││SSHserver,CIcontainer││Cankeepaclient_secretCANNOTkeepasecret││(anyonecangetthebinary)││Fixedredirect_uriNodomainofitsown││https://portal.example.comfortheIdPtoredirectto││User'sbrowserisonMayhaveNObrowser││thesamedevice(SSH,Docker,TV)│└───────────────────────────────────────────────────────────┘

Three consequences:

  1. A CLI is a public client. Any "secret" embedded in the binary is effectively public. So a CLI must use PKCE or a grant that needs no secret.
  2. No web-style redirect URI. The IdP cannot redirect back to "the terminal". The CLI needs another channel to receive the result: either open a small web server on 127.0.0.1 (loopback), or ask periodically (polling) whether the user has approved (device flow).
  3. There may be no browser. When a developer SSHes into a server, runs inside a container, or the CLI runs on a Smart TV, there is no browser to open. The user has to use a second device (laptop, phone).

Self-check question: if you embed a client_secret in the devcli binary and publish it to npm, who can use that secret? (Answer: anyone who downloads the package and reads the binary.)

2. Five ways a CLI can authenticate

#MethodWho authenticatesBrowser?Supports IdP SSO/MFANotes
1API key / Personal Access Token (PAT) pasted into the CLIThe user creates the token on the webNo (at use time)Indirectly (when creating the token)Simple, but tokens are usually long-lived and easily leaked in shell history
2Resource Owner Password Credentials (ROPC): the CLI asks for username/password and sends them to the IdPThe CLI holds the passwordNoPractically none (MFA, passkeys, federated SSO all break)RFC 9700 §2.4: MUST NOT be used
3Authorization Code + PKCE via loopback redirect (RFC 8252)The IdP, in a browser on the same machineRequired, on the same machineFullSmoothest experience when a browser is available
4Device Authorization Grant (RFC 8628)The IdP, in a browser on any deviceRequired, but can be on another deviceFullWorks over SSH/in containers; has its own phishing risk (Day 2, Part 3)
5Workload identity / OIDC federation / mTLSInfrastructure (CI provider, cloud)NoNot applicable (no human)For machines, not humans (Day 4, Part 1)

Two principles follow:

  • Humans logging in to a CLI: use (3) when there is a browser on the same machine, (4) when there is not or when you need to log in from another device. (1) is the fallback.
  • Machines (CI, cron, servers) calling an API: use (5) or a narrowly scoped machine token. Do not run device flow in CI — there is nobody there to approve it.

Why ROPC is forbidden

RFC 9700 (OAuth 2.0 Security Best Current Practice, 01/2025) says it plainly: "The resource owner password credentials grant MUST NOT be used." Reasons:

  • The CLI sees the user's real password → the password can leak through logs, crash dumps, plugins.
  • The IdP no longer controls the login step → it cannot enforce MFA, passkeys, device/location-based sign-in policies, or SSO via an enterprise IdP.
  • Users get "trained" to type their password somewhere other than the IdP's page → they become easier to phish.

3. Reading the output of a device-flow login command

This is typical output when running the login command of a public CLI that uses device flow (the format matches real output; the command name and codes have been replaced):

$ <cli> login
> Visit https://example.com/device?user_code=WDJB-MJHT

Waiting for authentication...

  Congratulations! You are now signed in.

Each line corresponds to a step in RFC 8628:

Output lineWhat is happening behind the scenes
(before printing)The CLI calls POST /device/code with client_id (and scope). The server returns device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval
Visit https://…/device?user_code=WDJB-MJHTThe CLI prints verification_uri_complete (the URL with the code already embedded). Many CLIs also try to open the browser with this URL right away
Waiting for authentication...The CLI starts polling POST /token with grant_type=urn:ietf:params:oauth:grant-type:device_code and device_code. The server returns authorization_pending until the user approves
(user opens the link, signs in to the IdP, clicks "Approve")The browser talks to the server; the CLI knows nothing about this step
Congratulations! You are now signed in.The next poll receives an access_token (and usually a refresh_token). The CLI stores the token on the machine (Day 2, Part 2)

DevCLI uses a clearer closing line that also states the identity and scope so the user can spot a wrong account immediately: ✓ Logged in: dev@example.com (profile: default, team: team-platform).

Two subtle points:

  • The device_code never appears on screen. It is the "key" to obtain the token, held only by the CLI. What the user sees is the user_code, a short code for typing by hand.
  • The browser does not need to be on the same machine. The printed link can be opened on a phone. That is why device flow works over SSH.
┌──────────────┐1.POST/device/code┌──────────────────────┐│devcli│────────────────────────▶│AuthorizationServer││(terminal)│◀────────────────────────│auth.example.com│││device_code,user_code└──────────────────────┘││▲││3.pollPOST/token│2.useropens││────────────────────────▶(sameAS)│/device,enters││◀────pending...token│user_code,└──────────────┘│signsin,Approve┌──────────┴───────────┐│Browser(laptop││orphone)│└──────────────────────┘

The information below was checked against the official documentation at the time of writing; behavior may change between CLI versions.

CLIDefault when a browser is availableWhen there is no browser / you want to log in from another deviceSource
AWS CLI aws sso loginAuthorization Code + PKCE (default since v2.22.0), callback to localhost (--redirect-port picks the port)--use-device-code uses Device Authorization; --no-browser to not open the browser automaticallyAWS CLI User Guide, aws sso login reference
Azure CLI az loginSince v2.61.0: WAM (Web Account Manager) on Windows, browser sign-in on macOS/LinuxIf the browser cannot be opened it falls back to the device code flow at https://aka.ms/devicelogin; force it with --use-device-codeMicrosoft Learn: Sign in interactively with Azure CLI
GitHub CLI gh auth loginBrowser-based flow with a one-time OAuth device code (with a --clipboard flag to copy the code)Same flow, open the link on another machine; or --with-token to read a PAT from stdinGitHub CLI manual gh auth login
gcloud gcloud auth loginOpens a browser on the same machine--no-browser: the "remote bootstrap" flow — copy a command to a machine that has a browser and gcloud and run it there. Not the RFC 8628 device flowgcloud reference auth login

Lesson: there is no "one correct flow for every CLI". Major CLIs usually have both: loopback/browser as the default for the best experience, and device code as the fallback for environments without a browser.

5. Decision framework for DevCLI

ACME Cloud wants to launch devcli. Its users are developers; 30% run it in SSH/devcontainers; the IdP is its own authorization server auth.example.com.

┌──────────────────────────────┐│Whoisauthenticating?│└──────────────┬───────────────┘Machine(CI,cron)│Human┌─────────────────────────┴───────────────────┐▼▼┌──────────────────────┐┌───────────────────────────┐│OIDCfederation/││Canabrowserbeopened││scopedmachinetoken││ontheSAMEmachine?││(Day4,Part1)│└─────────────┬─────────────┘└──────────────────────┘Yes│No/SSH┌───────────────────┴──────────────┐▼▼┌──────────────────────┐┌──────────────────────┐│Loopback+PKCE││DeviceAuthorization││(default,││Grant(Parts2-3)││Day2,Part1)│││└──────────────────────┘└──────────────────────┘

Decisions for DevCLI (used throughout the course):

  • devcli login: try loopback + PKCE; if it detects that a browser cannot be opened (SSH_CONNECTION variable, no DISPLAY on Linux, running in a container), it automatically switches to device flow.
  • devcli login --device: force device flow.
  • devcli login --no-browser: does not change the flow, it only skips opening the browser and prints the URL for the user to open. (DevCLI does not use --use-device-code; that is an AWS CLI/Azure CLI flag.)
  • In CI: no login; use DEVCLI_TOKEN or OIDC federation.

6. Common design mistakes

MistakeConsequenceCorrect approach
Embedding a client_secret in the CLI and treating it as secretAnyone can impersonate the clientRegister the CLI as a public client; use PKCE / device flow
Asking for the password in the terminal (ROPC)Loses MFA/SSO, password leaksAlways send the user to the IdP's page
Supporting only loopbackDevelopers on SSH/devcontainers cannot log inHave device flow as the fallback
Running device flow in CI "for convenience"The pipeline hangs waiting for approval, or someone approves blindlyMachine token or OIDC federation
Printing the device_code to logsAnyone reading the logs can get the token once the user approvesPrint only the user_code and URL

Questions to ask the IdP before choosing a flow

Before committing to a flow, check the IdP you use:

  1. Does it allow registering a public client (no secret)?
  2. Does it support PKCE S256, and can it be enforced for that client?
  3. Does it accept loopback redirects with any port (http://127.0.0.1/callback)?
  4. Can the Device Authorization Grant be enabled for this client only, and what are expires_in and interval?
  5. Does it have a revocation endpoint (RFC 7009) and refresh token rotation?
  6. Do customer organizations have a policy that blocks device flow (e.g. Conditional Access)?

7. Terminology used in this course

TermMeaning in this course
Public clientA client that cannot keep secrets (CLI, mobile app, SPA). Has no real client_secret
Authorization Server (AS)The server that issues tokens. In the examples: auth.example.com
Device clientThe application that starts the device flow, here devcli
device_codeThe secret code the CLI uses to obtain the token when polling. Never shown to the user
user_codeThe short code shown to the user to enter in the browser
Verification URIThe page the user opens to enter the user_code, e.g. https://example.com/device
PollingThe CLI calls the token endpoint periodically to ask "has the user approved yet?"
Loopback redirectA redirect to a temporary web server of the CLI on 127.0.0.1
PKCEProof Key for Code Exchange (RFC 7636), binds whoever started the flow to whoever exchanges the code
Credential storeThe OS secret store: Keychain, Credential Manager, Secret Service
ProfileA named set of login configuration (account, team, issuer)
OIDC federationCI proves its identity with a token issued by the CI platform and exchanges it for short-lived credentials

8. Course roadmap

The course is 1 week, 5 days. Each day combines 3 related topics into Parts.

WeekDayTopicQuestion you can answer after studying
11, Part 1Why a CLI needs its own flowWhich flow should my CLI use?
11, Part 2RFC 8628 in detailWhat do the CLI and the AS exchange, and how are errors handled?
11, Part 3user_code and the confirmation pageHow long should the code be, and what should the consent page show?
12, Part 1Loopback + PKCEHow does a CLI receive a callback without a domain?
12, Part 2Storing tokens on the developer machineWhere do tokens live, and what does logout do?
12, Part 3SecurityHow do attackers abuse device flow?
13, Parts 1-2Building the AS and the CLIWrite the code for both sides
13, Part 3Existing IdPsHow do Auth0, Entra ID, GitHub, Keycloak support it?
14, Part 1Token lifecycle, profiles, CIRefresh, multiple accounts, CI with no human
14, Part 2Debugging and operations"I'm logged in but still Not authorized" — what now?
14, Part 3CapstoneWrite a complete spec and threat model
15Final quiz30 questions covering the whole course

Part 2: RFC 8628 — Device Authorization Grant step by step

1. Three roles and two channels

┌──────────────────────────────────────────────────────────────┐│Deviceclient:devcliintheterminal(publicclient)││Authorization:auth.example.com││Server(AS)-deviceauthorizationendpoint││-tokenendpoint││-verificationpage(browser)││Enduser:dev,usingabrowseranywhere││││Channel1(device↔AS):HTTPS,theCLIinitiatescalls││Channel2(user↔AS):browser,NOTconnectedtotheCLI│└──────────────────────────────────────────────────────────────┘

The core of RFC 8628: the two channels do not talk to each other directly. The RFC assumes the device has no way to receive a signal back from the browser. The only bridge is the user_code, which the user carries from the CLI screen to the browser. The CLI learns the result by asking the AS again periodically (polling).

The device authorization endpoint can be published in the AS metadata (RFC 8414) via the device_authorization_endpoint field, just as token_endpoint is published. The CLI should read the metadata instead of hard-coding URLs.

Example metadata (trimmed) that DevCLI reads from https://auth.example.com/.well-known/oauth-authorization-server:

{
  "issuer": "https://auth.example.com",
  "authorization_endpoint": "https://auth.example.com/authorize",
  "token_endpoint": "https://auth.example.com/token",
  "device_authorization_endpoint": "https://auth.example.com/device/code",
  "revocation_endpoint": "https://auth.example.com/revoke",
  "grant_types_supported": [
    "authorization_code",
    "refresh_token",
    "urn:ietf:params:oauth:grant-type:device_code"
  ],
  "code_challenge_methods_supported": ["S256"]
}

device_authorization_endpoint is registered by RFC 8628 §4 in the RFC 8414 metadata registry. If the AS does not publish this field, the CLI should report a clear error, "the IdP has not enabled device flow", instead of guessing the URL.

2. Step 1 — Device Authorization Request

POST /device/code HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

client_id=devcli&scope=openid%20offline_access%20deploy%3Aread
ParameterRequiredNotes
client_idYes (for public clients)A public client sends only client_id. A confidential client authenticates as it does at the token endpoint (RFC 6749 §3.2.1)
scopeNoThe requested scope. DevCLI defaults to openid offline_access deploy:read; deploy:write is requested only via step-up when a command needs it (Day 4, Part 1). If omitted, the server uses the default openid offline_access deploy:read

Rules worth remembering from RFC 8628 §3.1:

  • Every request from the device MUST use TLS.
  • Parameters sent without a value are treated as omitted; the AS ignores unrecognized parameters; each parameter appears at most once.
  • The client SHOULD start device authorization only when the user asks for it (typing the login command), not automatically at app startup or when an old session expires. Reason: every start triggers a series of polling requests.

3. Step 2 — Device Authorization Response

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store

{
  "device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS",
  "user_code": "WDJB-MJHT",
  "verification_uri": "https://example.com/device",
  "verification_uri_complete": "https://example.com/device?user_code=WDJB-MJHT",
  "expires_in": 1800,
  "interval": 5
}
FieldRequiredMeaning
device_codeYesThe secret code the CLI uses when polling. High entropy, never shown
user_codeYesA short code for the user to type by hand
verification_uriYesThe page the user opens in the browser. Should be short and memorable because the user may have to type it
verification_uri_completeNoA URL with the user_code embedded, used for QR codes or opening the browser directly
expires_inYesLifetime (seconds) of both the device_code and the user_code
intervalNoMinimum number of seconds between 2 polls. If absent, the client MUST use 5

Real-world example: GitHub returns expires_in = 900 (15 minutes) and interval = 5 for the OAuth app device flow (per GitHub Docs). The RFC example uses 1800 seconds. The specific numbers are the AS's decision (Part 3 of this lesson and Day 2, Part 3).

4. Step 3 — The user confirms in the browser

The CLI prints instructions: "Open https://example.com/device and enter the code WDJB-MJHT", or prints verification_uri_complete directly, or draws a QR code. In the browser:

  1. The user opens the verification page.
  2. Signs in to the IdP if not already signed in (MFA, passkeys, enterprise SSO all work because this is the AS's real page).
  3. Enters the user_code (or the code pre-filled from verification_uri_complete).
  4. Reviews the consent screen: which client, which permissions, which device started the request.
  5. Clicks Approve or Deny.

RFC 8628 does not specify the UI for this step; it only gives security recommendations (Part 3 of this lesson and Day 2, Part 3).

5. Step 4 — Polling the token endpoint

Right after displaying the instructions, the CLI starts sending:

POST /token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded

grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code
&device_code=GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS
&client_id=devcli

grant_type=urn:ietf:params:oauth:grant-type:device_code is an extension grant defined by RFC 8628 (using the mechanism in RFC 6749 §4.5). client_id is required if the client does not authenticate in some other way.

Responses:

  • Success: a standard RFC 6749 §5.1 response (access_token, token_type, expires_in, optionally refresh_token, scope).
  • Not done yet / error: a standard RFC 6749 §5.2 error response (HTTP 400, JSON body with error), with these specific codes:
errorMeaningWhat the CLI must do
authorization_pendingThe user has not finishedWait at least interval seconds (or 5s if absent), then poll again
slow_downStill waiting, but the client is polling too fastIncrease the interval by 5 seconds for this and all subsequent requests, then keep polling
access_deniedThe user clicked DenyStop polling, report an error
expired_tokenThe device_code has expiredStop polling. MAY start over, but SHOULD wait for the user to ask instead of restarting automatically
Other codes (invalid_client, invalid_grant...)Configuration or request errorMUST stop polling, report an error

In addition, RFC 8628 §3.5 requires: on a connection timeout, the client MUST reduce its polling frequency before retrying; exponential backoff is recommended (e.g. double the interval after each timeout).

┌──────────────────────────────────────────────────────────┐│CLIpollingloop││││interval=response.interval??5││loop:││sleep(interval)││r=POST/token││authorization_pending->continue││slow_down->interval+=5,continue││connectiontimeout->interval*=2,continue││200OK->savetoken,exit││access_denied->report"denied",exit││expired_token->report"codeexpired",exit││othererror->reporterror,exit│└──────────────────────────────────────────────────────────┘

6. Complete sequence diagram

sequenceDiagram
    autonumber
    participant U as Dev (user)
    participant C as devcli
    participant AS as auth.example.com
    participant B as "Browser (any device)"

    U->>C: devcli login --device
    C->>AS: POST /device/code (client_id, scope)
    AS-->>C: 200 device_code, user_code, verification_uri, expires_in, interval
    C-->>U: Prints "Open example.com/device, enter WDJB-MJHT"
    loop Every interval seconds
        C->>AS: POST /token (grant_type=device_code, device_code, client_id)
        AS-->>C: 400 error=authorization_pending
    end
    U->>B: Open verification_uri
    B->>AS: GET /device
    AS-->>B: Sign-in page (MFA, SSO...)
    B->>AS: Sign in, enter user_code
    AS-->>B: Consent screen (client, scope, device)
    B->>AS: Approve
    C->>AS: POST /token (device_code)
    AS-->>C: 200 access_token, refresh_token
    C-->>U: ✓ Logged in: dev@example.com (profile: default, team: team-platform)

Note: polling happens in parallel with the browser steps. The order in the diagram is for illustration only.

7. Compared with Authorization Code + PKCE

AspectAuthorization Code + PKCEDevice Authorization Grant
How the result returns to the clientRedirect to redirect_uri (with code)The client polls the token endpoint
Needs a browser on the same deviceYesNo
Binding between the sending and receiving clientPKCE (code_verifier) + statedevice_code held only by the client
CSRF protection on the callbackstateNo callback, so no state needed
Specific risksHijacked redirect URI, mix-upRemote phishing: an attacker gives the victim their own user_code (Day 2, Part 3)
Load on the token endpoint1 requestMany polling requests → needs rate limiting, slow_down

8. Common implementation mistakes

MistakeConsequence
Polling immediately without waiting for intervalConstant slow_down or getting rate limited
Receiving slow_down but not permanently increasing the intervalViolates the RFC; the AS may block the client
Treating every 400 error as "pending" and polling foreverThe CLI hangs indefinitely on misconfiguration (invalid_client)
Automatically starting a new device flow on expired_tokenCreates a loop generating codes nobody uses, increasing load and phishing risk
No overall timeoutThe CLI hangs if the AS never returns expired_token

Part 3: Designing the user_code and the confirmation page

1. Two codes, two purposes

┌───────────────────────────────────────────────────────────┐│device_codeuser_code││────────────────────││HeldonlybytheCLIShowntouser,hand-typed││ExchangedforthetokenLinksthebrowserto││theCLI'ssession││VERYhighentropy(>=128bit)Justenoughentropy,short││NeednotbereadableMustbeeasytoread/type││Guessed=attackergetstheGuessed=deviceboundto││victim'stokentheattacker'saccount│└───────────────────────────────────────────────────────────┘

RFC 8628 §5.2: because the device_code is not displayed, there is no UX reason to make it short, so it SHOULD use a very high-entropy code. Conversely, the user_code must be short enough to type, so its entropy is lower and must be compensated with rate limiting + a short expiry (§5.1).

Note the consequence in §5.1: if an attacker guesses a user_code correctly, they approve with their own account, so the victim's device receives a token bound to the attacker's account. This is the reverse of guessing a bearer token. It is not always economically worthwhile for the attacker, but it is still a privacy risk and can be dangerous if that account can control the device.

2. Charset per RFC 8628 §6.1

Users often enter the code on a phone, where switching case or switching to digits is slow. The RFC suggests:

  • Use only letters A-Z, case-insensitive, no digits.
  • Drop vowels to avoid accidentally forming real words (possibly offensive ones).
  • Result: the base-20 charset BCDFGHJKLMNPQRSTVWXZ.
  • You may add a hyphen for readability, e.g. WDJB-MJHT: 8 significant characters, entropy 20^8.
  • All-digit codes also work well for locales that do not use A-Z keyboards, but they must be longer. RFC example: 9 digits 019-450-730, entropy 10^9.

When processing input, the server should strip hyphens and punctuation and uppercase the input before comparing (for the A-Z charset). Whether the user types wdjbmjht or WDJB MJHT, it must be accepted.

FormatExampleCombinationsBits of entropy (approx.)
8 base-20 charactersWDJB-MJHT20^8 ≈ 2.56 × 10^1034.5
9 digits019-450-73010^929.9
6 digits (too short)482-91310^619.9

3. Calculating the probability of a correct guess

RFC 8628 §5.1 gives an example: with a 128-bit symmetric key, an attacker must spend 2^96 work to have a 2^-32 chance of guessing correctly. With an 8-character base-20 code (~34.5 bits), achieving the same 2^-32 probability through random guessing means rate limiting and expiry may allow only about 5 attempts.

In practice there is one more factor: the attacker does not need to guess one specific code, only any code that is still valid. The probability per guess:

P(hit per guess) = number of active codes / total combinations

DevCLI example: at any time about 2,000 codes are pending, 8-character base-20 codes.

P(1 guess) = 2,000 / 2.56e10        ≈ 7.8e-8
Rate limit = 10 attempts/minute/IP, block IP after 50 wrong
Attacker has 1,000 IPs, at most 50 attempts per IP
Total attempts = 50,000
P(at least 1 hit) ≈ 50,000 × 7.8e-8 ≈ 0.4%

0.4% is not 0. So the server needs additional layers of protection:

  • Rate limit by signed-in account on the verification page (the attacker must sign in before entering a code), not just by IP.
  • Count wrong entries per account and lock temporarily.
  • Short expiry (expires_in) to reduce the number of active codes.
  • Anomaly detection: one account entering many different codes in a short time.

4. Generating codes securely

import { randomInt, randomBytes } from 'node:crypto';

const USER_CODE_CHARSET = 'BCDFGHJKLMNPQRSTVWXZ'; // base-20, RFC 8628 §6.1

/** user_code in XXXX-XXXX form, uses a CSPRNG (not Math.random). */
export function generateUserCode(): string {
  let raw = '';
  for (let i = 0; i < 8; i++) {
    raw += USER_CODE_CHARSET[randomInt(USER_CODE_CHARSET.length)];
  }
  return `${raw.slice(0, 4)}-${raw.slice(4)}`;
}

/** device_code: 32 random bytes (256 bits), base64url. */
export function generateDeviceCode(): string {
  return randomBytes(32).toString('base64url');
}

/** Normalize user input: drop every non-letter character, uppercase. */
export function normalizeUserCode(input: string): string {
  return input.replace(/[^a-z]/gi, '').toUpperCase();
}

Notes:

  • randomInt from node:crypto uses a CSPRNG and avoids modulo bias.
  • When storing, use the normalized form (WDJBMJHT) as the lookup key; the hyphenated form is for display only.
  • Check for collisions with active codes before issuing (unlikely but possible).
  • Store a hash of the device_code instead of plaintext (details in Day 3, Part 1).

5. The verification page

Goal: the user enters the code quickly with few mistakes, and recognizes if the request was not started by them.

┌─────────────────────────────────────────────────────────┐│example.com/device││││Connectadevice││Enterthecodeshowninyourterminal:││││[WDJB]-[MJHT]││││(Continue)││││Didn'tjustrunalogincommandyourself?Closethis││page.NoonefromACMECloudwillaskyouforthiscode│└─────────────────────────────────────────────────────────┘

Recommendations:

  • Short, easy-to-type URL (example.com/device), because the user may have to type it on a phone.
  • The input field auto-uppercases, accepts codes with or without the hyphen, and accepts pasting either the code or the URL.
  • Require sign-in before entering the code, so rate limiting can be per account.
  • Generic error message ("Invalid or expired code"), not distinguishing "wrong" from "expired" so as not to help code guessers.
  • Accessibility: the input has a label, works with screen readers, and the code is shown in a monospace font.
  • i18n: if your market uses non-Latin keyboards, consider a longer all-digit code.

After the code is validated, the AS shows a confirmation screen. RFC 8628 §5.4 recommends informing the user that they are authorizing a device and confirming that the device is in their possession; the AS SHOULD display information about the device so the user can notice if software is impersonating a device.

┌─────────────────────────────────────────────────────────┐│AllowDevCLItoaccessyouraccount?││││App:DevCLI(ACMECloud,officialapp)││Access:Readprojects,createdeployments││Requestedfrom:IP203.0.113.24-Hanoi,VN││at10:42,1minuteago││Code:WDJB-MJHT(matchesyourterminal?)││││OnlycontinueifYOUjustran"devclilogin".││││(Deny)(Allow)│└─────────────────────────────────────────────────────────┘

Each line has a reason:

InformationWhy it is needed
App name + "official" labelThe user knows who they are granting access to
Easy-to-understand permission listAvoids over-granting
IP and location of the initiating deviceThe user is in Ho Chi Minh City but the request comes from another country → sign of phishing
Time of initiationThe code was created 20 minutes ago but the user just ran the command → suspicious
Showing the code againEspecially important when using verification_uri_complete (section 7)
Clear warning sentenceReduces the effectiveness of the "IT staff sent you a code" scenario

7. verification_uri_complete and QR codes

verification_uri_complete (e.g. https://example.com/device?user_code=WDJB-MJHT) allows:

  • The CLI to open the browser directly with the code pre-filled.
  • Devices without a keyboard (TV, IoT) to draw a QR code to scan with a phone.

In exchange, the user no longer types the code themselves, so they are more likely to click "Allow" reflexively when they receive a link by email or message. RFC 8628 §5.4 stresses: for an AS that supports verification_uri_complete, confirming that the device is in the user's possession is even more important. The RFC's suggestion: show the code again in the flow and ask the user to check that it matches the code shown on the device.

Considerations for DevCLI:

ContextUse verification_uri_complete?
The CLI opens the browser itself on the same machineYes, but the page still requires clicking confirm and shows the code again
The CLI runs over SSH and prints the link to the terminalYes, and also prints the code separately for the user to compare
Sending the link by email/chat to someone elseNever: this is exactly the phishing scenario

8. Choosing expires_in

RFC 8628 §5.4: the code must live long enough for the user to grab a second device, open the page, and sign in (possibly with MFA), but short enough to reduce the value of codes obtained through phishing. A short-lived code does not stop a real-time interactive attacker, but it does limit codes sent via email or SMS.

ValueComment
1800 seconds (RFC example)Generous; suits first-time device setup where the user needs time
900 seconds (GitHub device flow)Balanced for a developer tool
300-600 secondsSuits internal CLIs with SSO already in place; reduces the phishing window

DevCLI chooses 600 seconds, with an interval of 5 seconds.

9. Verification page test checklist

#ScenarioExpected result
1Enter the code in lowercase, with spacesAccepted
2Enter an expired code"Invalid or expired code"
3Enter a code that was already approvedSame message, no state leaked
4Consecutive wrong entries beyond the thresholdTemporarily blocked per account
5Open verification_uri_complete while not signed inAfter signing in, returns to the same code
6Initiating IP in a different country from the browserProminent warning on the consent screen

Review Questions

  1. Why must a CLI distributed via npm/Homebrew be treated as a public client?

    Show answer

    The CLI binary sits on every user's machine, and anyone can unpack it and read the strings inside. A client_secret embedded there is no longer secret, so the authorization server cannot use it to authenticate the client. Therefore the CLI registers as a public client and relies on mechanisms that need no secret: PKCE for loopback, or a one-time device_code for device flow.

  2. What does RFC 9700 say about the Resource Owner Password Credentials grant? Give two reasons.

    Show answer

    RFC 9700 §2.4 states that this grant MUST NOT be used. Reasons: (1) the client sees the user's real password, increasing the leak surface (logs, crash dumps, plugins); (2) the IdP loses control of the login step, so it cannot enforce MFA, passkeys, federated SSO, or device-based policies; in addition, users get used to typing their password somewhere other than the IdP's page, making them easier to phish.

  3. In the output Visit https://example.com/device?user_code=WDJB-MJHT, which RFC 8628 parameter is being printed? Why doesn't the CLI print the device_code?

    Show answer

    It is verification_uri_complete (the URL with the user_code embedded). The device_code is the value the CLI uses to obtain the token when polling; anyone with the device_code can get the token as soon as the user approves, so it must never be displayed or logged. The user only needs the user_code, a short code to enter or confirm in the browser.

  4. Is gcloud auth login --no-browser the RFC 8628 device flow?

    Show answer

    No. According to the gcloud documentation, --no-browser displays a gcloud auth login --remote-bootstrap=... command for the user to run on another machine that has a browser and gcloud installed, then paste the result back. This is a gcloud-specific mechanism, with no user_code and no polling of a token endpoint as in RFC 8628. This example shows you need to read each CLI's docs instead of assuming.

  5. DevCLI needs to support both loopback and device flow. State the conditions under which the CLI automatically switches to device flow.

    Show answer

    When the CLI detects that it cannot open a browser on the same machine: it is in an SSH session (SSH_CONNECTION/SSH_TTY is set), Linux has no DISPLAY/WAYLAND_DISPLAY, it is running in a container/devcontainer, or the browser-opening command fails. The user can also force it with the --device flag. In CI it does not switch to device flow; instead it reports an error telling the user to use a machine token or OIDC federation.

  6. If the device authorization response has no interval field, how long must the CLI wait between two polls? What is the source of this rule?

    Show answer

    5 seconds. RFC 8628 §3.2 defines interval as OPTIONAL and states "If no value is provided, clients MUST use 5 as the default." §3.5 repeats it: before each new request, the client MUST wait at least interval seconds, or 5 seconds if absent.

  7. The CLI is polling every 5 seconds and receives slow_down. What is the new interval, and how long does it apply?

    Show answer

    10 seconds. Per RFC 8628 §3.5, on receiving slow_down the interval MUST be increased by 5 seconds "for this and all subsequent requests", meaning it applies to every subsequent poll in this session and never goes back to 5 seconds. If another slow_down arrives, add 5 again (15, 20...).

  8. Among the error codes returned by the token endpoint, which ones allow the CLI to keep polling? What does the RFC require for the others?

    Show answer

    Only authorization_pending and slow_down allow polling to continue. For any other error code (access_denied, expired_token, invalid_client, invalid_grant...), RFC 8628 §3.5 requires the client MUST stop polling and SHOULD react appropriately, for example by displaying the error to the user.

  9. Why doesn't device flow need a state parameter like Authorization Code does?

    Show answer

    state protects against CSRF on the callback: it ensures the redirect response to redirect_uri belongs to the session that started it. Device flow has no redirect or callback to the client; the client fetches the result itself using a device_code that only it holds. The "whoever starts it receives the token" binding is guaranteed by the high-entropy device_code (RFC 8628 §5.2).

  10. On receiving expired_token, should the CLI automatically call /device/code again to get a new code?

Show answer

Not automatically. RFC 8628 §3.5 allows (MAY) starting over but recommends (SHOULD) waiting for user interaction before restarting, to avoid unnecessary polling. In practice the CLI should report "the code has expired, run devcli login again". Continuously generating codes also creates "orphan" codes that can be abused.

  1. Why does RFC 8628 suggest the charset BCDFGHJKLMNPQRSTVWXZ for the user_code?
Show answer

Users often enter the code on a phone, where switching case or switching to digits takes time. Using case-insensitive A-Z letters with no digits makes typing fast. Dropping vowels keeps random codes from accidentally forming real words (possibly offensive ones). The result is a set of 20 consonants (RFC 8628 §6.1).

  1. How many combinations and roughly how many bits of entropy does an 8-character base-20 user_code have? Why is that acceptable when the device_code must be much longer?
Show answer

20^8 ≈ 2.56 × 10^10 combinations, about 34.5 bits. The user_code is acceptable because it is constrained by rate limiting and a short expiry, so the actual number of attempts is very small (RFC 8628 §5.1). The device_code is not displayed, has no UX constraints, and guessing it gives the attacker the victim's token, so RFC 8628 §5.2 requires very high entropy.

  1. The server receives the input wdjb mjht from the user. How should it be normalized before lookup?
Show answer

Remove all whitespace, hyphens, and punctuation (characters the server added for readability), then uppercase everything, giving WDJBMJHT. RFC 8628 §6.1 recommends that the server strip punctuation and uppercase input when using the A-Z charset. The storage key should also be in normalized form.

  1. Name 3 pieces of information on the consent screen that help the user detect a device flow request they did not start.
Show answer

(1) The IP/location of the device that started the request: very different from the user's location is a red flag. (2) The time of initiation: a code created long before the user opened the page is suspicious. (3) The code shown again so the user can compare it with the code in their own terminal. Plus the warning "only continue if you just ran the command yourself". RFC 8628 §5.4 recommends displaying device information.

  1. Why does verification_uri_complete increase phishing risk, and how does the RFC suggest mitigating it?
Show answer

With the code embedded in the URL, the user does not need to type the code, so they are more likely to approve reflexively when they receive a link from someone else. RFC 8628 §5.4 says confirming that the device is in the user's possession is "particularly important" in this case, and suggests displaying the code during the flow and asking the user to check that it is the one shown on the device they are setting up.

Hands-on Exercises

Exercise 1: Observe a real CLI

Pick a CLI you have access to (gh, aws, az). Run the login command in device code mode (gh auth login, aws sso login --use-device-code, az login --use-device-code). Record each output line and map it to the table in section 3.

Expected output: a 2-column table "output line → RFC 8628 step", noting the interval and expiry time if the CLI prints them. Do not copy real tokens or codes into shared documents.

Exercise 2: Decision table for your product

For a hypothetical CLI at your company, fill in a table: user groups, share of SSH/container use, IdP in use, MFA/SSO requirements, whether there is CI. From that, choose a default flow and a fallback flow.

Expected output: a decision diagram like section 5 for your product, with 3-5 lines of reasoning.

Exercise 3: Call device flow with curl

With a test IdP that has device flow enabled (e.g. a test GitHub OAuth app with Device Flow enabled, or Keycloak running locally), call POST /device/code and poll POST /token with curl. Deliberately poll faster than interval to see slow_down.

Expected output: a time-ordered log of responses (containing no real tokens), showing when you received authorization_pending, slow_down, and the token. Note the new interval after slow_down.

Exercise 4: Write a polling state table

Write a CLI-side state machine table: states (waiting, backing_off, done, denied, expired, failed), events (each response type, timeout, Ctrl+C), actions, and next states.

Expected output: a 6 states × 7 events table, every cell filled, consistent with section 5.

Exercise 5: Probability spreadsheet

Write a spreadsheet (or script) that takes: the charset, code length, number of active codes, rate limits per IP and per account, and the number of IPs/accounts the attacker has. Output the probability of guessing at least one code within the expires_in window.

Expected output: a comparison of 3 configurations (8 base-20 characters, 9 digits, 6 digits) under the same assumptions, with a conclusion on which configuration meets your acceptable probability threshold.

Draw wireframes of two screens for DevCLI: code entry and consent. Mark which recommendation from sections 5-7 each component corresponds to.

Expected output: 2 wireframes (ASCII or a drawing tool), each component annotated with its rationale, including the "invalid or expired code" error state.

References


Next lesson →