devHọc Dev

Week 1 - Day 4: Token Lifecycle and CI, Operational Debugging, Capstone Spec and Threat Model

Week 1 – Day 4

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 devcli processes 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

login──►access_token(short,e.g.1hour)+refresh_token(long,e.g.30days)││everydevclicommand▼valid>60sleft?──yes──►useitasis│no▼POST/tokengrant_type=refresh_token│┌──────┴────────────┐▼▼200:newtoken400invalid_grant(+newrefresh(refreshexpired/revoked/ifrotation)reused)││saveitdeletelocal,require`devclilogin`
ParameterSuggested value for DevCLIReason
Access token TTL1 hourShort damage window if leaked
Refresh token TTL30 days, sliding on useDevelopers don't have to log in again every day
Early refresh thresholdLess than 60 seconds leftCompensates for clock skew and network latency
Refresh token rotationOnDetects 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).

TerminalATerminalBreadrefreshR1readrefreshR1POSTrefresh(R1)──►R2✓POSTrefresh(R1)──►R1alreadyused!server:reusedetected──►revokeR2andallrelatedtokensuseR2nexttime──►invalid_grant=>bothterminalsareloggedout

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) and clearAuth hold this lock while doing read-modify-write on auth.json. A per-profile lock does not protect the shared file: if profiles default and work refresh 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.

BugSymptomFix
No inter-process lockOccasionally every terminal is logged out at onceFile lock as above
Lock but no re-readSame as above, hard to reproduceRe-read the token inside the lock
Server returns a new refresh token but the CLI does not save itThe next refresh uses the old token and gets revokedAlways save the new refresh_token if present
Stale lock when a process is killedCommand hangs foreverCheck 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 ownTwo processes refresh together, triggering reuse detectionWrite 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?"

PrioritySourceExample
1Command line flag--token <token>
2Environment variableDEVCLI_TOKEN
3Token of the selected profileprofile 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?"

PrioritySourceExample
1Command line flag--team team-platform
2Environment variableDEVCLI_TEAM
3Project directory link file.devcli/project.json containing teamId, projectId
4Profile's default teamteam 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:

  1. Environment variables beat files, so a stale DEVCLI_TOKEN in .zshrc can silently override the token you just logged in with. whoami must print the source clearly: token: env DEVCLI_TOKEN.
  2. 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:

ApproachDescriptionWhen to use
Machine token (machine token / service account)Long-lived token created on the dashboard, narrow scope, stored in the CI secret storeCI system does not support OIDC
OIDC federationCI issues a short-lived JWT per job; the IdP/cloud trusts the CI issuer and exchanges the JWT for a short-lived tokenGitHub Actions, GitLab CI, and other CIs with OIDC
Workload identityRunning on cloud, use the machine/pod identityJobs 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:

ApproachProsCons
One broad-scope token at loginSimple, log in onceA leaked token leaks every permission
Log in with minimal scope, request more when needed (step-up)Least privilegeOne 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

MistakeConsequenceRight way
Refresh exactly at expiresAtThe request reaches the server after the token expired, gets 401, and only then refreshesRefresh about 60 seconds early
Retry forever when refresh gets invalid_grantCLI hangs or spams the serverinvalid_grant is a terminal error: delete the credential, require login
Not saving the new refresh_token returnedThe next refresh uses an invalidated tokenAlways overwrite if the response contains refresh_token
Sharing one profile across several accountsLogging in to one account overwrites the otherOne profile per account, whoami prints the profile
Enabling device flow in CI "for convenience"Job hangs, code leaks in the logBlock 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.

┌─────────────────────────────────────────────────────────┐│Timeline││││t0whoami->Notauthorized││t1login->"Loggedin"││t2whoami->Notauthorized(absurd?)││t3logout+login->"Loggedin"││t4whoami->Notauthorized││t5whoami(outsideprojectdir)->printsusername!│└─────────────────────────────────────────────────────────┘

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

LayerQuestionIn the case study
1. CLI versionIs 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. IdentityWhich 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. ScopeWhich 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:

devcliwhoami(insidetheprojectdirectory)│├─token:keychain──►personalaccount├─team:.devcli/project.json──►team-platformoftheworkaccount▼GET/v1/me?teamId=team-platform▼403forbidden:userisnotamemberofteam-platform▼OldCLIprints:"Error:Notauthorized"◄──allcontextlost

3. Diagnostic procedure

StepCommand/actionConclusion
1Check the CLI version, try the latest version (e.g. npx <cli>@latest whoami) without overwriting the installNew versions usually print structured errors with reason and hint
2Run whoami inside and outside the project directoryDifferent results ⇒ suspect the project link file
3List the teams the current account can seeThe team in the link file is not in the list ⇒ wrong account or not invited yet
4Open the link file (.devcli/project.json), look at teamId/projectId (not secrets)You know exactly which scope the CLI is sending
5Check the relevant environment variables without printing values ([ -n "${DEVCLI_TOKEN:+set}" ])Rules out a stale token in env overriding
6Check which account is logged in in the browser before approvingAvoids issuing a token to the wrong account again
7logout, login again and choose the right account on the approval pageA 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)
PrincipleApplication
State the identity in usePrint email/username in 401/403 errors
State the scope and its source"team-platform (from ./.devcli/project.json)"
Distinguish 401 from 403401: 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 scopeThis 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

┌─────────────────────────────────────────────────────────┐│Deviceflowdashboard(perclient_id,perhour)││││codes_issuednewsessionscreated││codes_approvedsessionsapproved││codes_deniedsessionsdenied││codes_expiredsessionsexpiredunused││token_polls/sess.averagenumberofpolls││slow_down_rate%slow_downresponses││approve_latency_p50timefromcreationtoapproval││user_code_failureswrongcodeentries│└─────────────────────────────────────────────────────────┘
SignalInterpretationAction
codes_expired / codes_issued spikesApproval page UX problem, or a new CLI version prints the wrong URLCheck the latest CLI release, test the flow end-to-end
High slow_down_rate for one CLI versionClient polls at the wrong pace or resets the intervalReport a bug to the CLI team, keep the rate limit
user_code_failures rising from a few IPsSomeone is guessing codesTighten rate limits, temporarily block the IPs
Many sessions created from one unusual IP/ASN, approved by many different usersSign 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 countriesMay be legitimate (SSH) but worth a lookAdd 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

  1. Ask the user for the output of devcli whoami --output json run inside and outside the project directory.
  2. If it succeeds outside and fails inside: check the teamId in the link file against the account's team list.
  3. If both fail with 401: ask for the CLI version, request an upgrade, then logout + login.
  4. If login is 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.
  5. Never ask the user to send a token, the auth.json file, or a screenshot containing a token.
  6. 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.
  7. Record the CLI version, operating system, and the result of each step in the ticket so the development team can reproduce it.
  8. 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.

SectionContent for the case study
SummaryA developer logged in successfully but every command in the project directory got 403; it took about an hour to find the cause
ImpactDelayed deploy; no data exposed; no impact on other users
TimelineAs in the diagram in section 1, with specific times
Root causeToken for account A, link file selecting a team of account B; the old CLI only printed "Not authorized"
Contributing factorsThe 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 wellTried 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 datesEach 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:

ItemCheck
Login flowRun the three scenarios approve, deny, abandon on the staging environment
PollingMeasure the actual spacing between requests; no slow_down when the server returns the default interval
Token storageCheck the keychain on macOS, Windows, Linux with Secret Service, and the 0600 file fallback in containers
Backward compatibilityThe new version can read credentials saved by the old version; if the format changes, there is a migration step
Error messages401 and 403 errors still state identity, team and source
Version warningThe server can return a header suggesting the minimum version; the CLI prints a warning when too old
TelemetryUser-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.

┌─────────────────────────────────────────────────────────┐│Spec:DevCLIAuthenticationv1││││1.Scopeandoutofscope││2.Terminology(device_code,user_code,profile,team)││3.Flowselection(loopbackdefault,devicefallback)││4.Endpoints(fixedtableforeachendpoint)││5.Datamodel(Redis,keychain,linkfile)││6.Errorbranches+HTTPstatus+CLImessages││7.Sequencediagram││8.Parameters(TTL,interval,ratelimit)││9.Threatmodel(STRIDE)││10.Metrics,alerts,runbook│└─────────────────────────────────────────────────────────┘

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

LocationItemRequiredValue
headerContent-TypeYesapplication/x-www-form-urlencoded
headerAcceptNoapplication/json
bodygrant_typeYesurn:ietf:params:oauth:grant-type:device_code
bodydevice_codeYesValue received from /device/code
bodyclient_idYesdevcli (public client, no secret)

Processing details:

  1. Wrong grant_type → 400 unsupported_grant_type.
  2. Unregistered client_id → 401 invalid_client.
  3. Look up dc:{sha256(device_code)}. Not found → 400 expired_token.
  4. client_id differs from the value in the record → 400 invalid_grant.
  5. Previous poll was less than interval ago → increase interval by 5 seconds, 400 slow_down.
  6. status=pending → 400 authorization_pending.
  7. status=denied → delete the record, 400 access_denied.
  8. status=approved → SET used:{hash} NX; lose → 400 invalid_grant; win → delete the record, issue tokens, 200.
  9. Every response has Cache-Control: no-store.

Response 200:

FieldValue
access_tokenJWT, TTL 3600 seconds
refresh_tokenOpaque, TTL 30 days, rotation on
token_typeBearer
expires_in3600
scopeThe scope actually granted

Repeat this block for /device/code, /device (GET), /device/approve, /revoke, /v1/me.

3. Data model

StorageKeyFieldSourceTTL
Redisdc:{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 pageexpires_in (600 seconds)
Redisuc:{normalized user_code}, e.g. uc:BDFHKLMN (uppercase, dash removed)value = hash of device_code/device/codeexpires_in, deleted immediately on approve/deny
Redisused:{hash}"1"/token600 seconds
Developer machine credential storeservice 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 droppedCLIFollows 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 } }CLIFollows the refresh token
Project file.devcli/project.jsonteamId, projectId (no secrets)devcli linkNone

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

STRIDEThreatApplies toMitigation
SpoofingDevice code phishing: the attacker creates a session and tricks the victim into entering the user_codeDevice flowShort 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
SpoofingAnother application on the machine listens on the loopback port to receive the codeLoopbackPKCE S256, state, bind 127.0.0.1 on a random port
TamperingEdit .devcli/project.json to redirect requests to another teamCLIThe server always checks the user's permission on the team; the link file contains no secrets
RepudiationA user denies having approved the sessionServerLog approved_by, approve_ip, time, created_ip
Information disclosureToken leaks via logs, overly permissive files, terminalCLIKeychain, 0600 file, mask tokens when logging, do not print env
Information disclosureA Redis dump exposes device_codeServerStore the hash of device_code
Denial of serviceExhausting the user_code space, flooding pollsServerRate limit /device/code per IP and client; slow_down; cap the number of live sessions per IP
Elevation of privilegeA broad-scope token leaksBothMinimal scope at login, step-up when production write permission is needed; short access token TTL
Elevation of privilegeA refresh token is copied and used in parallelCLI + ServerRotation + reuse detection; inter-process lock so the CLI does not trigger it by accident

6. 10-question CLI auth review checklist

  1. Is the default flow loopback + PKCE when a browser is available, with device flow only when headless or requested by the user?
  2. Does the user_code have enough entropy, a readable charset, rate limiting on wrong entries, and a short TTL?
  3. Does the consent page show the client name, scope, the logged-in account (with a switch button), IP/location, and a phishing warning?
  4. Does the server enforce interval/slow_down and issue tokens exactly once (atomic lock)?
  5. Are the device_code and refresh token stored as hashes on the server?
  6. Token storage in the CLI: keychain first, 0600 file fallback with a warning, never log values?
  7. Refresh: early refresh, single-flight within a process, inter-process lock, re-read after acquiring the lock?
  8. Does logout revoke on the server (RFC 7009) before deleting local data?
  9. Do the 401/403 error messages clearly state the identity, team, and their sources; does whoami work outside the project directory?
  10. CI: does the CLI refuse device flow when CI=true and 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

LocationItemRequiredValue
headerContent-TypeYesapplication/x-www-form-urlencoded
bodyclient_idYesdevcli
bodyscopeNoDefault 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:

  1. Unregistered client_id → 401 invalid_client.
  2. Scope outside the allowed list → 400 invalid_scope.
  3. Rate limit exceeded per IP or client → 429, Retry-After header.
  4. Generate a 32-byte random device_code (base64url) and an 8-character base-20 user_code in the form XXXX-XXXX.
  5. HSET dc:{sha256(device_code)} with status=pending, interval=5, IP and User-Agent, EXPIRE 600, in one MULTI (write dc: first so uc: never points to a session that does not exist yet).
  6. SET uc:{normalized user_code} NX EX 600 (uppercase, dash removed); on collision regenerate up to 5 times, still colliding → delete dc:, return 503 temporarily_unavailable with Retry-After (a code borrowed from RFC 6749 §4.1.2.1, outside §5.2, documented as a custom convention). On success, HSET the user_code as well.
  7. 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):

ParameterValueReason
expires_in600 secondsEnough for the user to open the browser, short to limit phishing
interval5 secondsRFC 8628 default
user_code8 base-20 charactersAbout 25.6 billion combinations, readable, no vowels
Wrong code entries5 per 15 minutes per sessionBlocks code guessing
Access token TTL3600 secondsLimits damage on leak
Refresh token TTL30 days, rotationBalances convenience with theft detection
/device/code rate limit10 requests per minute per IPPrevents 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:

QuestionResultNote
1. Default flowFailMissing loopback + PKCE when a browser is available, increasing phishing risk
2. user_codeUnclearThe spec does not state charset, length, rate limit
3. Consent pageUnclearNeeds a mockup with account, IP, warning
4. Enforce interval, issue onceUnclearNeeds to be described in the /token table
5. Hash secrets on the serverUnclearNeeds a data model section
6. Token storage in the CLIFailNo keychain; file permissions not stated
7. RefreshFailNo mention of an inter-process lock
8. LogoutFailOnly deletes locally, no revoke
9. Error messagesUnclearNo 401/403 message template yet
10. CIFailDoes 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

  1. Two terminals run devcli at 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.

  2. 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 devcli commands 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.

  3. A developer just ran devcli login successfully, but devcli whoami still shows the old account. According to the credential precedence table, what is the most likely cause?

    Show answer

    The DEVCLI_TOKEN environment variable (for example set in .zshrc earlier) has higher priority than the token in the keychain, so the CLI still uses the old token. whoami must print the token's source so the user notices right away; the fix is to remove the environment variable or use --profile explicitly.

  4. 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 checks iss and 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.

  5. The server returns invalid_grant when the CLI refreshes. What should the CLI do?

    Show answer

    invalid_grant on 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 run devcli 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.

  6. devcli whoami fails 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 the teamId in the link file and compare it with the list of teams the account can see.

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

  8. 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, login choosing the right account, re-link the project). It should also have a --output json mode with fields such as reason, hint, retryable for scripts.

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

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

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

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

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

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

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


Next lesson →