devHọc Dev

Week 1 - Day 2: Loopback + PKCE, storing tokens on developer machines, and device code phishing

Week 1 – Day 2

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.1 is recommended over localhost
  • 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) and whoami correctly
  • 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 tokens

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

RuleLevelWhat it means for a CLI
Use an external browser (external user-agent), not an embedded webviewNative 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 clientsMUST (§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.3No 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 URIsMUST (§7.3)The CLI picks a random port, the IdP does not require registering each port
Using localhost instead of an IP literalNOT 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 interfaceshould (§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:

  1. Avoid accidentally listening on another interface. localhost is 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.
  2. 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 (never 0.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):

ParameterProtects againstIn the CLI
code_verifier / code_challenge (S256)Another app on the machine intercepts the code and exchanges it for a tokencode_verifier lives only in the CLI process memory
stateCSRF: someone fires a fake callback at the open portCompare 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 state before reading code or error; a request with the wrong state gets 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.1 of the SSH server, which the browser on the laptop cannot reach. This is when you must use the device flow.
  • spawn with an argument array, never string concatenation into a shell, so the URL cannot be interpreted as a command. On Windows use rundll32 url.dll,FileProtocolHandler: cmd /c start still 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. spawn reports ENOENT (missing xdg-open) through the asynchronous 'error' event, which try/catch cannot catch; without a handler the process crashes.

Checks on the IdP side before enabling loopback

QuestionIf "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

ScenarioDoes loopback work?Reason
Laptop with a browserYesIdeal case
SSH into a server, browser on the laptopNoRedirect goes to the server's 127.0.0.1; the laptop browser cannot reach it (unless you port forward manually)
Devcontainer / DockerUsually notThe port inside the container is not mapped to the host
WSLDepends on configurationCan open the Windows browser, but loopback between WSL and Windows depends on the networking mode
CI runnerNot applicableNo 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

CriterionLoopback + PKCEDevice flow
ExperienceOne click, no code to typeMust transfer a code to the browser
Needs a browser on the same machineYesNo
SSH / containerPoorGood
Load on the AS1 code exchange requestContinuous polling
Main riskAnother app intercepts the code (mitigated by PKCE), port already takenRemote phishing with the user_code
IdP requirementAllow loopback redirect with any portEnable 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:

ScenarioBrowser page showsTerminal 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 code or tokens, and does not load external resources (to avoid leaking the URL via Referer).
  • You can redirect the result page to a static product page (for example https://example.com/cli/success) to remove the code from the address bar.
  • Exit code: 0 on success, non-zero on failure, so scripts calling devcli login know 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:

SourceExample
File readable by every user on the machineAuth file created with the default 0644 permissions
Home directory backup/syncConfiguration directory synced to a personal cloud drive
Public dotfilesDeveloper accidentally commits the configuration directory to GitHub
Infostealer malwareScans common CLI configuration paths
Logs/terminalCLI 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

┌────────────────────────────────────────────────────────────┐│OptionA:OScredentialstore││macOS:Keychain││Windows:CredentialManager││Linux:SecretService(gnome-keyring,KWallet...)││+Encryptedatrest,tiedtotheOSloginsession││-Notavailableonheadlessservers,containers,CI│├────────────────────────────────────────────────────────────┤│OptionB:Fileintheconfigurationdirectory││~/.config/devcli/auth.json(Linux,macOS)││%APPDATA%\devcli\auth.json(Windows)││+Workseverywhere││-Plaintext;protectedonlyby0600filepermissions│└────────────────────────────────────────────────────────────┘

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:

  1. Try the credential store via the @napi-rs/keyring library (Node binding for the Rust keyring crate; Atom's keytar has been archived since 12/2022 and should not be used for new projects).
  2. If there is no store: write a file with 0600 permissions (owner read/write only), directory 0700, and print a warning once.
  3. A --insecure-storage flag 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

PlatformPreferred storeWhen to fall back to a file
macOS desktopKeychainAlmost never
WindowsCredential 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 ServiceNo Secret Service daemon running
Linux server over SSHUsually no Secret ServiceAlmost always use a 0600 file
Devcontainer / DockerNoneAlways use a file; mount the configuration directory to keep the login
WSLDepends on the distroUsually 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 relative expires_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 with Date.now() on every run. This is also the StoredAuth/AuthFile schema in the Day 3, Part 2 code.
  • Store the verified identity (userId, email) so whoami does not need a network call, but whoami --verify should call the API to make sure the token is still valid.
  • Store issuer and team/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). accessToken is optional. When using the credential store (service devcli, 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 --debug mode. 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.

┌──────────────────────────────────────────────────────────┐│Refreshtokenrotation││││CLIsendsrefresh_tokenR1──▶ASreturnsaccessA2││andaNEWrefreshR2││R1isinvalidated││││Ifsomeone(athieforanotherprocess)reusesR1:││ASdetects"reuse"──▶revokesthewholechainR1,R2,A2││──▶everypartymustloginagain│└──────────────────────────────────────────────────────────┘

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 devcli processes 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_token or refresh_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:

PrioritySourceUsed when
1--token flagTrying one command with a different token (careful: ends up in shell history)
2DEVCLI_TOKEN environment variableCI, scripts
3Profile selected with --profileMultiple accounts, chosen per command
4Profile selected with the DEVCLI_PROFILE variableMultiple accounts, chosen per shell
5default profileDaily use

Team chain:

PrioritySource
1--team flag
2DEVCLI_TEAM environment variable
3Project link file .devcli/project.json in the current directory
4Default team of the active profile

Safety rules:

  • When using a token from an environment variable, whoami must say clearly "source: DEVCLI_TOKEN". A lot of debugging time is wasted just because an old environment variable is still lingering in the shell.
  • logout must 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.

ScenarioCorrect behavior
New CLI reads an old-version fileConvert to the new format, write atomically (write a temp file then rename), keep 0600 permissions
Old CLI reads a new-version fileReport "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 storeWrite 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_token

Why 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_code has 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:

AspectPublished content
TimeframeActive since around August 2024
AssessmentMicrosoft assesses with medium confidence that the group aligns with Russian state interests
TargetsGovernments, NGOs, and many industries across multiple regions
LureImpersonating 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 tokensAccess to email, cloud storage... without a password; use proxies matching the victim's geography to hide anomalous sign-in signals
Update 14/02/2025The 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/2026Microsoft 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

MeasureEffectNotes for DevCLI
Only allowed clients can use the device grantThe 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 flowA phished token has few permissionsdevcli does not request billing/IAM admin permissions via the device flow
Short expires_inCodes sent via email/chat lose value quickly (RFC 8628 §5.4)600 seconds
Information-rich consent screenThe 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 alertsDetect an ongoing campaignMany codes approved by different accounts but initiated from the same IP/ASN
Per-organization policyEnterprise customers disable the device flow if they do not use it"Disable device login" option in the admin console
Fast revocationReduces how long the attacker keeps accessA "Sessions" page listing each CLI session, each revocable individually
Complete loggingPost-incident investigationLog 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

StrategyWhen it fitsTrade-off
Block the device flow entirelyThe organization has no device/CLI that needs the device flowDevelopers on SSH/containers must use other methods (port forwarding for loopback, machine tokens)
Allow per client and user groupOnly some CLIs/devices need it (for example DevCLI for the engineering group)Must manage an exception list, audit periodically
Allow everythingPersonal products, low riskLargest 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 on example.com/device if 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_code to 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:

RiskDescriptionMitigation
Another app intercepts the codeRFC 8252 §8.1: on some OSes, another app can listen on the same loopbackPKCE (mandatory)
Fake callback (CSRF)A web page sends a request to http://127.0.0.1:{port}/callback with the attacker's codeRandom state, checked before processing
Port already takenOther software has already bound the fixed port the CLI wantsUse a random port (port 0)
Listening on the wrong interfaceBinding 0.0.0.0 lets other machines on the network send requestsBind 127.0.0.1 (RFC 8252 §8.3)
DNS rebindingA 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 responseRedirect 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 longExtended attack windowOpen the port at start, close as soon as a response arrives or on timeout
Opening the URL through a shellThe 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 separatorspawn 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.

┌──────────────────────────────────────────────────────────┐│Damage-limitationlayers││││1.Short-livedaccesstokens(5-60minutes)││2.Refreshtokenrotation+reusedetection(Part2)││→thiefandrealCLIsharethechain→detected││3.MinimalscopefortheCLI││4.Sender-constraining(DPoP)iftheASsupportsit││5.Newsign-innotification(email"newCLIsession")││6.Sessionmanagementpage+per-sessionrevocation││7.Dangerousoperationsrequirere-auth(step-up)│└──────────────────────────────────────────────────────────┘

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

  1. Is the CLI registered as a public client, with no embedded secret?
  2. Does loopback use PKCE S256 + state, bind 127.0.0.1, and a random port?
  3. Is the device grant enabled only for clients that need it, with a narrow scope?
  4. Is the device code expires_in short enough (a few minutes to 15 minutes)?
  5. Does the consent page show the application, permissions, IP/location, and time of initiation?
  6. Is user_code entry rate-limited per account and IP?
  7. Are tokens stored in the credential store, with a 0600 file fallback?
  8. Do refresh tokens use rotation or sender-constraining (RFC 9700 §2.2.2)?
  9. Does logout call revoke (RFC 7009) before deleting locally?
  10. Is there a session management page, enough logging to investigate, and an option to disable the device flow per organization?

8. Common design mistakes

MistakeWhy it is dangerousCorrect approach
Enabling the device grant for every client by defaultThe attacker picks the client with the most permissions for the lureEnable only for clients that need it, narrow scope
Consent screen with only a "Continue" buttonThe user has no information to be suspiciousShow the application, permissions, IP/location, time of initiation
expires_in of 30-60 minutes for an internal CLIA code sent by email stays usable for a long time5-15 minutes
Not logging the initiating IPCannot trace the source of a campaignLog the IP, ASN, user agent of the /device/code request
No way to revoke a single CLI sessionYou have to force a password change and revoke everythingSession management page, per-session revocation
Verification page distinguishes "wrong code" from "expired code"Helps an attacker probing codes learn which codes existedOne generic message

9. Runbook for suspected device code phishing

When the system detects (or a user reports) an anomalously approved DevCLI session:

StepActionOwner
1Identify the session: client_id, user, initiating IP, approving IP, time, scopeOn-call
2Revoke the refresh token and access token of that session (if the AS supports access token revocation)On-call
3Force the user to re-authenticate on the next accessOn-call
4Look for other sessions initiated from the same IP/ASN in the last 7-14 daysSecurity
5Review audit logs: which APIs the attacker called with that tokenSecurity
6Contact the user: confirm whether they ran the command, where they got the codeSecurity
7If it is a campaign: temporarily disable the device flow for the targeted organization, strengthen warnings on the consent screenProduct + Security
8Write a postmortem, update detection rulesSecurity

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

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

  2. Why does RFC 8252 recommend http://127.0.0.1:{port} instead of http://localhost:{port}?

    Show answer

    RFC 8252 §8.3 classifies localhost as 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 resolves localhost to ::1 while the server only binds 127.0.0.1.

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

  4. 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_verifier that matches the code_challenge sent at authorize time. The code_verifier lives only in the CLI process memory; the other app does not have it, so it cannot exchange the code. RFC 8252 §6 makes PKCE mandatory for public native apps precisely because of this redirect interception risk (§8.1).

  5. 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.1 of the SSH server. After login, the IdP redirects the laptop browser to http://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).

  6. 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 login docs.

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

  8. The CLI calls /revoke with 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.

  9. Why should you store expiresAt as an absolute point in time instead of keeping the expires_in from the token response?

    Show answer

    expires_in is 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 when expires_in started 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.

  10. A developer runs devcli logout but subsequent commands still work with the old permissions. Give the most common cause and how whoami helps 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.

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

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

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

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

  1. A malicious web page sends GET http://127.0.0.1:53682/callback?code=ATTACKER_CODE while 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


Next lesson →