Bài này gộp 3 chủ đề: Xây authorization server hỗ trợ device flow, Xây CLI client
devcli login, Device flow với IdP có sẵn.
Mục tiêu học tập
- Thiết kế đủ bốn endpoint phía server cho device flow của DevCLI:
/device/code,/device,/device/approve,/token - Xây data model trên Redis: lưu
device_codedạng hash, ánh xạuser_code, TTL bằngexpires_in - Cài đặt state machine
pending → approved | denied | expired → consumedvà bảo đảm token chỉ phát một lần - Enforce
intervalvàslow_downở server thay vì tin client tự giữ nhịp - Liệt kê đủ nhánh lỗi với đúng mã lỗi OAuth và HTTP status theo RFC 6749 §5.2 và RFC 8628 §3.5
- Viết lệnh
devcli loginhoàn chỉnh bằng TypeScript trên Node 22+, chỉ dùngfetchcó sẵn và một thư viện keychain - Cài đặt vòng polling tôn trọng
interval,slow_down,expires_invà xử lý đúng mọi mã lỗi dừng - Hỗ trợ Ctrl+C, timeout mạng và cờ
--no-browser(chỉ in URL, không tự mở trình duyệt; không đổi flow) - Lưu token vào OS keychain bằng
@napi-rs/keyring(Linux ghim Secret Service), fallback file 0600 theo từng profile - Viết
devcli whoamivàdevcli logout(revoke ở server theo RFC 7009 rồi xoá local) - Biết cách bật và gọi device flow trên các IdP phổ biến: Auth0, Okta, Microsoft Entra ID, GitHub, Keycloak
- Nhận ra chỗ các IdP lệch khỏi RFC 8628 (tên endpoint, mã lỗi, trường bị lược bỏ) để CLI không viết cứng theo một nhà cung cấp
- Hiểu vì sao AWS CLI v2 chuyển
aws sso loginsang Authorization Code + PKCE làm mặc định và vẫn giữ--use-device-code - Biết Amazon Cognito user pool không hỗ trợ device flow native và chọn pattern thay thế
- Viết lớp "provider adapter" trong DevCLI để đổi IdP mà không đổi vòng polling
Phần 1: Xây authorization server hỗ trợ device flow
1. Bức tranh tổng thể phía server
Ở Ngày 1, Phần 2 (RFC 8628) ta đã đi qua giao thức từ góc nhìn client. Hôm nay ta đứng ở phía authorization server https://auth.example.com của ACME Cloud và tự xây phần đó.
| Endpoint | Ai gọi | Mục đích |
|---|---|---|
POST /device/code | CLI | Tạo phiên device authorization, trả device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval |
GET /device | Trình duyệt | Trang nhập user_code (hoặc tự điền từ verification_uri_complete) |
POST /device/approve | Trình duyệt (đã đăng nhập) | Người dùng xác nhận hoặc từ chối |
POST /token | CLI | Polling với grant_type=urn:ietf:params:oauth:grant-type:device_code |
Điểm khác Authorization Code: không có redirect_uri, hai "kênh" (CLI và trình duyệt) chỉ gặp nhau qua dữ liệu trong Redis. Toàn bộ an toàn của flow dựa vào việc server giữ trạng thái đúng.
2. Data model trên Redis
Các quyết định thiết kế:
| Quyết định | Lý do |
|---|---|
Lưu sha256(device_code) thay vì bản rõ | device_code là bearer secret của CLI. Nếu Redis bị đọc trộm (backup, log, dump), kẻ tấn công không lấy được token. Giống cách lưu refresh token |
user_code lưu bản rõ, khoá uc: ở dạng chuẩn hoá (in hoa, bỏ gạch) | Người dùng có thể gõ bdfh klmn hay BDFH-KLMN; mọi biến thể phải ra cùng một khoá. Người dùng phải nhập lại; entropy thấp nên bảo vệ bằng rate limit và TTL ngắn (Ngày 1, Phần 3), không phải bằng hash |
TTL Redis = expires_in | Phiên tự biến mất, không cần job dọn dẹp; trạng thái expired suy ra từ "không tìm thấy key" |
Lưu created_ip, created_ua | Hiển thị trên trang consent để người dùng nhận ra phiên lạ (chống device code phishing, Ngày 2, Phần 3) |
last_poll_at + interval trong record | Server tự quyết khi nào trả slow_down, không phụ thuộc client |
Lỗi hay gặp: dùng user_code làm khoá chính duy nhất. user_code ngắn nên có thể trùng giữa hai phiên đang sống; luôn sinh lại khi SET NX thất bại.
3. State machine
uc:{code} bị xoá ngay ở bước approve hoặc deny (mục 5), không đợi tới lúc consume. Từ đó user_code vô dụng; CLI vẫn poll bằng device_code.
| Trạng thái hiện tại | POST /token trả về |
|---|---|
Không tìm thấy dc:{hash} | 400 expired_token (hoặc invalid_grant nếu muốn không phân biệt "sai" với "hết hạn") |
pending, poll đúng nhịp | 400 authorization_pending |
pending, poll sớm hơn interval | 400 slow_down, tăng interval lên 5 giây |
denied | 400 access_denied, xoá key |
approved, thắng used | 200 kèm access_token, refresh_token, expires_in |
approved, thua used (request trùng) | 400 invalid_grant |
Theo RFC 8628 §3.5, chỉ authorization_pending và slow_down cho phép client tiếp tục poll; mọi mã khác client phải dừng.
4. Endpoint POST /device/code
import express from "express";
import { createClient } from "redis";
import { createHash, randomBytes, randomInt } from "node:crypto";
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
const app = express();
app.use(express.urlencoded({ extended: false }));
const EXPIRES_IN = 600; // 10 phút
const INTERVAL = 5; // giây, mặc định RFC 8628
const ALPHABET = "BCDFGHJKLMNPQRSTVWXZ"; // base-20, RFC 8628 §6.1
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
function newUserCode(): string {
let s = "";
for (let i = 0; i < 8; i++) s += ALPHABET[randomInt(ALPHABET.length)];
return `${s.slice(0, 4)}-${s.slice(4)}`; // dạng hiển thị XXXX-XXXX
}
// Dạng dùng làm khoá Redis: in hoa, bỏ mọi ký tự ngoài charset (gạch, khoảng trắng)
const normalize = (s: string) =>
[...s.toUpperCase()].filter((c) => ALPHABET.includes(c)).join("");
const CLIENTS: Record<string, { scopes: string[] }> = {
devcli: { scopes: ["openid", "offline_access", "deploy:read", "deploy:write"] },
};
const DEFAULT_SCOPE = "openid offline_access deploy:read";
app.post("/device/code", async (req, res) => {
const clientId = String(req.body.client_id ?? "");
const client = CLIENTS[clientId];
if (!client) return res.status(401).json({ error: "invalid_client" });
// RFC 8628 §3.1: tham số rỗng coi như bị bỏ qua, nên `scope=` cũng nhận scope mặc định
const scope = String(req.body.scope ?? "").trim() || DEFAULT_SCOPE;
if (!scope.split(" ").every((s) => client.scopes.includes(s)))
return res.status(400).json({ error: "invalid_scope" });
const deviceCode = randomBytes(32).toString("base64url");
const dcHash = sha256(deviceCode);
const dcKey = `dc:${dcHash}`;
// Ghi dc: TRƯỚC, hSet + expire trong một MULTI: uc: không bao giờ trỏ tới phiên chưa tồn tại
await redis.multi()
.hSet(dcKey, {
client_id: clientId, scope, status: "pending",
interval: String(INTERVAL), last_poll_at: "0",
created_ip: req.ip ?? "", created_ua: String(req.get("user-agent") ?? ""),
})
.expire(dcKey, EXPIRES_IN)
.exec();
let userCode = "";
for (let attempt = 0; attempt < 5 && !userCode; attempt++) {
const candidate = newUserCode();
const ok = await redis.set(`uc:${normalize(candidate)}`, dcHash, { EX: EXPIRES_IN, NX: true });
if (ok) userCode = candidate;
}
if (!userCode) {
await redis.del(dcKey);
// §5.2 không có mã cho lỗi tạm thời; mượn temporarily_unavailable của RFC 6749 §4.1.2.1
return res.status(503).set("Retry-After", "5").json({ error: "temporarily_unavailable" });
}
await redis.hSet(dcKey, { user_code: userCode });
res.set("Cache-Control", "no-store").json({
device_code: deviceCode,
user_code: userCode,
verification_uri: "https://example.com/device",
verification_uri_complete: `https://example.com/device?user_code=${userCode}`,
expires_in: EXPIRES_IN,
interval: INTERVAL,
});
});
Ghi chú:
client_idsai trảinvalid_client. RFC 6749 §5.2 cho phép 401 cho lỗi này; với public client không gửi headerAuthorization, 400 cũng hợp lệ. Chọn một và ghi vào spec.- Hết 5 lần sinh
user_codevẫn trùng: RFC 6749 §5.2 (mà RFC 8628 §3.2 dùng lại cho endpoint này) không có mã lỗi cho tình huống "tạm thời quá tải". Bài này mượntemporarily_unavailablecủa §4.1.2.1 (authorization endpoint) kèm HTTP 503 vàRetry-After; đây là quy ước riêng, phải ghi vào spec. Client chỉ cần coi mọi mã lạ là lỗi dừng. - Rate limit endpoint này theo IP và theo
client_idđể kẻ tấn công không "đổ đầy" không gianuser_code. Cache-Control: no-storecho mọi response chứa secret, giống token endpoint.
5. Trang /device và POST /device/approve
Trang nhập mã chỉ hiển thị sau khi người dùng đã đăng nhập SSO bình thường (cookie session của example.com). Luồng:
GET /device?user_code=BDFH-KLMN:normalize()(in hoa, bỏ ký tự ngoài charset như gạch, khoảng trắng) raBDFHKLMN, trauc:BDFHKLMN→dcHash→dc:{dcHash}.- Hiển thị trang consent: tên client "DevCLI", danh sách scope, IP và User-Agent đã khởi tạo, thời điểm tạo, cảnh báo "Chỉ tiếp tục nếu chính bạn vừa chạy
devcli login". POST /device/approvevớiuser_code,decision=allow|denyvà CSRF token của form.
app.post("/device/approve", requireSession, verifyCsrf, async (req, res) => {
const code = normalize(String(req.body.user_code ?? ""));
const dcHash = await redis.get(`uc:${code}`);
if (!dcHash) return res.status(404).render("device-invalid");
const allow = req.body.decision === "allow";
// Đọc-kiểm-ghi trong một Lua script để allow và deny gửi đồng thời không cùng lọt qua
const changed = await redis.eval(APPROVE_SCRIPT, {
keys: [`dc:${dcHash}`, `uc:${code}`],
arguments: [allow ? "approved" : "denied", allow ? String(req.session.userId) : ""],
});
if (changed === -1) return res.status(404).render("device-invalid"); // phiên đã hết hạn/biến mất
if (changed !== 1) return res.status(409).render("device-already-used");
res.render("device-done", { allowed: allow });
});
// KEYS[1] = dc:{hash}, KEYS[2] = uc:{code}; ARGV[1] = status mới, ARGV[2] = user_id
const APPROVE_SCRIPT = `
local status = redis.call("HGET", KEYS[1], "status")
if not status then redis.call("DEL", KEYS[2]) return -1 end
if status ~= "pending" then return 0 end
redis.call("HSET", KEYS[1], "status", ARGV[1], "user_id", ARGV[2])
redis.call("DEL", KEYS[2])
return 1
`;
redis.eval(script, { keys, arguments }) là API của node-redis v4, cùng client createClient ở mục 4. Lua script chạy atomic trong Redis: chỉ request đầu tiên thấy pending mới đổi được trạng thái và xoá uc:, request còn lại nhận 409. Nếu uc: còn mà dc: đã mất (hết TTL sớm hơn vài mili giây), script dọn uc: và trả -1 để trang báo "mã không hợp lệ hoặc đã hết hạn" (404), không báo nhầm "đã được sử dụng".
| Nhánh | Hành vi | HTTP |
|---|---|---|
| Chưa đăng nhập | Redirect sang login, giữ user_code trong tham số return_to đã kiểm tra cùng origin | 302 |
| Thiếu hoặc sai CSRF token | Từ chối | 403 |
user_code không tồn tại hoặc hết hạn | Trang "Mã không hợp lệ hoặc đã hết hạn", không nói rõ là sai hay hết hạn | 404 |
| Nhập sai quá N lần trong cửa sổ thời gian | Khoá tạm theo session và IP | 429 |
| Phiên đã được duyệt/từ chối | Trang "Mã đã được sử dụng" | 409 |
Vì sao xoá uc:{code} ngay khi duyệt? Nếu giữ lại, kẻ khác đoán trúng mã trong thời gian còn lại vẫn mở được trang consent và thấy thông tin phiên. Xoá xong, user_code vô dụng; CLI vẫn poll bằng device_code.
6. Endpoint POST /token với polling
app.post("/token", async (req, res) => {
res.set("Cache-Control", "no-store");
if (req.body.grant_type !== "urn:ietf:params:oauth:grant-type:device_code")
return res.status(400).json({ error: "unsupported_grant_type" });
const clientId = String(req.body.client_id ?? "");
if (!CLIENTS[clientId]) return res.status(401).json({ error: "invalid_client" });
const deviceCode = String(req.body.device_code ?? "");
if (!deviceCode) return res.status(400).json({ error: "invalid_request" });
const dcHash = sha256(deviceCode);
const key = `dc:${dcHash}`;
const rec = await redis.hGetAll(key);
if (!rec.status) return res.status(400).json({ error: "expired_token" });
if (rec.client_id !== clientId) return res.status(400).json({ error: "invalid_grant" });
// Server tự enforce nhịp polling
const now = Date.now();
const interval = Number(rec.interval);
if (now - Number(rec.last_poll_at) < interval * 1000) {
await redis.hSet(key, { interval: String(interval + 5), last_poll_at: String(now) });
return res.status(400).json({ error: "slow_down" });
}
await redis.hSet(key, { last_poll_at: String(now) });
if (rec.status === "pending") return res.status(400).json({ error: "authorization_pending" });
if (rec.status === "denied") {
await redis.del(key);
return res.status(400).json({ error: "access_denied" });
}
// approved: chỉ một request được phát token
const won = await redis.set(`used:${dcHash}`, "1", { EX: 600, NX: true });
if (!won) return res.status(400).json({ error: "invalid_grant" });
await redis.del(key);
const tokens = await issueTokens({ userId: rec.user_id, clientId, scope: rec.scope });
res.json({ token_type: "Bearer", ...tokens });
});
Ba điểm dễ sai:
- Kiểm tra
client_idkhớp với record. Nếu không, một client khác cầm đượcdevice_code(log rò rỉ) sẽ đổi được token. - Phát token một lần bằng
SET NX. Hai request poll trùng nhau (CLI retry do timeout mạng) có thể cùng thấyapproved; chỉ request thắng khoáusedmới nhận token. slow_downtăngintervalvĩnh viễn cho phiên đó. RFC 8628 §3.5: interval phải tăng thêm 5 giây cho lần này và mọi lần sau.
7. Bảng nhánh lỗi tổng hợp (dùng cho spec)
| Endpoint | Điều kiện | error | HTTP |
|---|---|---|---|
/device/code | client_id không tồn tại | invalid_client | 401 |
/device/code | scope ngoài danh sách cho phép | invalid_scope | 400 |
/device/code | Vượt rate limit theo IP hoặc client | Không có mã OAuth chuẩn; trả {"error":"rate_limited"} kèm Retry-After | 429 |
/device/code | Sinh user_code trùng 5 lần liên tiếp | Ngoài §5.2; quy ước temporarily_unavailable (mượn §4.1.2.1) kèm Retry-After | 503 |
/token | grant_type khác device_code | unsupported_grant_type | 400 |
/token | Thiếu device_code | invalid_request | 400 |
/token | Không tìm thấy phiên | expired_token | 400 |
/token | client_id không khớp phiên | invalid_grant | 400 |
/token | Poll sớm hơn interval | slow_down | 400 |
/token | Chưa duyệt | authorization_pending | 400 |
/token | Bị từ chối | access_denied | 400 |
/token | Đã phát token trước đó | invalid_grant | 400 |
RFC 6749 §5.2: lỗi token endpoint mặc định trả HTTP 400, riêng invalid_client server có thể trả 401 (bắt buộc 401 nếu client xác thực bằng header Authorization). Các mã authorization_pending, slow_down, access_denied, expired_token do RFC 8628 §3.5 bổ sung.
Đừng quên khai báo endpoint trong metadata (RFC 8414): device_authorization_endpoint và grant_types_supported có urn:ietf:params:oauth:grant-type:device_code.
Phần 2: Xây CLI client devcli login
1. Cấu trúc lệnh và trải nghiệm người dùng
Phạm vi bài này: nhánh --device. devcli login mặc định dùng loopback + PKCE (Ngày 2, Phần 1) và tự chuyển sang nhánh device khi phát hiện headless/SSH; devcli login --device ép dùng device flow. Hôm nay ta xây nhánh device; nhánh loopback đã có ở Ngày 2, Phần 1.
Output cần đạt:
$ devcli login --device
! Mở trình duyệt tại https://example.com/device
và nhập mã: BDFH-KLMN
(mã hết hạn sau 10 phút)
Đang chờ xác nhận... (Ctrl+C để huỷ)
✓ Đã đăng nhập: dev@example.com (profile: default, team: team-platform)
Tách code thành bốn module: oauth.ts (gọi server), poll.ts (vòng lặp), store.ts (lưu token), commands.ts (loginDevice, whoami, logout). Lệnh devcli login gọi loginDevice() khi có --device hoặc khi headless, ngược lại gọi nhánh loopback của Ngày 2, Phần 1.
2. Gọi device authorization endpoint
// oauth.ts
export const AUTH = "https://auth.example.com";
export const CLIENT_ID = "devcli"; // public client: không có client_secret
export interface DeviceCodeResponse {
device_code: string;
user_code: string;
verification_uri: string;
verification_uri_complete?: string;
expires_in: number;
interval?: number;
}
export async function requestDeviceCode(scope: string, signal: AbortSignal): Promise<DeviceCodeResponse> {
const res = await fetch(`${AUTH}/device/code`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ client_id: CLIENT_ID, scope }),
signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]), // Ctrl+C huỷ ngay
});
// Đọc text trước: proxy lỗi hay trả trang HTML 502, res.json() sẽ ném SyntaxError khó hiểu
const text = await res.text();
let body: any = null;
try { body = JSON.parse(text); } catch { /* không phải JSON */ }
if (!res.ok || !body) throw new Error(`device/code thất bại: ${body?.error ?? `HTTP ${res.status}`}`);
return body as DeviceCodeResponse;
}
Hai chi tiết:
- Body là
application/x-www-form-urlencoded, không phải JSON. RFC 8628 §3.1 dùng cùng định dạng với token endpoint của RFC 6749. intervallà tuỳ chọn; nếu server không trả, client dùng 5 giây (RFC 8628 §3.5).
3. Vòng polling
// poll.ts
import { setTimeout as sleep } from "node:timers/promises";
import { AUTH, CLIENT_ID, type DeviceCodeResponse } from "./oauth.js";
export interface TokenSet {
access_token: string;
refresh_token?: string;
expires_in: number;
token_type: string;
scope?: string;
}
export async function pollForToken(dc: DeviceCodeResponse, signal: AbortSignal): Promise<TokenSet> {
let interval = (dc.interval ?? 5) * 1000;
const deadline = Date.now() + dc.expires_in * 1000;
while (Date.now() < deadline) {
await sleep(interval, undefined, { signal }); // Ctrl+C sẽ ném AbortError
let res: Response;
try {
res = await fetch(`${AUTH}/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
device_code: dc.device_code,
client_id: CLIENT_ID,
}),
signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]),
});
} catch (e) {
if (signal.aborted) throw e;
interval = Math.min(interval * 2, 60_000); // lỗi mạng: lùi dần, không bỏ cuộc
continue;
}
const body = await res.json().catch(() => ({}));
if (res.ok) return body as TokenSet;
switch (body.error) {
case "authorization_pending":
continue;
case "slow_down":
interval += 5_000;
continue;
case "access_denied":
throw new LoginError("Yêu cầu đăng nhập đã bị từ chối trên trình duyệt.");
case "expired_token":
throw new LoginError("Mã đã hết hạn. Chạy lại `devcli login`.");
default:
throw new LoginError(`Đăng nhập thất bại: ${body.error ?? `HTTP ${res.status}`}`);
}
}
throw new LoginError("Mã đã hết hạn. Chạy lại `devcli login`.");
}
export class LoginError extends Error {}
| Tình huống | Hành vi của client | Lý do |
|---|---|---|
authorization_pending | Tiếp tục với interval hiện tại | RFC 8628 §3.5 |
slow_down | Cộng 5 giây vào interval cho mọi lần sau | RFC 8628 §3.5, MUST |
access_denied, expired_token, mã khác | Dừng, in thông báo, exit code khác 0 | Chỉ hai mã trên cho phép poll tiếp |
| Timeout hoặc lỗi kết nối | Lùi dần (exponential backoff), vẫn trong deadline | RFC 8628 §3.5 khuyến nghị backoff khi lỗi kết nối |
| Ctrl+C | Huỷ ngay giấc ngủ và request đang chạy | Không để tiến trình treo |
Lỗi hay gặp: reset interval về giá trị ban đầu sau slow_down. Server sẽ tiếp tục trả slow_down, và các server nghiêm ngặt có thể coi đó là hành vi lạm dụng.
4. Mở trình duyệt và chế độ không trình duyệt
// commands.ts (một phần)
import { spawn } from "node:child_process";
function openBrowser(url: string): void {
const [cmd, args]: [string, string[]] =
process.platform === "darwin" ? ["open", [url]]
: process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
: ["xdg-open", [url]];
const child = spawn(cmd, args, { stdio: "ignore", detached: true });
// spawn báo ENOENT qua event 'error' (bất đồng bộ), try/catch không bắt được
child.on("error", () => console.error("(Không mở được trình duyệt, hãy mở URL ở trên bằng tay.)"));
child.unref();
}
function isHeadless(): boolean {
return Boolean(process.env.SSH_CONNECTION || process.env.CI)
|| (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY);
}
Quy tắc hiển thị:
- In URL trước, rồi mới thử mở trình duyệt. Nếu mở thất bại (thiếu
xdg-open), người dùng vẫn có URL trên màn hình. - Trên Windows dùng
rundll32 url.dll,FileProtocolHandler, không dùngcmd /c start:cmd.exelà shell, nó coi&trong URL là dấu nối lệnh, làm URL bị cắt và phần sau bị chạy như một lệnh. - Luôn in
verification_urivàuser_codera stderr, kể cả khi đã mở được trình duyệt. Người dùng cần đối chiếu mã trên trang consent (chống phishing, Ngày 2, Phần 3). - Chỉ mở
verification_uri_completetự động khi chạy trên máy có màn hình. Với--no-browserhoặc phiên SSH, chỉ in URL để người dùng mở trên thiết bị khác. - Nếu
process.env.CIđược set, từ chối chạylogintương tác và hướng dẫn dùng token CI hoặc OIDC federation (Ngày 4, Phần 1).
5. Lưu token: keychain trước, file 0600 sau
keytar từng là lựa chọn phổ biến nhưng repo đã archived từ 12/2022. Hôm nay dùng @napi-rs/keyring, binding Node của thư viện Rust keyring-rs, API đồng bộ Entry.setPassword/getPassword/deletePassword.
// store.ts
import { Entry } from "@napi-rs/keyring";
import { mkdir, readFile, rename, open, rm } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { homedir } from "node:os";
import { join } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
import { withFileLock } from "./lock.js"; // khoá file liên tiến trình, giải thích ở Ngày 4, Phần 1 (mục 3)
const SERVICE = "devcli";
export const DIR = process.platform === "win32"
? join(process.env.APPDATA ?? homedir(), "devcli")
: join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "devcli");
const FILE = join(DIR, "auth.json");
const FILE_LOCK = join(DIR, "auth.json.lock"); // mọi profile chung một auth.json nên chung một khoá
const MAX_STORE_CHARS = 1_200; // Windows Credential Manager giới hạn blob ~2560 byte: chừa lề an toàn
export interface StoredAuth {
issuer: string;
userId: string;
email: string;
team: string;
scope: string;
refreshToken: string;
accessToken?: string; // có thể vắng khi store không chứa nổi; lần sau sẽ refresh
expiresAt: number; // hạn của accessToken, epoch ms
}
export type AuthFile = { version: 1; profiles: Record<string, StoredAuth> };
export const ensureDir = () => mkdir(DIR, { recursive: true, mode: 0o700 });
// Linux: ghim Secret Service; không ghim thì thư viện âm thầm rơi về kernel keyutils (mất khi reboot)
const entry = (profile: string) =>
new Entry(SERVICE, profile, { linux: { store: "secret-service" } });
function forStore(a: StoredAuth): string {
const full = JSON.stringify(a);
if (full.length <= MAX_STORE_CHARS) return full;
const { accessToken: _omit, ...small } = a; // chỉ giữ refresh token + metadata
return JSON.stringify({ ...small, expiresAt: 0 });
}
async function readFileStore(): Promise<AuthFile> {
let raw: string;
try { raw = await readFile(FILE, "utf8"); }
catch (e: any) { if (e.code === "ENOENT") return { version: 1, profiles: {} }; throw e; }
let f: AuthFile;
try { f = JSON.parse(raw); }
catch {
// Không ghi đè âm thầm: giữ bản hỏng để xem lại, báo user rồi coi như chưa đăng nhập
await rename(FILE, `${FILE}.bak`).catch(() => {});
console.error("Cảnh báo: auth.json bị hỏng, đã đổi tên thành auth.json.bak. Chạy lại `devcli login`.");
return { version: 1, profiles: {} };
}
if (f.version > 1) throw new Error("File đăng nhập được tạo bởi phiên bản DevCLI mới hơn, hãy nâng cấp CLI.");
return f;
}
async function writeFileStore(f: AuthFile): Promise<void> {
await ensureDir();
const tmp = `${FILE}.${randomUUID()}.tmp`;
try {
// File tạm mới tạo ("wx") với 0600: token không lúc nào nằm trong file quyền rộng hơn
const fh = await open(tmp, "wx", 0o600);
try {
await fh.writeFile(JSON.stringify(f, null, 2));
await fh.sync(); // dữ liệu xuống đĩa trước khi rename
} finally {
await fh.close();
}
await renameWithRetry(tmp, FILE);
} catch (e) {
await rm(tmp, { force: true }); // không để sót file tạm chứa token (ví dụ ENOSPC giữa chừng)
throw e;
}
}
// POSIX: rename trong cùng thư mục là atomic. Windows: đích đang bị mở (antivirus,
// tiến trình khác đang đọc) có thể làm rename lỗi EPERM/EBUSY tạm thời, nên thử lại vài lần
async function renameWithRetry(from: string, to: string): Promise<void> {
for (let i = 0; ; i++) {
try { return await rename(from, to); }
catch (e: any) {
if (i >= 4 || !["EPERM", "EBUSY", "EACCES"].includes(e.code)) throw e;
await sleep(50 * (i + 1));
}
}
}
export async function saveAuth(profile: string, a: StoredAuth): Promise<"keychain" | "file"> {
try {
entry(profile).setPassword(forStore(a));
return "keychain";
} catch {
// Đọc-sửa-ghi trong khoá chung: không có khoá thì hai profile ghi song song, bản ghi sau đè mất bản trước
await withFileLock(FILE_LOCK, async () => {
const f = await readFileStore();
f.profiles[profile] = a;
await writeFileStore(f);
});
return "file";
}
}
export async function loadAuth(profile: string): Promise<StoredAuth | null> {
try {
const v = entry(profile).getPassword();
if (v) return JSON.parse(v);
} catch { /* không có store: thử file */ }
return (await readFileStore()).profiles[profile] ?? null;
}
export async function clearAuth(profile: string): Promise<void> {
try { entry(profile).deletePassword(); } catch { /* bỏ qua */ }
await withFileLock(FILE_LOCK, async () => {
const f = await readFileStore();
if (profile in f.profiles) {
delete f.profiles[profile]; // chỉ xoá profile này, không đụng profile khác
await writeFileStore(f);
}
});
}
Ghi chú:
- Linux: nếu không ghim,
@napi-rs/keyringthử Secret Service trước rồi âm thầm rơi về kernel keyutils. Keyutils nằm trong bộ nhớ kernel, mất sau khi reboot, nên dev bị "đăng xuất bí ẩn". Ghim{ linux: { store: "secret-service" } }thì constructor ném lỗi rõ ràng khi không có Secret Service (container, server SSH), và ta fallback sang file kèm một dòng cảnh báo "token được lưu ở ~/.config/devcli/auth.json, quyền 0600". - Windows: Credential Manager giới hạn kích thước blob khoảng 2560 byte. Access token JWT cộng refresh token dễ vượt, nên
forStore()bỏ access token khi quá lớn; lệnh tiếp theo sẽ refresh để lấy access token mới (Ngày 4, Phần 1). - File fallback có
version: 1và mapprofiles{}, đúng schema ở Ngày 2, Phần 2 (mục 3);expiresAtlà epoch ms.logout --profile workchỉ xoá đúng profilework. - Ghi nguyên tử: ghi file tạm quyền 0600 →
fsync→renameđè lênauth.json; lỗi ở bất kỳ bước nào thì xoá file tạm. Ghi đè thẳng rồi mớichmodđể lộ token trong khoảng file cũ còn quyền 0644, và tiến trình bị kill giữa chừng để lại nửa JSON.renametrong cùng thư mục là atomic trên POSIX; trên Windows nó có thể lỗiEPERM/EBUSYkhiauth.jsonđang bị tiến trình khác mở, nênrenameWithRetrythử lại vài lần. - Khoá chung cho
auth.json: mọi profile nằm chung một file, nênsaveAuth(nhánh file) vàclearAuthbọc đọc-sửa-ghi bằngwithFileLock(auth.json.lock). Thiếu khoá, hai profile refresh cùng lúc thì bản ghi sau đè bản trước; refresh token vừa xoay của profile kia mất, lần sau CLI gửi token cũ và kích hoạt reuse detection.withFileLocknằm tronglock.ts, giải thích ở Ngày 4, Phần 1. - File hỏng: đổi tên thành
auth.json.bakvà báo người dùng, không trả{ profiles: {} }âm thầm. Nuốt lỗi thì lầnsaveAuthkế tiếp ghi đè file và xoá sạch các profile khác. - Không bao giờ log nội dung
StoredAuth. Khi debug, chỉ in profile,expiresAtvà 4 ký tự cuối của token (…a1b2). Prefix của JWT chỉ là header, không giúp nhận diện token nào.
6. Ghép lại: loginDevice, whoami, logout
// commands.ts
import { AUTH, CLIENT_ID, requestDeviceCode } from "./oauth.js";
import { pollForToken, LoginError } from "./poll.js";
import { saveAuth, loadAuth, clearAuth } from "./store.js";
const DEFAULT_SCOPE = "openid offline_access deploy:read"; // deploy:write xin bằng step-up (Ngày 4, Phần 1)
export async function loginDevice(opts: { profile: string; noBrowser: boolean }) {
if (process.env.CI) {
console.error("Không dùng `devcli login` trong CI. Đặt DEVCLI_TOKEN hoặc dùng OIDC federation.");
process.exit(2);
}
const ac = new AbortController();
const onSigint = () => ac.abort();
process.once("SIGINT", onSigint);
try {
const dc = await requestDeviceCode(DEFAULT_SCOPE, ac.signal);
const url = dc.verification_uri_complete ?? dc.verification_uri;
console.error(`! Mở trình duyệt tại ${dc.verification_uri}\n và nhập mã: ${dc.user_code}`);
if (!opts.noBrowser && !isHeadless()) openBrowser(url); // URL đã được in ở dòng trên
console.error("\nĐang chờ xác nhận... (Ctrl+C để huỷ)");
const t = await pollForToken(dc, ac.signal);
process.off("SIGINT", onSigint); // poll xong: trả Ctrl+C về mặc định cho bước userinfo/saveAuth
if (!t.refresh_token) throw new LoginError("Server không trả refresh token (thiếu scope offline_access?).");
const me = await userinfo(t.access_token);
const where = await saveAuth(opts.profile, {
issuer: AUTH, userId: me.id, email: me.email, team: me.team, scope: t.scope ?? DEFAULT_SCOPE,
refreshToken: t.refresh_token, accessToken: t.access_token,
expiresAt: Date.now() + t.expires_in * 1000,
});
console.error(`✓ Đã đăng nhập: ${me.email} (profile: ${opts.profile}, team: ${me.team})`);
if (where === "file") console.error(" Cảnh báo: token được lưu ở file auth.json (quyền 0600), không phải keychain.");
} catch (e) {
if (ac.signal.aborted) { console.error("\nĐã huỷ."); process.exit(130); }
if (e instanceof LoginError) { console.error(e.message); process.exit(1); }
// Lỗi mạng, 5xx, lỗi ghi store: in thông báo thay vì unhandled rejection
console.error(`Đăng nhập thất bại: ${(e as Error).message}`);
process.exit(1);
}
}
export async function whoami(profile: string) {
const a = await loadAuth(profile);
if (!a) { console.error(`Chưa đăng nhập profile ${profile}. Chạy \`devcli login\`.`); process.exit(1); }
// Bài này chưa có refresh; Ngày 4, Phần 1 thay hai dòng dưới bằng getValidAuth(profile)
if (!a.accessToken || a.expiresAt - Date.now() < 60_000) { console.error("Access token hết hạn, cần refresh (Ngày 4, Phần 1)."); process.exit(1); }
const me = await userinfo(a.accessToken);
console.log(`${me.email} profile=${profile} team=${a.team} token=…${a.refreshToken.slice(-4)}`);
}
export async function logout(profile: string) {
if (process.env.DEVCLI_TOKEN) console.error("Cảnh báo: DEVCLI_TOKEN đang được đặt, logout không ảnh hưởng tới token này.");
const a = await loadAuth(profile);
if (a?.refreshToken) {
// RFC 7009: revoke refresh token; server thường revoke cả access token liên quan
try {
const res = await fetch(`${AUTH}/revoke`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ token: a.refreshToken, token_type_hint: "refresh_token", client_id: CLIENT_ID }),
signal: AbortSignal.timeout(5_000),
});
if (!res.ok) console.error(`Cảnh báo: server trả HTTP ${res.status}, chưa revoke được token ở server.`);
} catch {
console.error("Cảnh báo: không liên lạc được server, chưa revoke được token ở server.");
}
}
await clearAuth(profile); // vẫn xoá local dù revoke thất bại
console.error(`Đã đăng xuất profile ${profile}.`);
}
userinfo() gọi GET https://api.example.com/v1/me với header Authorization: Bearer <token> và trả { id, email, team }. whoami phải in rõ team/scope đang dùng: đây là lệnh đầu tiên người dùng chạy khi gặp Not authorized (Ngày 4, Phần 2).
Exit code nên ổn định để script bọc ngoài dùng được: 0 thành công, 1 lỗi đăng nhập, 2 sai cách dùng, 130 bị Ctrl+C.
7. Lỗi hay gặp khi viết CLI client
| Lỗi | Hậu quả | Cách đúng |
|---|---|---|
Poll ngay lập tức, không chờ interval lần đầu | Server trả slow_down từ lần đầu | Ngủ interval trước mỗi request |
In token ra stdout khi --verbose | Token lọt vào log CI, lịch sử terminal | Che token, chỉ in 4 ký tự cuối (…a1b2) |
| Ghi đè thẳng file token (quyền mặc định 0644) | Người dùng khác đọc được; bị kill giữa chừng thì còn nửa JSON | File tạm mode: 0o600 → fsync → rename |
logout chỉ xoá local | Refresh token vẫn dùng được nếu đã bị sao chép | Gọi revoke (RFC 7009) có timeout, cảnh báo nếu thất bại, rồi xoá local |
Mở URL bằng cmd /c start trên Windows | & trong URL bị cmd.exe hiểu là nối lệnh | rundll32 url.dll,FileProtocolHandler <url> |
| Tự mở trình duyệt trong phiên SSH | Mở trên máy chủ từ xa, người dùng không thấy | Phát hiện headless, chỉ in URL |
Không phân biệt access_denied với expired_token | Người dùng không biết nên làm gì | Mỗi mã một thông báo và hướng dẫn |
Phần 3: Device flow với IdP có sẵn
1. Khi nào dùng IdP có sẵn thay vì tự xây
Ở Phần 1 của bài này ta tự xây authorization server để hiểu cơ chế. Trong thực tế, nếu công ty đã có IdP (Auth0, Okta, Entra ID, Keycloak), nên bật device flow ở đó:
| Tự xây (Phần 1) | Dùng IdP có sẵn |
|---|---|
| Kiểm soát hoàn toàn trang consent, data model | Trang consent, MFA, SSO, Conditional Access có sẵn |
| Tự chịu trách nhiệm bảo mật, audit, rate limit | IdP lo phần lớn; bạn cấu hình policy |
| Phù hợp khi sản phẩm của bạn là IdP (như một nền tảng cloud) | Phù hợp khi CLI chỉ là một client của IdP công ty |
ACME Cloud quyết định: DevCLI dùng IdP riêng (đã xây ở Phần 1) cho khách hàng bên ngoài, còn công cụ nội bộ acme-ops của nhân viên dùng IdP doanh nghiệp. Vì vậy DevCLI cần một lớp adapter.
2. Bảng so sánh nhanh
| IdP | Device authorization endpoint | Cách bật | Điểm lệch cần nhớ |
|---|---|---|---|
| Auth0 | https://{domain}/oauth/device/code | Application type Native, Grant Types có Device Code, Token Endpoint Auth Method = None, OIDC Conformant | Gọi API riêng phải gửi audience; không hỗ trợ confidential client |
| Okta | https://{okta-domain}/oauth2/default/v1/device/authorize (custom AS) | App Native OIDC, grant Device Authorization; với custom authorization server phải bật grant ở policy rule | Chỉ hỗ trợ native app |
| Microsoft Entra ID | https://login.microsoftonline.com/{tenant}/oauth2/v2.0/devicecode | Public client flows | Không trả verification_uri_complete; trả thêm message; mã lỗi authorization_declined, bad_verification_code |
| GitHub (OAuth app, GitHub App) | POST https://github.com/login/device/code | Phải bật "Device flow" trong settings của app | Token endpoint là https://github.com/login/oauth/access_token; có lỗi riêng device_flow_disabled, incorrect_device_code; mã sống 900 giây |
| Keycloak | /realms/{realm}/protocol/openid-connect/auth/device | Bật OAuth 2.0 Device Authorization Grant trên client | Gần chuẩn RFC; trang verify có thể đặt sau URL ngắn của bạn |
| Amazon Cognito user pool | Không có | Không hỗ trợ native | Xem mục 6 |
Thông tin trong bảng đã được đối chiếu với tài liệu chính thức ở mục Tài liệu tham khảo. Giao diện console của từng IdP thay đổi theo thời gian; tên menu có thể khác, nên kiểm tra docs bản hiện hành khi cấu hình.
3. Auth0 và Okta
Auth0 yêu cầu:
- Application type là Native, bật OIDC Conformant, Token Endpoint Authentication Method là None.
- Grant Types của application có Device Code (và Refresh Token nếu cần refresh).
- Khi xin token để gọi API riêng (
https://api.example.com), request tới/oauth/device/codephải cóaudience. Muốn có refresh token thì thêm scopeoffline_accessvà bật Allow Offline Access ở API.
POST https://{yourDomain}/oauth/device/code
Content-Type: application/x-www-form-urlencoded
client_id=<client_id>&scope=openid%20offline_access%20deploy:write&audience=https%3A%2F%2Fapi.example.com
Docs Auth0 cũng liệt kê giới hạn: không hỗ trợ client tạo bằng Dynamic Client Registration, không cho Rules/Actions đọc query string của trang login trong flow này, không hỗ trợ account linking.
Okta:
- Tạo app OIDC → Native Application, chọn grant Device Authorization và Refresh Token.
- Nếu dùng custom authorization server (ví dụ
default), vào Access Policies, sửa rule và tick Device Authorization; dùng org authorization server thì bỏ qua bước này. - Request:
POST https://{yourOktaDomain}/oauth2/default/v1/device/authorize.
Cả hai đều trả response đúng dạng RFC 8628 (device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval), nên vòng polling ở Phần 2 của bài này dùng lại nguyên vẹn.
4. Microsoft Entra ID và GitHub: những chỗ lệch chuẩn
Entra ID:
POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/devicecode
client_id=<client_id>&scope=user.read%20openid%20profile
→ { "user_code", "device_code", "verification_uri", "expires_in", "interval", "message" }
- Không có
verification_uri_complete: CLI không thể mở link đã điền sẵn mã. In cả URL và mã, hoặc in nguyênmessage(đã được bản địa hoá). - Token request dùng đúng
grant_type=urn:ietf:params:oauth:grant-type:device_code, nhưng mã lỗi khác: người dùng từ chối làauthorization_declined(không phảiaccess_denied), mã sai làbad_verification_code. Mặc định người dùng có 15 phút. - Microsoft xếp device code flow là luồng rủi ro cao vì hay bị dùng trong phishing, và khuyến nghị chặn bằng Conditional Access (Authentication flows) ở mọi nơi có thể, chỉ cho phép khi thật sự cần. Liên hệ Ngày 2, Phần 3.
GitHub (OAuth app hoặc GitHub App):
- Phải bật "Device flow" trong settings của app; nếu quên, token endpoint trả
device_flow_disabled. - Response mẫu:
user_codedạngWDJB-MJHT,verification_urilàhttps://github.com/login/device,expires_in900,interval5. - Gửi header
Accept: application/json, vì mặc định token endpoint của GitHub có thể trả dạng form-encoded. - Có thêm mã lỗi riêng như
incorrect_client_credentials,incorrect_device_code,device_flow_disabled.slow_downcộng 5 giây vào interval, giống RFC.
Bài học thiết kế: vòng polling nên coi mọi mã lạ là lỗi dừng (RFC 8628 §3.5), và có bảng ánh xạ mã lỗi theo provider để hiển thị thông báo dễ hiểu.
5. AWS IAM Identity Center và aws sso login
Đây là ví dụ tốt về việc một CLI lớn đổi flow mặc định:
| Phiên bản AWS CLI v2 | Flow mặc định của aws sso login / aws configure sso |
|---|---|
| Trước 2.22.0 | Device authorization |
| Từ 2.22.0 | Authorization Code + PKCE, cần trình duyệt trên cùng máy |
- Muốn dùng lại device flow trên bản mới, thêm
--use-device-code(ví dụ khi SSH vào máy không có trình duyệt). --no-browsertắt việc tự mở trình duyệt.- Với PKCE, CLI chạy callback server trên localhost;
--redirect-portchọn cổng cụ thể, mặc định lấy cổng ngẫu nhiên còn trống. Đây đúng là loopback redirect của Ngày 2, Phần 1.
Vì sao đổi? Loopback + PKCE buộc phiên đăng nhập hoàn tất trên chính máy chạy CLI, nên kẻ tấn công không thể gửi cho nạn nhân một mã để nhập từ xa như với device code phishing. Device flow vẫn được giữ cho trường hợp headless. DevCLI học theo: loopback mặc định khi có trình duyệt, device flow khi chạy devcli login --device hoặc phát hiện headless (cờ --use-device-code là của AWS CLI, DevCLI dùng --device).
6. Amazon Cognito: không có device flow native
Tài liệu Cognito liệt kê ba loại grant cho user pool: authorization code, implicit và client credentials. Không có device authorization grant. Các lựa chọn:
Lựa chọn B chính là server của Phần 1, chỉ thay bước "người dùng đã đăng nhập" bằng một lần đăng nhập Cognito trên trình duyệt. Hãy cân nhắc kỹ: bạn tự chịu trách nhiệm về state machine, rate limit và chống phishing, và token cấp cho CLI là token của service bạn (hoặc token Cognito được service chuyển tiếp — khi đó service đang giữ token người dùng, tăng phạm vi rủi ro).
7. Provider adapter trong DevCLI
export interface DeviceProvider {
name: string;
deviceCodeUrl: string;
tokenUrl: string;
extraParams?: Record<string, string>; // ví dụ audience cho Auth0
mapError(error: string): "pending" | "slow_down" | "denied" | "expired" | "fatal";
}
export const entra: DeviceProvider = {
name: "entra",
deviceCodeUrl: "https://login.microsoftonline.com/<tenant>/oauth2/v2.0/devicecode",
tokenUrl: "https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token",
mapError: (e) =>
e === "authorization_pending" ? "pending"
: e === "slow_down" ? "slow_down"
: e === "authorization_declined" ? "denied"
: e === "expired_token" ? "expired"
: "fatal",
};
export const github: DeviceProvider = {
name: "github",
deviceCodeUrl: "https://github.com/login/device/code",
tokenUrl: "https://github.com/login/oauth/access_token",
mapError: (e) =>
e === "authorization_pending" ? "pending"
: e === "slow_down" ? "slow_down"
: e === "access_denied" ? "denied"
: e === "expired_token" ? "expired"
: "fatal", // device_flow_disabled, incorrect_device_code, ...
};
Vòng polling ở Phần 2 của bài này chỉ cần gọi provider.mapError(body.error) thay vì switch trực tiếp trên chuỗi. Request luôn gửi Accept: application/json để GitHub trả JSON.
8. Tự phát hiện endpoint và lỗi hay gặp khi tích hợp
Thay vì viết cứng URL, CLI nên đọc metadata của authorization server. RFC 8628 đăng ký trường device_authorization_endpoint trong metadata của RFC 8414, và nhiều IdP OIDC công bố nó trong /.well-known/openid-configuration.
async function discover(issuer: string) {
const res = await fetch(new URL("/.well-known/openid-configuration", issuer));
const meta = await res.json();
if (!meta.device_authorization_endpoint) {
throw new Error(`${issuer} không công bố device_authorization_endpoint`);
}
return { deviceCodeUrl: meta.device_authorization_endpoint, tokenUrl: meta.token_endpoint };
}
Lưu ý: không phải IdP nào cũng công bố trường này (GitHub không phải OIDC provider cho người dùng và có endpoint riêng). Adapter nên ưu tiên discovery, rồi mới fallback sang URL cấu hình tay.
| Lỗi hay gặp | Triệu chứng | Cách xử lý |
|---|---|---|
| Quên bật grant/Device flow trên app | unauthorized_client, device_flow_disabled hoặc lỗi tương đương ngay ở bước đầu | Bật grant trong console IdP; ghi bước này vào runbook triển khai |
| Tạo app loại Web thay vì Native | IdP từ chối device grant | Auth0 và Okta yêu cầu application type Native |
Thiếu offline_access | Login được nhưng không có refresh token, người dùng phải đăng nhập lại mỗi giờ | Thêm scope và bật cấu hình cho phép offline access |
Thiếu audience (Auth0) | Token không gọi được API riêng | Gửi audience bằng Identifier của API |
In verification_uri_complete khi provider không trả | Link undefined trên terminal | Fallback về verification_uri + user_code |
| Viết cứng mã lỗi theo một provider | Không nhận ra người dùng từ chối trên provider khác | Adapter mapError theo provider |
Không gửi Accept: application/json | Parse lỗi với GitHub | Luôn gửi header này |
9. Kiểm thử end-to-end với nhiều IdP
Mỗi adapter cần ít nhất ba kịch bản test trên một tenant thử nghiệm của IdP tương ứng:
| Kịch bản | Thao tác trên trình duyệt | Kết quả CLI mong đợi |
|---|---|---|
| Duyệt | Nhập mã, bấm cho phép | Exit 0, lưu token, whoami đúng tài khoản |
| Từ chối | Nhập mã, bấm từ chối | Exit 1, thông báo "đã bị từ chối" (dù provider dùng mã lỗi nào) |
| Bỏ mặc | Không làm gì | Exit 1 sau expires_in, thông báo "mã đã hết hạn" |
Chạy bộ test này mỗi khi nâng cấp CLI hoặc khi IdP thông báo thay đổi API. Tenant thử nghiệm phải tách khỏi tenant production và không dùng tài khoản thật của nhân viên.
Câu hỏi ôn tập
-
Vì sao server nên lưu
sha256(device_code)thay vì bản rõ, trong khiuser_codelại lưu bản rõ?Xem đáp án
device_codelà bearer secret: ai cầm được nó vàclient_idlà đổi được token sau khi người dùng duyệt. Lưu hash nghĩa là dump Redis, backup hay log rò rỉ không đủ để đổi token, giống cách lưu refresh token.user_codethì người dùng phải gõ lại trên trang/device, server cần tra trực tiếp theo giá trị đã chuẩn hoá. Entropy củauser_codethấp nên bảo vệ nó bằng TTL ngắn, rate limit nhập sai và xoá ngay sau khi dùng, không phải bằng hash. -
Hai request
POST /tokencủa cùng một CLI đến gần như đồng thời khi phiên vừaapproved. Thiết kế nào đảm bảo chỉ một token được phát?Xem đáp án
Dùng một khoá one-time như
SET used:{hash} 1 NX EX 600. Lệnh này atomic trong Redis nên chỉ một request thắng; request kia nhậninvalid_grant. Nếu chỉ dựa vào "đọc status rồi xoá key", hai request có thể cùng đọcapprovedtrước khi bất kỳ request nào kịp xoá, dẫn tới phát hai bộ token cho một lần duyệt. -
Server nhận request poll cách lần trước 2 giây trong khi
intervalcủa phiên là 5 giây. Server phải làm gì, và client phải phản ứng ra sao?Xem đáp án
Server trả
400vớierror=slow_downvà tăngintervalcủa phiên thêm 5 giây (thành 10). Theo RFC 8628 §3.5, client phải tăng khoảng chờ thêm 5 giây cho lần này và mọi lần sau, rồi tiếp tục poll.slow_downkhông phải lỗi dừng; chỉauthorization_pendingvàslow_downcho phép tiếp tục poll. -
Vì sao endpoint
/device/approvecần CSRF token, trong khi flow này không có redirect về client?Xem đáp án
/device/approvelà thao tác thay đổi trạng thái do người dùng đã đăng nhập thực hiện bằng cookie session. Một trang độc có thể dựng form tự submitdecision=allowcùnguser_codedo kẻ tấn công tạo, khiến trình duyệt nạn nhân duyệt phiên của kẻ tấn công mà không hề thấy trang consent. CSRF token (hoặc SameSite=Strict cho cookie phiên trên trang này) chặn kiểu tấn công đó. -
Trang
/devicenên trả thông báo gì khiuser_codesai, và vì sao không nên phân biệt "sai" với "hết hạn"?Xem đáp án
Trả một thông báo chung kiểu "Mã không hợp lệ hoặc đã hết hạn", HTTP 404, và đếm số lần sai để khoá tạm (429). Nếu phân biệt "hết hạn" với "không tồn tại", kẻ đoán mã biết được mã nào từng tồn tại, thu hẹp không gian đoán và lộ thông tin về hoạt động của người khác.
-
Vì sao CLI phải ngủ
intervaltrước request/tokenđầu tiên, thay vì gọi ngay sau khi in mã?Xem đáp án
RFC 8628 §3.5 yêu cầu client chờ ít nhất
intervalgiây trước mỗi request token. Người dùng cũng không thể duyệt trong vài trăm mili giây đầu. Gọi ngay chỉ tạo request thừa và có thể nhậnslow_down, làmintervalcủa cả phiên tăng thêm 5 giây. -
Trong lúc polling, request bị timeout mạng. Client nên làm gì, và khác gì so với khi nhận
expired_token?Xem đáp án
Timeout mạng không phải phản hồi của server, nên client tiếp tục poll nhưng lùi dần khoảng chờ (exponential backoff), vẫn trong thời hạn
expires_in.expired_tokenlà phản hồi chính thức rằng phiên đã kết thúc; client phải dừng ngay, báo người dùng và gợi ý chạy lạilogin. -
Vì sao ví dụ dùng
@napi-rs/keyringthay vìkeytar, và cần làm gì khi keychain không khả dụng?Xem đáp án
Repo
keytarđã bị archived từ 12/2022, không còn bảo trì.@napi-rs/keyringlà binding Node củakeyring-rs, còn phát hành bản mới. Trên Linux phải ghimstore: "secret-service": nếu không, thư viện âm thầm rơi về kernel keyutils (mất khi reboot) thay vì báo lỗi. Khi đã ghim mà không có Secret Service (container, server SSH), constructor ném lỗi; CLI fallback sang file~/.config/devcli/auth.jsonquyền 0600 (thư mục 0700), lưu theoprofiles{}, và in cảnh báo cho người dùng biết. -
devcli logoutgọi endpoint revoke nhưng server không phản hồi. CLI có nên giữ lại token local để thử lại sau không?Xem đáp án
Không. Ý định của người dùng là "máy này không còn đăng nhập", nên CLI vẫn xoá token local, đồng thời in cảnh báo rằng không revoke được ở server. Nếu nghi token bị lộ, người dùng revoke phiên từ trang quản lý tài khoản trên web. Giữ token local chỉ để thử revoke lại sẽ trái với kỳ vọng và kéo dài rủi ro.
-
Vì sao
devcli loginnên từ chối chạy khi biếnCIđược set?
Xem đáp án
Device flow cần một người thật mở trình duyệt và bấm duyệt. Trong CI không có ai làm việc đó, job sẽ treo đến khi mã hết hạn. Tệ hơn, người ta có thể bị lừa duyệt mã in trong log CI. CI nên dùng token máy hoặc OIDC federation (Ngày 4, Phần 1), và CLI nên báo lỗi rõ ràng ngay lập tức.
- Một CLI viết cứng
case "access_denied"để báo người dùng đã từ chối. Khi chuyển sang Entra ID, người dùng bấm từ chối thì chuyện gì xảy ra?
Xem đáp án
Entra ID trả authorization_declined, không phải access_denied. Nếu CLI xử lý đúng RFC 8628 (mọi mã ngoài authorization_pending/slow_down là lỗi dừng) thì CLI vẫn dừng nhưng hiện thông báo chung chung. Nếu CLI sai kiểu "mã lạ thì tiếp tục poll", nó sẽ poll đến khi hết hạn. Cách đúng là adapter ánh xạ mã lỗi theo provider.
- Vì sao AWS CLI v2 từ bản 2.22.0 chuyển
aws sso loginsang Authorization Code + PKCE làm mặc định?
Xem đáp án
Với loopback redirect, mã ủy quyền được trả về callback server trên chính máy chạy CLI, nên phiên đăng nhập gắn với máy đó. Device flow cho phép hoàn tất trên một thiết bị bất kỳ, chính đặc điểm mà device code phishing lợi dụng. Device flow vẫn được giữ qua --use-device-code cho môi trường không có trình duyệt.
- Đội của bạn dùng Amazon Cognito user pool và muốn CLI đăng nhập được khi SSH vào server. Phương án nào phù hợp?
Xem đáp án
Cognito user pool không có device authorization grant (chỉ authorization code, implicit, client credentials). Có ba hướng: (1) nếu có thể mở trình duyệt trên máy cục bộ, dùng loopback + PKCE kết hợp port forwarding; (2) tự dựng một device authorization service như Phần 1, trong đó bước duyệt trên trình duyệt là một lần đăng nhập Cognito; (3) chuyển sang IdP hỗ trợ device flow native. Hướng (2) tốn công và bạn tự chịu trách nhiệm bảo mật.
- Gọi
/oauth/device/codecủa Auth0 thành công nhưng access token nhận được không gọi đượchttps://api.example.com. Thiếu gì?
Xem đáp án
Thiếu tham số audience bằng Identifier của API trong Auth0. Không có audience, Auth0 chỉ cấp token phục vụ lấy thông tin người dùng (userinfo), không dành cho API riêng. Nếu cần refresh token thì thêm scope offline_access và bật Allow Offline Access cho API.
- Vì sao CLI nên gửi
Accept: application/jsonkhi gọi token endpoint của GitHub?
Xem đáp án
Token endpoint của GitHub hỗ trợ nhiều định dạng phản hồi, chọn theo header Accept. Thiếu header này, CLI có thể nhận dữ liệu không phải JSON và res.json() sẽ lỗi. Gửi rõ Accept: application/json giúp vòng polling dùng chung cho mọi provider.
Bài tập thực hành
Bài 1: Quan sát slow_down
Chạy đoạn server ở mục 4 và 6 với Redis local (docker run -p 6379:6379 redis:7). Gọi POST /device/code bằng curl, rồi poll /token mỗi 2 giây.
Đầu ra mong đợi: lần poll thứ hai trở đi nhận slow_down; HGET dc:{hash} interval tăng dần 10, 15, 20.
Bài 2: Race khi phát token
Viết test cho race condition: sau khi set status=approved, bắn 20 request /token song song (Promise.all).
Đầu ra mong đợi: đúng 1 response 200 chứa token. 19 response còn lại là 400 với invalid_grant, slow_down, hoặc expired_token (request đến sau khi dc:{hash} đã bị xoá).
Bài 3: Rate limit trang nhập mã
Bổ sung rate limit cho trang nhập mã: tối đa 5 lần sai mỗi 15 phút theo session.
Đầu ra mong đợi: lần sai thứ 6 nhận 429; tính lại xác suất đoán trúng một user_code 8 ký tự base-20 với giới hạn này trong expires_in = 600 giây (áp dụng công thức ở Ngày 1, Phần 3).
Bài 4: Đăng nhập end-to-end với server Phần 1
Chạy devcli login --device với server Phần 1. Ở cửa sổ khác, đặt status=approved bằng redis-cli HSET dc:{hash} status approved user_id u_123.
Đầu ra mong đợi: CLI in "Đã đăng nhập", keychain (Keychain Access trên macOS) có mục devcli, và devcli whoami in email cùng team.
Bài 5: Kiểm chứng slow_down
Sửa server để luôn trả slow_down 3 lần đầu, rồi mới trả token. Đo thời gian thực tế giữa các request.
Đầu ra mong đợi: khoảng cách lần lượt khoảng 5, 10, 15, 20 giây; không lần nào quay về 5 giây.
Bài 6: Fallback file trong container
Chạy devcli login --device trong container Linux không có Secret Service (store đã ghim secret-service), rồi đăng nhập thêm --profile work và devcli logout --profile work.
Đầu ra mong đợi: CLI in cảnh báo fallback; ~/.config/devcli/auth.json có quyền -rw-------, thư mục drwx------; file chứa profiles.default và sau khi logout không còn profiles.work nhưng profiles.default vẫn nguyên.
Bài 7: Adapter GitHub khi chưa bật Device flow
Tạo một GitHub OAuth app thử nghiệm, chưa bật Device flow, và chạy vòng polling của DevCLI với adapter github.
Đầu ra mong đợi: CLI dừng ngay với thông báo dịch từ device_flow_disabled; sau khi bật Device flow trong settings, đăng nhập thành công.
Bài 8: Adapter Auth0 và Keycloak
Viết adapter auth0 (có extraParams.audience) và keycloak (endpoint /realms/{realm}/protocol/openid-connect/auth/device).
Đầu ra mong đợi: cùng một hàm pollForToken chạy được với ba provider; unit test cho mapError của mỗi adapter.
Bài 9: Đề xuất flow mặc định cho DevCLI
Viết đề xuất 1 trang cho ACME: DevCLI dùng loopback + PKCE mặc định hay device flow mặc định?
Đầu ra mong đợi: bảng so sánh rủi ro phishing, trải nghiệm SSH/container, yêu cầu cấu hình IdP; kết luận có lý do, tham chiếu cách AWS CLI v2 đã chọn.
Tài liệu tham khảo
- RFC 8628 — OAuth 2.0 Device Authorization Grant
- RFC 6749 §5.2 — Error Response
- RFC 8414 — OAuth 2.0 Authorization Server Metadata
- Redis SET command (NX, EX)
- RFC 9700 — OAuth 2.0 Security Best Current Practice
- RFC 8628 §3.4–3.5 — Device Access Token Request/Response
- RFC 7009 — OAuth 2.0 Token Revocation
- @napi-rs/keyring (keyring-node)
- atom/node-keytar (archived)
- AWS CLI
sso login— tuỳ chọn--no-browser,--use-device-code - Auth0 — Device Authorization Flow
- Auth0 — Call Your API Using the Device Authorization Flow
- Okta — Configure Device Authorization Grant Flow
- Microsoft Entra — OAuth 2.0 device authorization grant
- Microsoft Entra — Conditional Access: Authentication flows
- GitHub — Authorizing OAuth apps (Device flow)
- GitHub — Generating a user access token for a GitHub App
- Keycloak Server Administration Guide — Device authorization grant
- AWS CLI — Configure IAM Identity Center authentication
- AWS CLI —
aws sso login - Amazon Cognito — OAuth 2.0 grants