This lesson combines 3 topics: Loopback redirect + PKCE (RFC 8252), Storing tokens on the developer machine, Security: device code phishing and the risks of CLI auth.
Learning Objectives
- Understand how a CLI receives an authorization code through a temporary web server on
127.0.0.1 - Know the RFC 8252 rules: external browser, loopback IP literal, any port, mandatory PKCE
- Explain why
127.0.0.1is recommended overlocalhost - Implement a minimal loopback flow in Node/TypeScript
- Know when the CLI must switch to the device flow on its own
- Choose where to store tokens: the OS credential store or a permission-restricted configuration file
- Design the login data structure: token, refresh token, expiry time, identity, scope/team
- Understand the RFC 9700 requirements for refresh tokens issued to public clients
- Design
logout(RFC 7009 revocation + local deletion) andwhoamicorrectly - Define the precedence between tokens from environment variables, command-line flags, and the login file
- Understand how device code phishing works and why MFA does not stop it
- Analyze a real campaign published by Microsoft (Storm-2372, 2024-2025)
- Design mitigations on the authorization server, the CLI, and the organization side
- Identify the risks specific to the loopback flow
- Apply damage-limitation principles when a token on a developer machine is stolen
Part 1: Loopback redirect + PKCE (RFC 8252)
1. The idea: turn the CLI into a "web app" for a few seconds
Authorization Code needs a redirect_uri for the IdP to send the code back to. A CLI has no domain, but it can open a port on the machine itself and listen there:
sequenceDiagram
participant U as User
participant C as devcli (temporary HTTP server)
participant B as Browser
participant AS as auth.example.com
Note over C: 1. open port 127.0.0.1:53682 (random)
C->>B: 2. open browser: https://auth.example.com/authorize?<br/>redirect_uri=http://127.0.0.1:53682/callback<br/>&code_challenge=...&state=...
B->>AS: GET /authorize
U->>B: 3-4. user signs in + consents in the browser
AS-->>B: 302 to redirect_uri (code, state)
B->>C: 5. GET /callback?code=...&state=...<br/>(browser redirects to the local machine)
C->>AS: 6. POST /token (code + code_verifier)
AS-->>C: access_token, refresh_token
Note over C: 7. close port, store tokensCompared with the device flow: no code to type, no polling, instant response. The trade-off is that you need a browser on the same machine as the CLI.
2. Key rules of RFC 8252
RFC 8252 "OAuth 2.0 for Native Apps" (BCP 212) is the standard for apps running on the user's machine, including CLIs.
| Rule | Level | What it means for a CLI |
|---|---|---|
| Use an external browser (external user-agent), not an embedded webview | Native apps MUST NOT use an embedded user-agent (§8.12) | The CLI opens the default browser, it does not render the login page itself |
| Public native apps MUST implement PKCE; the AS MUST support PKCE for these clients | MUST (§6) | code_challenge S256 is mandatory |
Loopback redirects use the http scheme and an IP literal: http://127.0.0.1:{port}/{path} or http://[::1]:{port}/{path} | §7.3 | No TLS needed because the request never leaves the machine (§8.3) |
| The AS MUST allow any port specified at request time for loopback IP redirect URIs | MUST (§7.3) | The CLI picks a random port, the IdP does not require registering each port |
Using localhost instead of an IP literal | NOT RECOMMENDED (§8.3) | See section 3 |
| Open the port only when starting the request and close it right after receiving the response; listen only on the loopback interface | should (§8.3) | Temporary server, lives a few dozen seconds |
Why embedded webviews are forbidden (§8.12): an app hosting a webview can read every key the user types (including the password), auto-submit forms to bypass consent, and copy session cookies. A webview also lacks an address bar for the user to check the domain. With an external browser, the CLI cannot touch the user's credentials, and the user benefits from an already signed-in SSO session.
3. 127.0.0.1 instead of localhost
RFC 8252 §8.3 gives two reasons:
- Avoid accidentally listening on another interface.
localhostis resolved through machine configuration; it may resolve to::1,127.0.0.1, or, on a misconfigured machine, some other address. Binding to an IP literal guarantees you listen only on loopback. - Less affected by client-side firewalls and misconfigured name resolution.
One more practical reason: if the CLI server binds 127.0.0.1 but the redirect URI uses localhost, the browser may resolve it to ::1 (IPv6) and fail to connect. Using the same IP literal in both places removes this bug.
In practice: some IdPs only accept redirect URIs registered as
http://localhost. In that case still bind the server to loopback (never0.0.0.0) and test IPv4/IPv6 carefully.
4. PKCE and state in the loopback flow
A recap (details in the Login Flow Design course, Week 1 Day 3, Part 2 PKCE, state, nonce):
| Parameter | Protects against | In the CLI |
|---|---|---|
code_verifier / code_challenge (S256) | Another app on the machine intercepts the code and exchanges it for a token | code_verifier lives only in the CLI process memory |
state | CSRF: someone fires a fake callback at the open port | Compare state before handling code |
RFC 8252 §8.1 notes that a loopback redirect can be intercepted on some operating systems by another app on the same machine listening on loopback. PKCE is the main protection: the other app has the code but not the code_verifier, so it cannot exchange it for a token.
5. Minimal implementation (Node 22+, TypeScript)
import http from 'node:http';
import { randomBytes, createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
import type { AddressInfo } from 'node:net';
const AUTH = 'https://auth.example.com';
const CLIENT_ID = 'devcli';
const b64url = (b: Buffer) => b.toString('base64url');
function openBrowser(url: string): void {
// Windows: do NOT use `cmd /c start` because cmd.exe is a shell and treats `&` in the URL as a command separator.
const [bin, args] =
process.platform === 'darwin' ? ['open', [url]] :
process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]] :
['xdg-open', [url]];
// spawn does not throw synchronously when the binary is missing (ENOENT); the error arrives via the 'error' event.
const child = spawn(bin as string, args as string[], { stdio: 'ignore', detached: true });
child.on('error', () => { /* URL was already printed, the user opens it manually */ });
child.unref();
}
export async function loopbackLogin(scope: string) {
const verifier = b64url(randomBytes(32));
const challenge = b64url(createHash('sha256').update(verifier).digest());
const state = b64url(randomBytes(16));
const server = http.createServer();
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r)); // port 0 = OS picks a free port
const { port } = server.address() as AddressInfo;
const redirectUri = `http://127.0.0.1:${port}/callback`;
const authUrl = new URL(`${AUTH}/authorize`);
authUrl.search = new URLSearchParams({
response_type: 'code', client_id: CLIENT_ID, redirect_uri: redirectUri,
scope, state, code_challenge: challenge, code_challenge_method: 'S256',
}).toString();
const code = await new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Timed out waiting for login')), 5 * 60_000);
server.on('request', (req, res) => {
const url = new URL(req.url ?? '/', redirectUri);
if (url.pathname !== '/callback') { res.writeHead(404).end(); return; }
const err = url.searchParams.get('error');
if (url.searchParams.get('state') !== state) {
res.writeHead(400).end('State mismatch.'); return; // ignore, keep waiting for a valid callback
}
clearTimeout(timer);
if (err) { res.writeHead(400).end('Login was denied.'); reject(new Error(err)); return; }
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
.end('<p>Login successful. You can close this tab.</p>');
resolve(url.searchParams.get('code') ?? '');
});
console.log(`Open the following URL in your browser (trying to open it automatically):\n${authUrl}`); // always print first
openBrowser(authUrl.toString());
}).finally(() => server.close());
const res = await fetch(`${AUTH}/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code', code, redirect_uri: redirectUri,
client_id: CLIENT_ID, code_verifier: verifier,
}),
});
if (!res.ok) throw new Error(`Code exchange failed: ${res.status}`);
return res.json(); // { access_token, refresh_token?, expires_in, ... }
}
Points to note in the code:
server.listen(0, '127.0.0.1'): the port is assigned by the OS, and the server listens only on loopback.- Check
statebefore readingcodeorerror; a request with the wrongstategets a 400 but does not break the session. - There is an overall timeout (5 minutes) and
server.close()always runs. - If the browser cannot be opened, print the URL so the user can open it. But over SSH, the URL redirects to
127.0.0.1of the SSH server, which the browser on the laptop cannot reach. This is when you must use the device flow. spawnwith an argument array, never string concatenation into a shell, so the URL cannot be interpreted as a command. On Windows userundll32 url.dll,FileProtocolHandler:cmd /c startstill goes through a shell (cmd.exe), and an&in the URL cuts the URL and the rest runs as a command.- Always print the URL first, then try to open it.
spawnreports ENOENT (missingxdg-open) through the asynchronous'error'event, whichtry/catchcannot catch; without a handler the process crashes.
Checks on the IdP side before enabling loopback
| Question | If "no" |
|---|---|
| Is the client registered as public, without a secret? | The CLI would have to embed a secret: unacceptable |
Is the redirect http://127.0.0.1/callback accepted with any port? | You must use a fixed, pre-registered port range, prone to conflicts |
| Is PKCE S256 enforced for this client? | Another app that intercepts the code can exchange it for a token |
| Are embedded webviews blocked / is the system browser required? | Does not affect the CLI, but worth knowing when building desktop apps |
6. When to switch to the device flow
| Scenario | Does loopback work? | Reason |
|---|---|---|
| Laptop with a browser | Yes | Ideal case |
| SSH into a server, browser on the laptop | No | Redirect goes to the server's 127.0.0.1; the laptop browser cannot reach it (unless you port forward manually) |
| Devcontainer / Docker | Usually not | The port inside the container is not mapped to the host |
| WSL | Depends on configuration | Can open the Windows browser, but loopback between WSL and Windows depends on the networking mode |
| CI runner | Not applicable | No human; use machine tokens (Day 4, Part 1) |
This is also why major CLIs have a switch flag: AWS CLI uses PKCE by default since v2.22.0 and has --use-device-code; Azure CLI automatically falls back to device code when it cannot open a browser and also has --use-device-code.
7. Summary comparison
| Criterion | Loopback + PKCE | Device flow |
|---|---|---|
| Experience | One click, no code to type | Must transfer a code to the browser |
| Needs a browser on the same machine | Yes | No |
| SSH / container | Poor | Good |
| Load on the AS | 1 code exchange request | Continuous polling |
| Main risk | Another app intercepts the code (mitigated by PKCE), port already taken | Remote phishing with the user_code |
| IdP requirement | Allow loopback redirect with any port | Enable the device authorization grant |
8. The result page and the error experience
After the browser redirects to 127.0.0.1, what the user sees is the page returned by the CLI, not by the IdP. A few principles:
| Scenario | Browser page shows | Terminal shows |
|---|---|---|
| Success | "Login successful, you can close this tab" | "✓ Logged in: dev@example.com (profile: default, team: team-platform)" |
| User clicks Deny | "You denied the authorization request" | "Login cancelled" (non-zero exit code) |
state mismatch | "Invalid request" (no detailed explanation) | Keeps waiting for a valid callback |
| Timeout | (the tab may still show the IdP page) | "Timed out, run devcli login again" |
- The result page does not contain the
codeor tokens, and does not load external resources (to avoid leaking the URL viaReferer). - You can redirect the result page to a static product page (for example
https://example.com/cli/success) to remove thecodefrom the address bar. - Exit code: 0 on success, non-zero on failure, so scripts calling
devcli loginknow the outcome.
IPv6 note: if you bind both IPv4 and IPv6 (RFC 8252 §7.3 says clients should try binding both when needed), the redirect URI must match exactly the address used (127.0.0.1 or [::1]).
Part 2: Storing tokens on the developer machine
1. Tokens on a developer machine are high-value
After devcli login, the developer machine holds a refresh token that lives for days, possibly weeks. Whoever gets it has the user's permissions until the token is revoked. Common leak sources:
| Source | Example |
|---|---|
| File readable by every user on the machine | Auth file created with the default 0644 permissions |
| Home directory backup/sync | Configuration directory synced to a personal cloud drive |
| Public dotfiles | Developer accidentally commits the configuration directory to GitHub |
| Infostealer malware | Scans common CLI configuration paths |
| Logs/terminal | CLI prints the token when run with --debug |
So where and how tokens are stored is a design decision, not an implementation detail.
2. Two storage options
A common strategy: prefer the credential store, fall back to a file, and tell the user clearly. Example, GitHub CLI: according to the gh auth login docs, the token is stored in the system credential store; if no store is found or there is an error, gh falls back to a plaintext file. The --insecure-storage flag deliberately stores plaintext. gh auth status tells you where the token is.
Another example: AWS CLI caches IAM Identity Center tokens as JSON files under ~/.aws/sso/cache.
DevCLI's choice:
- Try the credential store via the
@napi-rs/keyringlibrary (Node binding for the Rustkeyringcrate; Atom'skeytarhas been archived since 12/2022 and should not be used for new projects). - If there is no store: write a file with 0600 permissions (owner read/write only), directory 0700, and print a warning once.
- A
--insecure-storageflag for anyone who wants to force file storage.
Linux note: according to the @napi-rs/keyring README, the library tries Secret Service first and then silently falls back to kernel keyutils when Secret Service is not available, without throwing. The kernel keyring may not survive a reboot. So DevCLI pins the store: new Entry('devcli', profile, { linux: { store: 'secret-service' } }) so that a missing Secret Service produces a clear error, and only then falls back to a 0600 file with a warning.
Windows note: Credential Manager limits the blob size to about 2560 bytes. A JSON containing both a JWT access token and a refresh token easily exceeds the limit and the write fails. DevCLI writes the whole record to the store when the JSON is short (threshold 1,200 characters, about 2,400 bytes in UTF-16); above the threshold it drops the access token, keeps only the refresh token plus small metadata, and the next command refreshes (Day 3, Part 2).
Choosing a store per platform
| Platform | Preferred store | When to fall back to a file |
|---|---|---|
| macOS desktop | Keychain | Almost never |
| Windows | Credential Manager (drop the access token when the JSON exceeds ~1,200 characters, due to the ~2560-byte limit) | When writing to the store fails |
| Linux desktop (GNOME, KDE) | Secret Service | No Secret Service daemon running |
| Linux server over SSH | Usually no Secret Service | Almost always use a 0600 file |
| Devcontainer / Docker | None | Always use a file; mount the configuration directory to keep the login |
| WSL | Depends on the distro | Usually a file |
Things not to do:
- Do not store tokens in a shared configuration file with other settings users often share (for example a file with aliases, themes).
- Do not have the CLI put tokens into environment variables (writing to
~/.bashrc,~/.zshrc). - Do not "encrypt" the file with a key hardcoded in the binary: it is only obfuscation, it adds no real security.
- Do not write tokens to log files, even when the user enables verbose mode.
3. Login data structure
{
"version": 1,
"profiles": {
"default": {
"issuer": "https://auth.example.com",
"userId": "usr_xxxxxxxx",
"email": "dev@example.com",
"team": "team-platform",
"scope": "openid offline_access deploy:read",
"refreshToken": "<refresh_token>",
"accessToken": "<access_token>",
"expiresAt": 1792579920000
}
}
}
Principles:
- Store an absolute
expiresAt(a point in time), not the relativeexpires_in. DevCLI stores it as epoch ms (Date.now() + expires_in * 1000; the example above is 2026-10-21T10:52:00Z) and compares it directly withDate.now()on every run. This is also theStoredAuth/AuthFileschema in the Day 3, Part 2 code. - Store the verified identity (
userId,email) sowhoamidoes not need a network call, butwhoami --verifyshould call the API to make sure the token is still valid. - Store
issuerandteam/scope: one developer may have several accounts and several teams (Day 4, Parts 1-2). - The example above is the fallback file format (
~/.config/devcli/auth.json, Windows%APPDATA%\devcli\auth.json, permissions 0600).accessTokenis optional. When using the credential store (servicedevcli, account = profile name): each profile is one JSON record with the same fields; the access token only goes into the store when the JSON has room (threshold 1,200 characters), otherwise it is dropped and the refresh token plus metadata are kept. - Never print token values to logs, even in
--debugmode. If you need to correlate, print only the last 4 characters (…a1b2); do not print a prefix (a JWT prefix is just the header, useless and it builds the habit of printing tokens).
4. Refresh tokens for public clients
RFC 9700 §2.2.2: refresh tokens issued to a public client MUST be sender-constrained (for example DPoP or mTLS) or use refresh token rotation.
Consequences for the CLI:
- Write the new refresh token immediately after refreshing, before doing anything else. Losing this write means the next attempt is treated as reuse.
- Two
devcliprocesses refreshing in parallel will trigger reuse detection. Single-flight is only enough within one process; across processes you need a file lock and must re-read the token after acquiring the lock (Day 4, Part 1).
5. logout done right
A logout that only deletes the local file is not enough: the refresh token is still valid on the server. If it was copied earlier, the thief can still use it.
devcli logout
1. Read the refresh_token of the current profile
2. POST /revoke (RFC 7009)
token=<refresh_token>&token_type_hint=refresh_token&client_id=devcli
3. Regardless of the result of step 2 (network error, 200...), delete
the token from the credential store / file
4. Print: "Logged out dev@example.com from auth.example.com"
If step 2 had a network error: add the warning "The token may not
have been revoked on the server, revoke it in Settings > Sessions"
RFC 7009 details to know:
token_type_hint(OPTIONAL) helps the AS look up faster:access_tokenorrefresh_token.- The AS returns HTTP 200 when revocation succeeds and also when the token is invalid, because the client has no reasonable way to handle that error and the goal (the token is no longer usable) has been achieved.
- If the revoked token is a refresh token and the AS supports access token revocation, the AS SHOULD also invalidate the access tokens from the same authorization grant. If it is an access token, the AS MAY also revoke the refresh token. This propagation behavior depends on the AS policy.
6. whoami: answering "who am I, and where"
Many "I'm logged in but still denied" incidents (case study Day 4, Part 2) come from the user not knowing which account and which team/scope the CLI is using. whoami must show all of it:
$ devcli whoami
User : dev@example.com (usr_xxxxxxxx)
Issuer : https://auth.example.com
Team : team-platform (source: file .devcli/project.json in the current directory)
Profile : default
Token : keychain, expires at 10:52 (48 minutes left)
The team's "source" line matters a lot: the CLI can get the team from a command-line flag, an environment variable, a project link file in the current directory, or the profile default. Stating the source helps the user spot immediately when the CLI is using a team the account has no permission for.
7. Precedence for credentials and team
There are two separate chains: the chain that picks the credential (who you are) and the chain that picks the team (where you are operating). Merging them into one is the root of many confusing bugs (case study Day 4, Part 2). DevCLI follows a model similar to the "credential chain" of many cloud CLIs.
Credential chain:
| Priority | Source | Used when |
|---|---|---|
| 1 | --token flag | Trying one command with a different token (careful: ends up in shell history) |
| 2 | DEVCLI_TOKEN environment variable | CI, scripts |
| 3 | Profile selected with --profile | Multiple accounts, chosen per command |
| 4 | Profile selected with the DEVCLI_PROFILE variable | Multiple accounts, chosen per shell |
| 5 | default profile | Daily use |
Team chain:
| Priority | Source |
|---|---|
| 1 | --team flag |
| 2 | DEVCLI_TEAM environment variable |
| 3 | Project link file .devcli/project.json in the current directory |
| 4 | Default team of the active profile |
Safety rules:
- When using a token from an environment variable,
whoamimust say clearly "source: DEVCLI_TOKEN". A lot of debugging time is wasted just because an old environment variable is still lingering in the shell. logoutmust not silently ignore a token from an environment variable: print the warning "DEVCLI_TOKEN is set, logout does not affect this token".
8. Upgrading the login file format
A CLI lives for years; the auth file format will change. The "version": 1 field in section 3 exists to handle this.
| Scenario | Correct behavior |
|---|---|
| New CLI reads an old-version file | Convert to the new format, write atomically (write a temp file then rename), keep 0600 permissions |
| Old CLI reads a new-version file | Report "the login file was created by a newer version, please upgrade the CLI", do not overwrite |
| Corrupted file (invalid JSON) | Do not silently delete; rename it to auth.json.bak, ask the user to log in again |
| Moving from file to credential store | Write the token to the store, verify it reads back, only then delete the token from the file |
Atomic writes matter more than they look: if the process is killed in the middle of writing a new refresh token (rotation), the file may contain half a JSON. The next run loses the valid refresh token and the user has to log in again.
Part 3: Security: device code phishing and the risks of CLI auth
1. How device code phishing works
The strength of the device flow is "log in on another device". That is also its weakness: the person who initiates the request and the person who approves it can be two different people, and the AS has no way of knowing on its own.
sequenceDiagram
participant K as Attacker (their own machine)
participant AS as Authorization Server (the real IdP page)
participant N as Victim
K->>AS: 1. Calls /device/code with a valid client_id (public CLI)
AS-->>K: user_code ABCD-EFGH + device_code
K->>N: 2. Sends the victim: "Meeting invite, enter code ABCD-EFGH on the official sign-in page"
K->>AS: 3. Starts polling /token with device_code
AS-->>K: 400 authorization_pending
N->>AS: 4. Opens the REAL IdP page
N->>AS: 5. Signs in, passes MFA
N->>AS: 6. Enters ABCD-EFGH, clicks "Continue"
K->>AS: 7. Next poll (POST /token, device_code)
AS-->>K: the VICTIM's access_token + refresh_tokenWhy it is dangerous:
- The victim signs in on the real page, real URL, real certificate. "Check the address bar" skills do not help.
- MFA is still performed and still passes, because the victim performs it. The issued token carries the victim's identity.
- The attacker does not need a fake page and does not need the password.
- The refresh token allows prolonged access long after the
user_codehas expired.
RFC 8628 §5.4 ("Remote Phishing") describes exactly this scenario: the initiating device is in the attacker's hands, and the attacker sends an email instructing the victim to go to the verification URL and enter the code.
2. A real campaign: Storm-2372
On 13/02/2025, Microsoft Threat Intelligence published "Storm-2372 conducts device code phishing campaign". Key points from the post:
| Aspect | Published content |
|---|---|
| Timeframe | Active since around August 2024 |
| Assessment | Microsoft assesses with medium confidence that the group aligns with Russian state interests |
| Targets | Governments, NGOs, and many industries across multiple regions |
| Lure | Impersonating prominent people, building rapport via WhatsApp, Signal, Microsoft Teams; then sending fake Teams meeting invitations by email, which, when clicked, guide the victim to authenticate with an attacker-generated device code |
| After obtaining tokens | Access to email, cloud storage... without a password; use proxies matching the victim's geography to hide anomalous sign-in signals |
| Update 14/02/2025 | The group switched to using the Microsoft Authentication Broker client ID in the device code flow, which lets it obtain a Primary Refresh Token and access organizational resources |
| Update 31/07/2026 | Microsoft further assessed that Storm-2372 is a sub-cluster of Midnight Blizzard focused on initial access |
Microsoft's mitigation recommendations in the post (summary):
- Only allow device code flow where it is truly needed. Microsoft recommends blocking device code flow wherever possible; where needed, configure it via Conditional Access.
- Train users to recognize this technique; the sign-in screen should clearly name the application being signed into and include a "Cancel / Continue" confirmation step.
- When in doubt: revoke the user's refresh tokens (
revokeSignInSessions), consider Conditional Access to force re-authentication, use sign-in risk policies.
The Microsoft Entra Conditional Access docs ("Block authentication flows") also recommend getting as close as possible to blocking device code flow entirely, auditing current usage, and allowing it only in clearly documented cases.
3. Mitigations on the authorization server
| Measure | Effect | Notes for DevCLI |
|---|---|---|
| Only allowed clients can use the device grant | The attacker cannot pick an "attractive" client_id (for example an official app with broad permissions) | Enable the device grant only for devcli, not for the web app |
| Narrow scope for the device flow | A phished token has few permissions | devcli does not request billing/IAM admin permissions via the device flow |
Short expires_in | Codes sent via email/chat lose value quickly (RFC 8628 §5.4) | 600 seconds |
| Information-rich consent screen | The user sees the IP/location and time of initiation (Day 1, Part 3) | Compare the initiating IP with the browser IP; show a prominent warning if the countries differ |
| Anomaly alerts | Detect an ongoing campaign | Many codes approved by different accounts but initiated from the same IP/ASN |
| Per-organization policy | Enterprise customers disable the device flow if they do not use it | "Disable device login" option in the admin console |
| Fast revocation | Reduces how long the attacker keeps access | A "Sessions" page listing each CLI session, each revocable individually |
| Complete logging | Post-incident investigation | Log client_id, initiating IP, approving IP, user, scope, time |
Key point: no single measure removes the risk entirely. RFC 8628 §5.4 acknowledges that short-lived codes do not stop an attacker interacting with the victim in real time. So you need multiple layers.
Three strategies for customer organizations
| Strategy | When it fits | Trade-off |
|---|---|---|
| Block the device flow entirely | The organization has no device/CLI that needs the device flow | Developers on SSH/containers must use other methods (port forwarding for loopback, machine tokens) |
| Allow per client and user group | Only some CLIs/devices need it (for example DevCLI for the engineering group) | Must manage an exception list, audit periodically |
| Allow everything | Personal products, low risk | Largest attack surface, relies entirely on user vigilance |
DevCLI should offer customer admins the second option: "Only allow device code login for group X", plus a report of who used it in the last 30 days.
Sample internal communication message
Warning: device code scam. Bad actors may send you a short code (for example
ABCD-EFGH) along with a meeting invitation or a support request, and ask you to enter it on the official sign-in page. If you do, they get access to your account, even if you use MFA. Only enter a code when you yourself just ran a login command on your own device. If you already entered one, report it to the security team immediately so the session can be revoked.
An effective message has 3 parts: a concrete scenario, a one-sentence rule that is easy to remember, and what to do if you already fell for it.
4. Mitigations on the CLI and user side
On the CLI side:
- Clearly print who is requesting: "You are logging in to DevCLI on machine
build-01. Only enter this code onexample.com/deviceif you yourself just ran the command." - No "send the code to someone else" feature, no printing the code with a share button.
- Default to loopback when a browser is available (Part 1); use the device flow only when needed. Loopback has no
user_codeto be shared. - After a successful login, print the identity received ("✓ Logged in: dev@example.com (profile: default, team: team-platform)"). If the user sees an unfamiliar email, they know something is wrong.
Example output applying the principles above:
$ devcli login --device
Logging in to DevCLI from machine: build-01 (203.0.113.24)
Open https://example.com/device and enter the code: WDJB-MJHT (expires in 10 minutes)
Only enter the code if YOU just ran this command.
Waiting for authentication...
✓ Logged in: dev@example.com (profile: default, team: team-platform)
On the user/organization side, the training message is very short:
Never enter a login code you did not generate yourself. No colleague, IT staff, or partner needs you to enter a device code for them.
5. Risks specific to the loopback flow
Loopback has no user_code phishing scenario, but it has other risks:
| Risk | Description | Mitigation |
|---|---|---|
Another app intercepts the code | RFC 8252 §8.1: on some OSes, another app can listen on the same loopback | PKCE (mandatory) |
| Fake callback (CSRF) | A web page sends a request to http://127.0.0.1:{port}/callback with the attacker's code | Random state, checked before processing |
| Port already taken | Other software has already bound the fixed port the CLI wants | Use a random port (port 0) |
| Listening on the wrong interface | Binding 0.0.0.0 lets other machines on the network send requests | Bind 127.0.0.1 (RFC 8252 §8.3) |
| DNS rebinding | A malicious site makes its domain resolve to 127.0.0.1; the browser treats requests to the loopback server as same-origin with that site and can read the response | Redirect URI uses an IP literal; the server accepts only a Host header equal to 127.0.0.1:{port}, requires state, closes right after the callback |
| Temporary server lives too long | Extended attack window | Open the port at start, close as soon as a response arrives or on timeout |
| Opening the URL through a shell | The URL can inject commands when concatenated into a shell; on Windows, cmd /c start is also a shell and treats & in the URL as a command separator | spawn with an argument array; on Windows use rundll32 url.dll,FileProtocolHandler <url> |
6. When a token on a developer machine is stolen
Worst-case assumption: malware reads DevCLI's auth file. The design goal is damage limitation, not just prevention.
About layer 4: DPoP (RFC 9449, OAuth 2.0 Demonstrating Proof of Possession) binds the token to a key pair held by the client. Each request carries a proof signed with the private key; the AS and the resource server accept the token only with a valid proof. If the private key lives in the credential store (or secure hardware) while the token is copied out of a file, the thief has the token but cannot sign the proof. This is how you satisfy the "sender-constrained" requirement of RFC 9700 §2.2.2 instead of rotation.
Connection to the Login Flow Design course: the step-up authentication idea (Week 2 Day 7, Part 1) applies to CLIs. For example, devcli project delete requires re-authentication through the browser even with a valid token.
7. Quick security checklist for CLI auth
- Is the CLI registered as a public client, with no embedded secret?
- Does loopback use PKCE S256 +
state, bind127.0.0.1, and a random port? - Is the device grant enabled only for clients that need it, with a narrow scope?
- Is the device code
expires_inshort enough (a few minutes to 15 minutes)? - Does the consent page show the application, permissions, IP/location, and time of initiation?
- Is
user_codeentry rate-limited per account and IP? - Are tokens stored in the credential store, with a 0600 file fallback?
- Do refresh tokens use rotation or sender-constraining (RFC 9700 §2.2.2)?
- Does
logoutcall revoke (RFC 7009) before deleting locally? - Is there a session management page, enough logging to investigate, and an option to disable the device flow per organization?
8. Common design mistakes
| Mistake | Why it is dangerous | Correct approach |
|---|---|---|
| Enabling the device grant for every client by default | The attacker picks the client with the most permissions for the lure | Enable only for clients that need it, narrow scope |
| Consent screen with only a "Continue" button | The user has no information to be suspicious | Show the application, permissions, IP/location, time of initiation |
expires_in of 30-60 minutes for an internal CLI | A code sent by email stays usable for a long time | 5-15 minutes |
| Not logging the initiating IP | Cannot trace the source of a campaign | Log the IP, ASN, user agent of the /device/code request |
| No way to revoke a single CLI session | You have to force a password change and revoke everything | Session management page, per-session revocation |
| Verification page distinguishes "wrong code" from "expired code" | Helps an attacker probing codes learn which codes existed | One generic message |
9. Runbook for suspected device code phishing
When the system detects (or a user reports) an anomalously approved DevCLI session:
| Step | Action | Owner |
|---|---|---|
| 1 | Identify the session: client_id, user, initiating IP, approving IP, time, scope | On-call |
| 2 | Revoke the refresh token and access token of that session (if the AS supports access token revocation) | On-call |
| 3 | Force the user to re-authenticate on the next access | On-call |
| 4 | Look for other sessions initiated from the same IP/ASN in the last 7-14 days | Security |
| 5 | Review audit logs: which APIs the attacker called with that token | Security |
| 6 | Contact the user: confirm whether they ran the command, where they got the code | Security |
| 7 | If it is a campaign: temporarily disable the device flow for the targeted organization, strengthen warnings on the consent screen | Product + Security |
| 8 | Write a postmortem, update detection rules | Security |
Steps 2 and 3 should be doable in a single action in the admin tooling; during an incident, every minute the attacker keeps the token is valuable to them.
Review Questions
-
According to RFC 8252, may a CLI display the IdP login page in an embedded webview? Why?
Show answer
No. RFC 8252 §8.12 requires that native apps MUST NOT use an embedded user-agent for authorization requests. An app hosting a webview can record every keystroke (capturing the password), auto-submit forms to bypass consent, and copy session cookies; the user also loses the address bar to verify the domain. An external browser separates the user's credentials from the app and takes advantage of an existing SSO session.
-
Why does RFC 8252 recommend
http://127.0.0.1:{port}instead ofhttp://localhost:{port}?Show answer
RFC 8252 §8.3 classifies
localhostas NOT RECOMMENDED because an IP literal avoids accidentally listening on a non-loopback interface, and is less affected by client-side firewalls or misconfigured name resolution. In practice it also avoids the bug where the browser resolveslocalhostto::1while the server only binds127.0.0.1. -
The CLI picks a random port on every run. How does the IdP accept the redirect URI when the port changes?
Show answer
RFC 8252 §7.3 requires that the authorization server MUST allow any port specified at request time for loopback IP redirect URIs. The client only registers
http://127.0.0.1/callback, and the AS matches every part except the port. This is the only exception to the exact-match rule for redirect URIs. -
A malicious app on the same machine listens for the callback and obtains the
code. Which mechanism prevents it from exchanging it for a token?Show answer
PKCE. The token endpoint requires a
code_verifierthat matches thecode_challengesent at authorize time. Thecode_verifierlives only in the CLI process memory; the other app does not have it, so it cannot exchange thecode. RFC 8252 §6 makes PKCE mandatory for public native apps precisely because of this redirect interception risk (§8.1). -
A developer SSHes into a server and runs
devcli login. Why does the loopback flow fail even though the developer has a browser on the laptop?Show answer
The CLI's temporary server listens on
127.0.0.1of the SSH server. After login, the IdP redirects the laptop browser tohttp://127.0.0.1:{port}/callback, which is the laptop's own loopback, where no server is listening. The callback never reaches the CLI. Fix: use the device flow (or port forward manually, which is complicated for users). -
Why does DevCLI prefer the OS credential store but still need a fallback to a file?
Show answer
Credential stores (Keychain, Credential Manager, Secret Service) encrypt tokens at rest and tie them to the OS login session, which is safer than a plaintext file. But headless servers, containers, and many Linux machines have no Secret Service, so the CLI needs a fallback to a file with 0600 permissions (directory 0700) and a warning to the user. GitHub CLI does the same, per the
gh auth logindocs. -
What does RFC 9700 require of refresh tokens issued to a public client such as a CLI?
Show answer
RFC 9700 §2.2.2: refresh tokens for public clients MUST be sender-constrained (for example DPoP, mTLS) or use refresh token rotation. With rotation, on every refresh the AS returns a new refresh token and invalidates the old one; if the old one is reused, the AS detects the reuse and revokes the whole chain.
-
The CLI calls
/revokewith an expired refresh token. According to RFC 7009, what does the AS return? What should the CLI do next?Show answer
The AS returns HTTP 200: RFC 7009 §2.2 specifies returning 200 even when the token is invalid, because the client cannot handle that error in any reasonable way and the goal of revocation has been achieved. The CLI continues to delete the token from the credential store/file and reports a successful logout.
-
Why should you store
expiresAtas an absolute point in time instead of keeping theexpires_infrom the token response?Show answer
expires_inis the number of seconds from when the AS issued the token, and is meaningful only at the moment the response is received. A CLI is a short-lived process that runs many times; a later run does not know whenexpires_instarted counting. Storing an absolute time (receipt time +expires_in) lets each run compare it with the current clock, minus a safety margin for clock skew. -
A developer runs
devcli logoutbut subsequent commands still work with the old permissions. Give the most common cause and howwhoamihelps detect it.
Show answer
The DEVCLI_TOKEN environment variable is still set in the shell, and by precedence it ranks above the login file, so logout (which only deletes the profile) has no effect. whoami shows the credential source ("source: DEVCLI_TOKEN"), which reveals it immediately. Good design: logout warns when a token environment variable is set.
- Why does MFA not prevent device code phishing?
Show answer
The victim signs in on the real IdP page and performs MFA themselves, so MFA succeeds legitimately. The problem is not identity authentication but the fact that the token is handed to a device initiated by the attacker: the attacker holds the device_code and receives the token when polling. MFA proves "this is the victim", not "the victim is holding the requesting device".
- According to Microsoft's post, what lure did the Storm-2372 campaign use to make victims enter a device code?
Show answer
The attackers impersonated prominent people, built rapport with victims via WhatsApp, Signal, Microsoft Teams, then sent fake Microsoft Teams meeting invitations by email. When the victim clicked the invitation, they were guided to authenticate on the real sign-in page with a device code generated by the attacker.
- What does Microsoft recommend about enabling/disabling device code flow in an organization?
Show answer
Block device code flow wherever possible (get as close as possible to blocking it entirely), audit existing usage, and allow it only in clearly documented and protected cases, configured via Microsoft Entra ID Conditional Access.
- Name 3 authorization server measures that reduce device code phishing risk and briefly explain their effect.
Show answer
(1) Allow only certain clients to use the device grant, with a narrow scope: a phished token has few permissions. (2) Short expires_in: codes sent via email/chat quickly become useless (RFC 8628 §5.4). (3) A consent screen showing the IP/location and time the device initiated the request, compared with the browser location: the user sees the request comes from an unfamiliar place. Also: anomaly detection by initiating IP, a per-organization option to disable the device flow, a session revocation page.
- A malicious web page sends
GET http://127.0.0.1:53682/callback?code=ATTACKER_CODEwhile the CLI is waiting for the callback. Which mechanism prevents the CLI from using this code?
Show answer
The state parameter. The CLI generates a random state at the start and accepts only a callback with a matching state. The malicious page does not know the state, so the callback is rejected. This is CSRF protection on the callback. (PKCE protects against the opposite case: someone else obtaining the user's code.)
Hands-on Exercises
Exercise 1: Run the loopback flow against a test IdP
Use the code from section 5 with a test IdP that supports PKCE and loopback (for example Keycloak running locally, a public client, redirect http://127.0.0.1/*). Try sending a GET /callback?code=x&state=wrong request with curl to the open port.
Expected output: login succeeds and you receive tokens; the fake request with the wrong state gets a 400 and does not break the real login session.
Exercise 2: Detect the environment to pick a flow
Write a function pickFlow(): 'loopback' | 'device' | 'ci-error' for DevCLI based on environment variables and the platform (SSH, container, CI, whether DISPLAY is set).
Expected output: the function plus a test table of 6 cases (macOS laptop, Linux desktop, SSH, devcontainer, GitHub Actions, WSL) with the expected result for each.
Exercise 3: Inventory where the CLIs on your machine store tokens
For 2-3 CLIs you use (gh, aws, az...), find in the official docs where they store tokens and their fallback mode. Check the actual file permissions with ls -l (do not open the file contents).
Expected output: a table "CLI, storage location, uses credential store or not, actual file permissions", with recommendations if any file has permissions broader than 0600.
Exercise 4: Design the logout and whoami commands for DevCLI
Write a spec for the 2 commands following sections 5-7: input, steps, output, error branches (network error during revoke, no profile, DEVCLI_TOKEN in use).
Expected output: a spec as a table of steps, each error branch with a specific message for the user.
Exercise 5: Atomic file writes
Write a writeAuthFile(path, data) function in Node: write to a temp file in the same directory with 0600 permissions, fsync, then rename over the target file. Write a test simulating the process being killed mid-write.
Expected output: the function + a test proving the target file is always valid JSON (old version or new version, never half-written) and the file permissions are 0600 after writing.
Exercise 6: Threat model for the verification page
Apply STRIDE to the example.com/device page and DevCLI's consent screen. For each threat, note the mitigation and whether it is already in the Day 1, Part 3 design.
Expected output: a table of at least 8 rows (threat, STRIDE category, mitigation, status), including device code phishing and user_code brute force.
Exercise 7: Write detection rules
Write 3 anomaly detection rules for DevCLI's device flow logs, each with a condition, threshold, and action (alert, block, require re-authentication).
Expected output: 3 rules written as pseudocode or log queries, with an explanation of which campaign each rule targets.
Exercise 8: Rewrite the CLI message
Rewrite the output of devcli login --device to reduce phishing risk: state the requesting machine, the rule "only enter it if you yourself just ran the command", and the identity received after login.
Expected output: terminal output before and after login (as a code block), no more than 8 lines, with an explanation of which measure in section 4 each line corresponds to.
References
- RFC 8252 — OAuth 2.0 for Native Apps
- RFC 7636 — Proof Key for Code Exchange (PKCE)
- RFC 9700 — OAuth 2.0 Security Best Current Practice
- AWS CLI — Configure IAM Identity Center authentication (PKCE by default since v2.22.0)
- Azure CLI — Sign in interactively
- RFC 7009 — OAuth 2.0 Token Revocation
- RFC 9700 — OAuth 2.0 Security BCP (§2.2.2 Refresh Tokens)
- GitHub CLI — gh auth login (credential store, --insecure-storage)
- AWS CLI — IAM Identity Center token cache
- @napi-rs/keyring
- OWASP Secrets Management Cheat Sheet
- RFC 8628 §5.4 Remote Phishing
- Microsoft Security Blog — Storm-2372 conducts device code phishing campaign (13/02/2025)
- Microsoft Entra — Block authentication flows with Conditional Access policy
- Microsoft Entra — Authentication flows as a condition in Conditional Access
- RFC 8252 §8 Security Considerations
- RFC 9700 — OAuth 2.0 Security BCP
- RFC 9449 — OAuth 2.0 Demonstrating Proof of Possession (DPoP)