This lesson combines 3 topics: Token lifecycle, profiles and CI, Debugging, operations and a real case study, Capstone: spec and threat model for
devcli login.
Learning Objectives
- Refresh the access token at the right time, accounting for clock skew
- Handle races when several
devcliprocesses refresh at once, especially when the server enables refresh token rotation - Design multiple profiles/teams with two separate precedence chains: credential and team
- Explain why CI must not use device flow and should use a machine token or OIDC federation instead
- Write error messages that tell the user which credential the CLI is using
- Systematically diagnose "login succeeded but every command says
Not authorized/forbidden" - Distinguish three layers of causes: CLI version, identity (account), scope (selected team/project)
- Draw CLI design lessons: error messages say clearly what is being used and where it came from
- Set server-side metrics and alerts for device flow: expiry rate, denial rate, poll rate,
slow_down, phishing signals - Write a short runbook for the support team
- Write a complete spec for the DevCLI login feature using the endpoint table format
- Specify the data model, error branches, and a sequence diagram that maps 1-1 to the processing steps
- Build a STRIDE threat model for both device flow and loopback + PKCE
- Use a 10-question checklist to self-review any CLI auth design
- Complete the final course exercise with a clearly defined deliverable
Part 1: Token lifecycle, profiles and CI
1. Token lifecycle on the developer machine
| Parameter | Suggested value for DevCLI | Reason |
|---|---|---|
| Access token TTL | 1 hour | Short damage window if leaked |
| Refresh token TTL | 30 days, sliding on use | Developers don't have to log in again every day |
| Early refresh threshold | Less than 60 seconds left | Compensates for clock skew and network latency |
| Refresh token rotation | On | Detects copied tokens (section 3) |
Clock skew: the expiresAt the CLI stores is computed with the developer machine's clock (Date.now() + expires_in * 1000), so it does not depend on the server clock. Still, a request can reach the server a few seconds late; refreshing 60 seconds early is safe enough.
2. Refresh within one process: single-flight
A single devcli deploy command can fire many API requests in parallel. If each request refreshes on its own when it sees the token about to expire, we get many refreshes at the same time.
// refresh.ts
// One promise per profile: a caller for profile B never receives profile A's token
const inflight = new Map<string, Promise<StoredAuth>>();
export async function getValidAuth(profile: string): Promise<StoredAuth> {
const a = await loadAuth(profile);
if (!a) throw new NotLoggedIn(profile);
if (a.accessToken && a.expiresAt - Date.now() > 60_000) return a;
// Only one refresh per profile within the process; other callers await the same promise
let p = inflight.get(profile);
if (!p) {
p = refresh(profile, a).finally(() => inflight.delete(profile));
inflight.set(profile, p);
}
return p;
}
accessToken may be absent when the store (Windows Credential Manager) cannot hold both tokens (Day 3, Part 2); in that case the first command refreshes.
The trade-off to know: when the JSON exceeds the 1,200-character threshold (the access token is not stored), every new process has to refresh, so with rotation the refresh token rotates on every command. Load on /token goes up and the multi-process race window (section 3) opens more often. Two ways to handle it: cache the (short-lived) access token separately in a 0600 file next to the store, or accept rotating on every command but make an inter-process lock mandatory.
Single-flight solves the problem within one process. But developers often open several terminals: devcli logs -f in one window, devcli deploy in another. The two processes need a shared lock.
3. Multiple processes and refresh token rotation
With rotation, on every refresh the server returns a new refresh token and invalidates the old one. Many servers also enable reuse detection: if an old refresh token is used again, the server treats it as a sign of theft and revokes the whole token family (RFC 9700 describes this mechanism for public clients).
Solution: an inter-process lock around the "read → refresh → write" operation.
// lock.ts
import { mkdir, open, readFile, rm, stat } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { dirname } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
const LOCK_STALE_MS = 30_000;
async function acquire(path: string): Promise<string> {
// A user on the keychain may never have written any file: a missing directory makes open fail with ENOENT, not EEXIST
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
const me = `${process.pid}:${randomUUID()}`; // identity of this lock
const giveUpAt = Date.now() + LOCK_STALE_MS + 10_000; // wait longer than the stale threshold
while (Date.now() < giveUpAt) {
try {
const fh = await open(path, "wx"); // create new; fails if it already exists
await fh.writeFile(me);
await fh.close();
return me;
} catch (e: any) {
if (e.code !== "EEXIST") throw e;
const owner = await readFile(path, "utf8").catch(() => null);
const s = await stat(path).catch(() => null);
if (owner !== null && s && Date.now() - s.mtimeMs > LOCK_STALE_MS) {
// stale lock: re-read right before deleting so we don't delete another process's new lock
if ((await readFile(path, "utf8").catch(() => null)) === owner) await rm(path, { force: true });
}
await sleep(100);
}
}
throw new Error(`Could not acquire lock ${path}`);
}
export async function withFileLock<T>(path: string, fn: () => Promise<T>): Promise<T> {
const me = await acquire(path);
try { return await fn(); }
finally {
// only delete the lock if it is still ours
if ((await readFile(path, "utf8").catch(() => null)) === me) await rm(path, { force: true });
}
}
// refresh.ts (continued): refresh inside the profile's lock
import { join } from "node:path";
import { withFileLock } from "./lock.js";
import { DIR, loadAuth, saveAuth, type StoredAuth } from "./store.js";
const lockPath = (profile: string) => join(DIR, `${encodeURIComponent(profile)}.lock`);
async function refresh(profile: string, old: StoredAuth): Promise<StoredAuth> {
return withFileLock(lockPath(profile), async () => {
// Re-read AFTER acquiring the lock: another process may have just finished refreshing
const cur = (await loadAuth(profile)) ?? old;
if (cur.accessToken && cur.expiresAt - Date.now() > 60_000) return cur;
const t = await postRefresh(cur.refreshToken);
const next: StoredAuth = { ...cur, accessToken: t.access_token,
refreshToken: t.refresh_token ?? cur.refreshToken,
expiresAt: Date.now() + t.expires_in * 1000 };
await saveAuth(profile, next); // the file branch additionally takes auth.json.lock inside
return next;
});
}
There are two kinds of lock, both inside the DIR of store.ts (Day 3, Part 2); acquire creates the directory with 0700 permissions if it does not exist:
<profile>.lock: wraps the whole "read → refresh → write" of one profile, so two processes never send the same refresh token.auth.json.lock:saveAuth(file branch) andclearAuthhold this lock while doing read-modify-write onauth.json. A per-profile lock does not protect the shared file: if profilesdefaultandworkrefresh in parallel, the later write overwrites the earlier one, the other profile's freshly rotated refresh token is lost, and the next refresh triggers reuse detection.
The lock order is always fixed: profile lock first, file lock second (the file lock is held only while writing and never waits for a profile lock), so there is no deadlock.
Two details of the lock: the wait loop (40 seconds) is longer than the stale threshold (30 seconds), so a stale lock is always cleaned up before a process gives up; and each lock records pid:nonce, so only the owner deletes its own lock. The "re-read before deleting" step narrows but does not fully eliminate the race between two processes cleaning up the same stale lock; for absolute rigor, use the operating system's file locks.
The key point is re-reading after acquiring the lock. Without this step, the second process still sends the old refresh token and triggers reuse detection.
| Bug | Symptom | Fix |
|---|---|---|
| No inter-process lock | Occasionally every terminal is logged out at once | File lock as above |
| Lock but no re-read | Same as above, hard to reproduce | Re-read the token inside the lock |
| Server returns a new refresh token but the CLI does not save it | The next refresh uses the old token and gets revoked | Always save the new refresh_token if present |
| Stale lock when a process is killed | Command hangs forever | Check the lock file's age, delete it if too old; wait loop longer than the stale threshold |
| A process deletes a lock that is not its own | Two processes refresh together, triggering reuse detection | Write pid:nonce into the lock, delete only on match |
4. Profiles, teams and two precedence chains
Developers often work with several accounts: personal, company, client. DevCLI supports:
devcli login --profile work
devcli deploy --profile work --team platform
DevCLI splits two different questions into two separate precedence chains (mirroring how the AWS CLI orders precedence: command line options, then environment variables, then configuration files).
Chain 1, credential: "which token to use?"
| Priority | Source | Example |
|---|---|---|
| 1 | Command line flag | --token <token> |
| 2 | Environment variable | DEVCLI_TOKEN |
| 3 | Token of the selected profile | profile chosen by --profile > env DEVCLI_PROFILE > default; token taken from keychain devcli/<profile> or the fallback file |
Chain 2, team: "which team to operate on?"
| Priority | Source | Example |
|---|---|---|
| 1 | Command line flag | --team team-platform |
| 2 | Environment variable | DEVCLI_TEAM |
| 3 | Project directory link file | .devcli/project.json containing teamId, projectId |
| 4 | Profile's default team | team field saved at login |
The project link file does not contain credentials; it only selects the team. Mixing the two chains into one table is the source of a lot of confusion when debugging.
Two principles from these two tables:
- Environment variables beat files, so a stale
DEVCLI_TOKENin.zshrccan silently override the token you just logged in with.whoamimust print the source clearly:token: env DEVCLI_TOKEN. - The project link file selects the team on its own, so the same command can work in one directory and be denied in another. On a
403, the error message must say where the team came from (Part 2 analyzes a real incident of this kind).
$ devcli whoami
user dev@example.com
profile work (from --profile)
team team-platform (from ./.devcli/project.json)
token keychain devcli/work, expires in 41 minutes
5. CI and non-interactive environments
Device flow needs a real person to click approve. In CI nobody does that, and if someone approves a code printed in the CI log, that is exactly the phishing scenario. The right choices:
| Approach | Description | When to use |
|---|---|---|
| Machine token (machine token / service account) | Long-lived token created on the dashboard, narrow scope, stored in the CI secret store | CI system does not support OIDC |
| OIDC federation | CI issues a short-lived JWT per job; the IdP/cloud trusts the CI issuer and exchanges the JWT for a short-lived token | GitHub Actions, GitLab CI, and other CIs with OIDC |
| Workload identity | Running on cloud, use the machine/pod identity | Jobs running in cloud infrastructure |
Example of GitHub Actions requesting an OIDC token for a job:
permissions:
id-token: write # allow the job to request an OIDC JWT
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: devcli deploy --oidc
On the ACME side, /token supports exchanging a GitHub JWT for a DevCLI access token (the token exchange model, RFC 8693), accepting it only when iss is https://token.actions.githubusercontent.com and the sub/repository claims match a registered repository. No long-lived secret lives in the repository or in CI.
The CLI needs a clear rule: CI=true without DEVCLI_TOKEN or --oidc fails immediately and never starts device flow.
6. Per-command scope
Not every command needs write permission. Two approaches:
| Approach | Pros | Cons |
|---|---|---|
| One broad-scope token at login | Simple, log in once | A leaked token leaks every permission |
| Log in with minimal scope, request more when needed (step-up) | Least privilege | One extra approval when running sensitive commands |
DevCLI's choice: devcli login requests openid offline_access deploy:read by default. If the token lacks deploy:write, devcli deploy --prod explains why and then reruns the login (loopback, or --device when headless) with the expanded scope openid offline_access deploy:read deploy:write. This pattern is similar to step-up authentication in the Login Flow Design course.
7. Common mistakes in the token lifecycle
| Mistake | Consequence | Right way |
|---|---|---|
Refresh exactly at expiresAt | The request reaches the server after the token expired, gets 401, and only then refreshes | Refresh about 60 seconds early |
Retry forever when refresh gets invalid_grant | CLI hangs or spams the server | invalid_grant is a terminal error: delete the credential, require login |
Not saving the new refresh_token returned | The next refresh uses an invalidated token | Always overwrite if the response contains refresh_token |
| Sharing one profile across several accounts | Logging in to one account overwrites the other | One profile per account, whoami prints the profile |
| Enabling device flow in CI "for convenience" | Job hangs, code leaks in the log | Block when CI=true, use OIDC or a machine token |
Part 2: Debugging, operations and a real case study
1. Case study: "logged in but still Not authorized"
The story below is based on a real incident, anonymized and moved into a DevCLI setting.
A developer needs to deploy a new version of an internal project. The developer runs:
$ devcli whoami
Error: Not authorized
Thinking the session expired, the developer runs devcli login. The browser opens, the developer clicks approve, and the CLI prints:
✓ Logged in: an.personal@example.com (profile: default, team: team-mobile)
This line already contains a clue (the account's default team is team-mobile), but the developer does not notice.
Running devcli whoami again in the project directory: still Error: Not authorized. The developer logs out and logs in once more: exactly the same result.
The decisive clue is at t5: the same token works when run outside the project directory. The problem is not the login.
2. Three layers of causes
| Layer | Question | In the case study |
|---|---|---|
| 1. CLI version | Is the CLI new enough to understand the current token/flow and print clear errors? | The CLI was many versions behind; the new version additionally prints the hint "Check that the selected team is correct" |
| 2. Identity | Which account does the token belong to? | The browser was already logged in to the personal account, so the first approval issued a token for the personal account |
| 3. Scope | Which team/project is the CLI sending requests with, and where does it come from? | The project directory has a link file pointing to a project owned by a team of another account (the work account). The CLI picked that team automatically, and the server returned forbidden |
Layer 3 explains why whoami fails inside the project directory but succeeds outside: outside the directory, the CLI uses the account's default team, so the request is valid.
The request path:
3. Diagnostic procedure
| Step | Command/action | Conclusion |
|---|---|---|
| 1 | Check the CLI version, try the latest version (e.g. npx <cli>@latest whoami) without overwriting the install | New versions usually print structured errors with reason and hint |
| 2 | Run whoami inside and outside the project directory | Different results ⇒ suspect the project link file |
| 3 | List the teams the current account can see | The team in the link file is not in the list ⇒ wrong account or not invited yet |
| 4 | Open the link file (.devcli/project.json), look at teamId/projectId (not secrets) | You know exactly which scope the CLI is sending |
| 5 | Check the relevant environment variables without printing values ([ -n "${DEVCLI_TOKEN:+set}" ]) | Rules out a stale token in env overriding |
| 6 | Check which account is logged in in the browser before approving | Avoids issuing a token to the wrong account again |
| 7 | logout, login again and choose the right account on the approval page | A token for the account that has access to that team |
In the case study, step 7 fixed the problem: after logging in with the work account, whoami in the project directory printed the right username, and the deploy worked.
Safety note when debugging: do not use commands that print every environment variable or cat a file containing tokens. Only check whether it exists, or read the key names of the JSON file, not the values.
4. Design lessons for the CLI
Most of the time lost in the case study was due to the overly poor Not authorized error message. Compare:
Bad:
Error: Not authorized
Good:
Error: forbidden (403)
You are logged in as an.personal@example.com
Selected team team-platform (from ./.devcli/project.json)
This account is not a member of team-platform.
Try: devcli teams ls
devcli login (choose the right account in the browser)
devcli link (re-link the project to your team)
| Principle | Application |
|---|---|
| State the identity in use | Print email/username in 401/403 errors |
| State the scope and its source | "team-platform (from ./.devcli/project.json)" |
| Distinguish 401 from 403 | 401: token wrong/expired ⇒ suggest login. 403: token valid but no permission ⇒ suggest checking team/account, do not blindly tell the user to log in again |
| Have a machine-readable mode | --output json with reason, hint, retryable so scripts and AI agents can handle it |
whoami does not depend on project scope | This command must work anywhere to answer "who am I" |
| The approval page shows the account about to receive the token | "You are authorizing DevCLI with account an.personal@… — Switch account" |
The last point is on the server side: the consent page from Day 3, Part 1 should clearly show the logged-in account and have a switch-account button, because the browser often holds a session different from the one the user thinks.
5. Server-side operations: metrics and alerts
| Signal | Interpretation | Action |
|---|---|---|
codes_expired / codes_issued spikes | Approval page UX problem, or a new CLI version prints the wrong URL | Check the latest CLI release, test the flow end-to-end |
High slow_down_rate for one CLI version | Client polls at the wrong pace or resets the interval | Report a bug to the CLI team, keep the rate limit |
user_code_failures rising from a few IPs | Someone is guessing codes | Tighten rate limits, temporarily block the IPs |
| Many sessions created from one unusual IP/ASN, approved by many different users | Sign of device code phishing (Day 2, Part 3) | Security alert, revoke related tokens, consider blocking device flow for that user group |
| Session approved but the creating IP and the browser IP are in two different countries | May be legitimate (SSH) but worth a look | Add to the risk score, require MFA again |
Each session log should have: client_id, created_ip, created_ua, approved_by, approve_ip, time, result. Do not log device_code, plaintext user_code or tokens.
6. Short runbook for support
- Ask the user for the output of
devcli whoami --output jsonrun inside and outside the project directory. - If it succeeds outside and fails inside: check the
teamIdin the link file against the account's team list. - If both fail with 401: ask for the CLI version, request an upgrade, then
logout+login. - If
loginis stuck at "Waiting for confirmation": check that the user opened the right URL and that the code on the page matches the code in the terminal. - Never ask the user to send a token, the
auth.jsonfile, or a screenshot containing a token. - If you suspect a token has leaked (the user accidentally pasted it into chat, a ticket, a log), guide them to revoke it immediately from the session management page on the web, and only then continue debugging.
- Record the CLI version, operating system, and the result of each step in the ticket so the development team can reproduce it.
- If the same symptom appears for many users in a short time, switch to checking the latest CLI release and the server-side dashboard.
7. Writing a blameless postmortem
An incident like the case study is easily seen as "user error". A blameless postmortem focuses on how the system made the error easy to make and hard to detect.
| Section | Content for the case study |
|---|---|
| Summary | A developer logged in successfully but every command in the project directory got 403; it took about an hour to find the cause |
| Impact | Delayed deploy; no data exposed; no impact on other users |
| Timeline | As in the diagram in section 1, with specific times |
| Root cause | Token for account A, link file selecting a team of account B; the old CLI only printed "Not authorized" |
| Contributing factors | The browser already held account A's session; the approval page did not clearly show the account; whoami failed inside the project directory so it could not answer "who am I" |
| What went well | Tried whoami outside the project directory; did not print tokens while debugging |
| Actions | (1) 403 errors state identity, team and the team's source; (2) whoami does not depend on the link file; (3) the approval page has a "Switch account" button; (4) the CLI warns when the version is too old |
| Owners and due dates | Each action has one owner and one completion date |
A good action changes the system, not "remind everyone to be more careful". Each action should have a way to verify it: for example, an integration test that reproduces exactly the "token of account A, link file for team B" scenario and checks the content of the error message.
test("403 states the identity and the source of the team", async () => {
const out = await runCli(["whoami"], { cwd: projectLinkedToTeamB, token: tokenOfUserA });
expect(out.exitCode).toBe(1);
expect(out.stderr).toContain("userA@example.com");
expect(out.stderr).toContain(".devcli/project.json");
});
8. Checklist before releasing a new CLI version
Many login incidents start with a CLI release. Before each release:
| Item | Check |
|---|---|
| Login flow | Run the three scenarios approve, deny, abandon on the staging environment |
| Polling | Measure the actual spacing between requests; no slow_down when the server returns the default interval |
| Token storage | Check the keychain on macOS, Windows, Linux with Secret Service, and the 0600 file fallback in containers |
| Backward compatibility | The new version can read credentials saved by the old version; if the format changes, there is a migration step |
| Error messages | 401 and 403 errors still state identity, team and source |
| Version warning | The server can return a header suggesting the minimum version; the CLI prints a warning when too old |
| Telemetry | User-Agent carries the right version so the dashboard can split metrics by version |
After a release, watch codes_expired / codes_issued and slow_down_rate by version for the first 24 hours; an abnormal increase is a rollback signal.
Part 3: Capstone: spec and threat model for devcli login
1. Spec structure
Same format as the Login Flow Design course, Day 7 Part 3 (/login-flow-design/week/02/day-07-step-up-operator-viet-spec): a fixed block per endpoint.
Scope: devcli login, logout, whoami, automatic refresh, profile/team selection. Out of scope: web dashboard login, CI login (a separate spec on OIDC federation).
2. Endpoint table template: POST /token (device grant)
Overview: the CLI polls to exchange device_code for tokens after the user approves in the browser.
HTTP method / Endpoint: POST https://auth.example.com/token
| Location | Item | Required | Value |
|---|---|---|---|
| header | Content-Type | Yes | application/x-www-form-urlencoded |
| header | Accept | No | application/json |
| body | grant_type | Yes | urn:ietf:params:oauth:grant-type:device_code |
| body | device_code | Yes | Value received from /device/code |
| body | client_id | Yes | devcli (public client, no secret) |
Processing details:
- Wrong
grant_type→ 400unsupported_grant_type. - Unregistered
client_id→ 401invalid_client. - Look up
dc:{sha256(device_code)}. Not found → 400expired_token. client_iddiffers from the value in the record → 400invalid_grant.- Previous poll was less than
intervalago → increaseintervalby 5 seconds, 400slow_down. status=pending→ 400authorization_pending.status=denied→ delete the record, 400access_denied.status=approved→SET used:{hash} NX; lose → 400invalid_grant; win → delete the record, issue tokens, 200.- Every response has
Cache-Control: no-store.
Response 200:
| Field | Value |
|---|---|
access_token | JWT, TTL 3600 seconds |
refresh_token | Opaque, TTL 30 days, rotation on |
token_type | Bearer |
expires_in | 3600 |
scope | The scope actually granted |
Repeat this block for /device/code, /device (GET), /device/approve, /revoke, /v1/me.
3. Data model
| Storage | Key | Field | Source | TTL |
|---|---|---|---|---|
| Redis | dc:{sha256(device_code)} | client_id, scope, user_code (display form XXXX-XXXX), status, user_id, interval, last_poll_at, created_ip, created_ua | /device/code request, approval page | expires_in (600 seconds) |
| Redis | uc:{normalized user_code}, e.g. uc:BDFHKLMN (uppercase, dash removed) | value = hash of device_code | /device/code | expires_in, deleted immediately on approve/deny |
| Redis | used:{hash} | "1" | /token | 600 seconds |
| Developer machine credential store | service devcli, account {profile} | JSON StoredAuth (issuer, userId, email, team, scope, refreshToken, accessToken?, expiresAt epoch ms); the access token goes into the store only when the JSON is ≤ 1,200 characters (≈ 2,400 bytes UTF-16, Windows Credential Manager limits to ~2560 bytes), otherwise it is dropped | CLI | Follows the refresh token |
| Developer machine file (fallback) | ~/.config/devcli/auth.json (Windows %APPDATA%\devcli\auth.json), permissions 0600, atomic write (temp file → fsync → rename) | { "version": 1, "profiles": { "<profile>": StoredAuth } } | CLI | Follows the refresh token |
| Project file | .devcli/project.json | teamId, projectId (no secrets) | devcli link | None |
4. Sequence diagram
sequenceDiagram
autonumber
participant U as User
participant C as devcli
participant A as auth.example.com
participant R as Redis
participant B as Browser
U->>C: devcli login
C->>A: POST /device/code (client_id, scope)
A->>R: SET uc:{normalized code} NX, HSET dc:{hash}
A-->>C: device_code, user_code, verification_uri, expires_in, interval
C-->>U: Print URL and user_code, open browser
loop Every interval seconds
C->>A: POST /token (device_code)
A->>R: HGETALL dc:{hash}
A-->>C: 400 authorization_pending
end
U->>B: Open verification_uri, enter user_code
B->>A: GET /device?user_code=...
A-->>B: Consent page (client, scope, IP, User-Agent)
B->>A: POST /device/approve (allow, CSRF token)
A->>R: Lua: status pending→approved, DEL uc:{code}
C->>A: POST /token (device_code)
A->>R: SET used:{hash} NX, DEL dc:{hash}
A-->>C: 200 access_token, refresh_token
C->>C: Save to keychain (fallback file 0600)
C-->>U: ✓ Logged in: email (profile, team)Every arrow must map back to a step in the endpoint table's "Processing details". If a step is missing from the diagram or vice versa, the spec is incomplete.
5. STRIDE threat model
| STRIDE | Threat | Applies to | Mitigation |
|---|---|---|---|
| Spoofing | Device code phishing: the attacker creates a session and tricks the victim into entering the user_code | Device flow | Short expires_in; the consent page shows the IP, location, and User-Agent where the session was created, with a clear warning; loopback by default; let organizations disable device flow |
| Spoofing | Another application on the machine listens on the loopback port to receive the code | Loopback | PKCE S256, state, bind 127.0.0.1 on a random port |
| Tampering | Edit .devcli/project.json to redirect requests to another team | CLI | The server always checks the user's permission on the team; the link file contains no secrets |
| Repudiation | A user denies having approved the session | Server | Log approved_by, approve_ip, time, created_ip |
| Information disclosure | Token leaks via logs, overly permissive files, terminal | CLI | Keychain, 0600 file, mask tokens when logging, do not print env |
| Information disclosure | A Redis dump exposes device_code | Server | Store the hash of device_code |
| Denial of service | Exhausting the user_code space, flooding polls | Server | Rate limit /device/code per IP and client; slow_down; cap the number of live sessions per IP |
| Elevation of privilege | A broad-scope token leaks | Both | Minimal scope at login, step-up when production write permission is needed; short access token TTL |
| Elevation of privilege | A refresh token is copied and used in parallel | CLI + Server | Rotation + reuse detection; inter-process lock so the CLI does not trigger it by accident |
6. 10-question CLI auth review checklist
- Is the default flow loopback + PKCE when a browser is available, with device flow only when headless or requested by the user?
- Does the
user_codehave enough entropy, a readable charset, rate limiting on wrong entries, and a short TTL? - Does the consent page show the client name, scope, the logged-in account (with a switch button), IP/location, and a phishing warning?
- Does the server enforce
interval/slow_downand issue tokens exactly once (atomic lock)? - Are the
device_codeand refresh token stored as hashes on the server? - Token storage in the CLI: keychain first, 0600 file fallback with a warning, never log values?
- Refresh: early refresh, single-flight within a process, inter-process lock, re-read after acquiring the lock?
- Does logout revoke on the server (RFC 7009) before deleting local data?
- Do the 401/403 error messages clearly state the identity, team, and their sources; does
whoamiwork outside the project directory? - CI: does the CLI refuse device flow when
CI=trueand point to OIDC federation or a machine token?
7. Second endpoint table and parameter table
Overview: the CLI creates a device authorization session.
HTTP method / Endpoint: POST https://auth.example.com/device/code
| Location | Item | Required | Value |
|---|---|---|---|
| header | Content-Type | Yes | application/x-www-form-urlencoded |
| body | client_id | Yes | devcli |
| body | scope | No | Default openid offline_access deploy:read; deploy:write is requested via step-up when a command needs it; only scopes in the client's allowed list are accepted |
Processing details:
- Unregistered
client_id→ 401invalid_client. - Scope outside the allowed list → 400
invalid_scope. - Rate limit exceeded per IP or client → 429,
Retry-Afterheader. - Generate a 32-byte random
device_code(base64url) and an 8-character base-20user_codein the formXXXX-XXXX. HSET dc:{sha256(device_code)}withstatus=pending,interval=5, IP and User-Agent,EXPIRE600, in oneMULTI(writedc:first souc:never points to a session that does not exist yet).SET uc:{normalized user_code} NX EX 600(uppercase, dash removed); on collision regenerate up to 5 times, still colliding → deletedc:, return 503temporarily_unavailablewithRetry-After(a code borrowed from RFC 6749 §4.1.2.1, outside §5.2, documented as a custom convention). On success,HSETtheuser_codeas well.- Return 200 with
device_code,user_code,verification_uri,verification_uri_complete,expires_in,interval;Cache-Control: no-store.
Parameter table (placed in section 8 of the spec):
| Parameter | Value | Reason |
|---|---|---|
expires_in | 600 seconds | Enough for the user to open the browser, short to limit phishing |
interval | 5 seconds | RFC 8628 default |
user_code | 8 base-20 characters | About 25.6 billion combinations, readable, no vowels |
| Wrong code entries | 5 per 15 minutes per session | Blocks code guessing |
| Access token TTL | 3600 seconds | Limits damage on leak |
| Refresh token TTL | 30 days, rotation | Balances convenience with theft detection |
/device/code rate limit | 10 requests per minute per IP | Prevents exhausting the code space |
8. Example: applying the checklist to a design
A team proposes: "DevCLI uses only device flow, the token is stored in ~/.devcli/token as plain text, logout deletes the file". Applying the checklist:
| Question | Result | Note |
|---|---|---|
| 1. Default flow | Fail | Missing loopback + PKCE when a browser is available, increasing phishing risk |
2. user_code | Unclear | The spec does not state charset, length, rate limit |
| 3. Consent page | Unclear | Needs a mockup with account, IP, warning |
4. Enforce interval, issue once | Unclear | Needs to be described in the /token table |
| 5. Hash secrets on the server | Unclear | Needs a data model section |
| 6. Token storage in the CLI | Fail | No keychain; file permissions not stated |
| 7. Refresh | Fail | No mention of an inter-process lock |
| 8. Logout | Fail | Only deletes locally, no revoke |
| 9. Error messages | Unclear | No 401/403 message template yet |
| 10. CI | Fail | Does not block device flow when CI=true |
Review conclusion: send the design back with 5 "fail" items that must be fixed and 5 "unclear" items to add to the spec. A good review points out what is missing and why, without rewriting the design for the team.
Review Questions
-
Two terminals run
devcliat the same time, and the server enables refresh token rotation with reuse detection. Describe why the user gets logged out in both places and how to fix it.Show answer
Both processes read the same refresh token R1. Process A exchanges it for R2; process B sends the already-used R1, the server treats it as reuse and revokes the whole token family including R2. Fix it with an inter-process lock around "read, refresh, write", and require re-reading the token after acquiring the lock; if another process just finished refreshing, use the new token and do not refresh again.
-
Why is single-flight (one shared promise) not enough for a CLI?
Show answer
Single-flight only coalesces refreshes within the same Node process. Developers often run several
devclicommands in parallel in different terminals, each command being a separate process with its own memory. Coordinating across processes requires a mechanism outside memory, such as a file lock in the config directory. -
A developer just ran
devcli loginsuccessfully, butdevcli whoamistill shows the old account. According to the credential precedence table, what is the most likely cause?Show answer
The
DEVCLI_TOKENenvironment variable (for example set in.zshrcearlier) has higher priority than the token in the keychain, so the CLI still uses the old token.whoamimust print the token's source so the user notices right away; the fix is to remove the environment variable or use--profileexplicitly. -
Why not run
devcli login(device flow) in GitHub Actions, and what to use instead?Show answer
Device flow needs a person to approve in the browser; the CI job would hang until the code expires, and printing the code to the log opens the door to phishing. Use OIDC federation instead: the job declares
permissions: id-token: write, requests a short-lived JWT from GitHub, and the ACME server checksissand the repository claim and then exchanges it for a short-lived access token. If the CI has no OIDC, use a narrow-scope machine token stored in the secret store. -
The server returns
invalid_grantwhen the CLI refreshes. What should the CLI do?Show answer
invalid_granton refresh means the refresh token expired, was revoked, or was detected as reused. The CLI should not retry; it should delete the local credential for that profile and ask the user to rundevcli login, with a message stating which profile is affected. If this happens often on a machine with many terminals, suspect a missing inter-process lock. -
devcli whoamifails in the project directory but succeeds in the home directory. What is your first hypothesis?Show answer
The token is valid, but the scope differs by directory: the project has a link file (for example
.devcli/project.json) selecting a team/project the current account has no access to. In the home directory, the CLI uses the account's default team so it succeeds. The next step is to look at theteamIdin the link file and compare it with the list of teams the account can see. -
Why didn't the advice "just log in again" solve the incident in the case study, until the last time?
Show answer
Every time the developer logged in again, the browser was still holding the personal account's session, so the issued token still belonged to the personal account. The problem was the wrong identity relative to the selected team, not an expired token. Only when the right work account was chosen on the approval page did the token get access to that team.
-
What information should a good 403 error message from a CLI contain?
Show answer
The identity in use (email/username), the selected scope (team/project) along with its source (flag, env, link file), the specific reason (not a team member), and suggested commands (
teams ls,loginchoosing the right account, re-linkthe project). It should also have a--output jsonmode with fields such asreason,hint,retryablefor scripts. -
Which metric suggests a device code phishing campaign targeting your users?
Show answer
Many sessions created from a small number of unusual IPs or ASNs, then approved by many different users within a short time, often with the creating IP and the approving IP in very different locations. When you see this signal, raise a security alert, revoke related tokens, and consider blocking device flow for the targeted group.
-
When debugging a login error, why should you not run a command that prints every environment variable or open the token file to look at it?
Show answer
Terminal output can end up in logs, history, screenshots, or be sent to AI tools, exposing tokens and other secrets. Diagnosis only needs to know whether the variable is set ([ -n "${VAR:+set}" ]) or the key names in the file, not the values.
- Why must the spec have both the "Processing details" table and the sequence diagram, instead of only one of them?
Show answer
The processing table lists all error branches and the order of checks, which a diagram usually omits. The diagram shows the interaction between parties over time, which is hard to see in a table. Cross-checking the two 1-1 helps find missing steps: an arrow with no corresponding step, or a step that does not appear in the flow.
- In STRIDE, which category does device code phishing belong to, and why doesn't PKCE help?
Show answer
It belongs to Spoofing: the attacker gets the victim to authenticate on behalf of the attacker's device. PKCE protects the channel that returns the code to the client that initiated the flow, but in device flow the attacker is the initiating client and holds the device_code; the victim only approves in the browser. Mitigation has to live in the consent page UX, short TTL, policies that block device flow, and preferring loopback.
- Why must the server still check the user's permission on the team, even though the CLI reads the team from a link file committed by the project itself?
Show answer
The link file lives on the client machine, so anyone can edit it (Tampering). It is only a scope hint, not proof of permission. The server must check whether the user in the token is a member of that team and return 403 if not. This is also why the link file must not contain secrets.
- How does checklist question 9 relate to the case study in Part 2 of this lesson?
Show answer
In the case study, the CLI only printed "Not authorized", without saying which account was in use or which link file the team came from, so the user logged in again many times for nothing. If the 403 error had stated the identity, team, and the team's source, and whoami worked outside the project directory, the incident would have been diagnosed in a few minutes.
- A design stores refresh tokens in plaintext in Redis on the grounds that "Redis is on the internal network". How do you push back?
Show answer
An internal network does not prevent leaks via backups, snapshots, debugging tools, employee read access, or an SSRF vulnerability. A refresh token is a long-lived bearer secret; storing a hash means leaked data cannot be used to obtain tokens, while the server can still match it. The cost of hashing is close to zero.
Hands-on Exercises
Exercise 1: Reproduce the multi-process refresh race
Simulate the race: run 5 node refresh-test.js processes at the same time when the token has 30 seconds left, with the server enabling rotation and reuse detection.
Expected output: without the lock, at least one process gets invalid_grant and all tokens are revoked; with the lock and re-read, exactly 1 refresh request reaches the server and all 5 processes share the new token.
Exercise 2: whoami prints the source of each value
Implement devcli whoami printing the source of each value (profile, team, token) according to the two precedence chains in section 4.
Expected output: when run with DEVCLI_TOKEN set and inside a directory with .devcli/project.json, the output clearly says "from env" and "from ./.devcli/project.json".
Exercise 3: OIDC federation for GitHub Actions
Write a GitHub Actions workflow that uses OIDC and specify the server-side checks.
Expected output: a YAML file with permissions: id-token: write; a table of the claims the server checks (iss, aud, sub/repository, exp) and the behavior when each claim is wrong.
Exercise 4: Reproduce the case study
Reproduce the case study with DevCLI: create two accounts, set .devcli/project.json to point to account B's team, and log in with account A.
Expected output: whoami fails inside the project directory and succeeds outside; record the diagnostic steps following the table in section 3.
Exercise 5: 403 error message with sources
Improve DevCLI's 403 error message following section 4, including a --output json mode.
Expected output: the text output states the identity, team, the team's source, and suggestions; the JSON output has the fields status, reason, hint, retryable.
Exercise 6: Expired code rate dashboard
Write a dashboard query for codes_expired / codes_issued by CLI version and set alert thresholds.
Expected output: a threshold table (normal, warning, critical) with the corresponding action for each level.
Exercise 7: DevCLI Authentication v1 spec (final course exercise)
Write the "DevCLI Authentication v1" spec following the structure in section 1, with complete endpoint tables for /device/code, /device, /device/approve, /token (device grant and refresh), /revoke, /v1/me.
Expected output: a 6-10 page Markdown file with a data model, an error branch table with HTTP statuses, a Mermaid sequence diagram that renders with npx -y @mermaid-js/mermaid-cli -i spec.md -o spec.svg, TTL/rate limit parameters, and a STRIDE threat model of at least 8 rows.
Exercise 8: Review a real CLI
Use the 10-question checklist in section 6 to review a real CLI you use often (for example GitHub CLI or AWS CLI), based on public documentation and observed behavior.
Expected output: a 10-row table with results "pass / fail / unclear", evidence (docs links or output with tokens masked), and improvement suggestions.
Exercise 9: Flow selection decision tree
Add a "Flow selection" section to the spec with a decision tree: browser available or not, --device flag or not, CI=true or not. Note that --no-browser only disables automatically opening the browser (it prints the URL) and does not change the flow.
Expected output: a decision diagram and a behavior table for each branch, with the corresponding CLI message.
References
- RFC 6749 §6 — Refreshing an Access Token
- RFC 9700 — OAuth 2.0 Security BCP (refresh token rotation, sender-constraining)
- RFC 8693 — OAuth 2.0 Token Exchange
- GitHub Actions — OpenID Connect
- GitHub Actions — Configuring OpenID Connect in AWS
- AWS CLI — Configuration and credentials precedence
- RFC 8628 §5 — Security Considerations
- RFC 6750 §3.1 — Error Codes (invalid_token, insufficient_scope)
- Microsoft Entra — Conditional Access: Authentication flows
- RFC 8628 — OAuth 2.0 Device Authorization Grant
- RFC 8252 — OAuth 2.0 for Native Apps
- RFC 7009 — OAuth 2.0 Token Revocation
- RFC 9700 — OAuth 2.0 Security Best Current Practice
- OWASP Threat Modeling Cheat Sheet