Bad CLI request
missing/invalid redirect_uri, state, or code_challenge.
// `logicsrc login` OAuth-style flow (authorization code + PKCE + loopback):
// GET /cli/authorize browser lands here (login required) → approve page
// POST /cli/authorize approve → mint a code, redirect to the CLI's loopback
// POST /cli/token CLI exchanges code + verifier → an lsk_ API key (bearer)
// GET /api/me Bearer → who am I (for `logicsrc whoami`)
//
// …and the device-authorization flow, for CLIs on a machine with no browser
// (SSH, droplets, containers) where a 127.0.0.1 redirect_uri is unreachable:
// POST /cli/device/code CLI asks for a device_code + short user_code
// GET /cli/device human opens this anywhere, types/confirms the code
// POST /cli/device approve (or deny) the pending code
// POST /cli/device/token CLI polls with device_code → an lsk_ API key
import { Router } from "express";
import crypto from "node:crypto";
import { get, run } from "../db.mjs";
import { token, sha256 } from "../lib/crypto.mjs";
import { page, footer, appBar, esc } from "../lib/html.mjs";
import { requireAuth, csrfInput } from "../lib/session.mjs";
import { createApiKey, bearer, keyForBearer } from "../lib/apikey.mjs";
import { requestOrigin } from "../lib/origin.mjs";
import { config } from "../config.mjs";
export const cliRouter = Router();
// Only loopback redirect URIs are allowed (the CLI listens on 127.0.0.1).
function loopbackOk(uri) {
try {
const u = new URL(uri);
return u.protocol === "http:" && (u.hostname === "127.0.0.1" || u.hostname === "localhost");
} catch { return false; }
}
cliRouter.get("/cli/authorize", requireAuth, (req, res) => {
const { redirect_uri, state, code_challenge } = req.query;
if (!loopbackOk(redirect_uri) || !state || !code_challenge) {
return res.status(400).type("html").send(page({ body: ` missing/invalid redirect_uri, state, or code_challenge. Grant ${esc(name)} on this machine access to manage teams & encrypted credentials as ${esc(req.user.email || req.user.display_name)}. You'll return to your terminal.Bad CLI request
Authorize the LogicSRC CLI
${detail}
logicsrc login again.";
return res.status(code ? 400 : 200).type("html").send(devicePage(req, `Enter the code shown in your terminal.
${problem ? `${problem}
` : ""}Grant ${esc(row.name || "logicsrc cli")} access to manage teams & encrypted credentials as ${esc(req.user.email || req.user.display_name)}.
${esc(row.user_code)}
Only approve this if the code matches the one in your terminal.
logicsrc login again for a fresh code.");
await run(`UPDATE cli_device_codes SET status = ?, user_id = ? WHERE user_code = ?`, [deny ? "denied" : "approved", req.user.id, code]);
return deny
? deviceResult(req, res, 200, "Denied", "Nothing was granted. You can close this tab.")
: deviceResult(req, res, 200, `You're in.`, "Return to your terminal — you can close this tab.");
});
cliRouter.post("/cli/device/token", async (req, res) => {
const deviceCode = req.body?.device_code;
if (!deviceCode) return res.status(400).json({ error: "invalid_request" });
const row = await get(`SELECT * FROM cli_device_codes WHERE device_code_hash = ?`, [sha256(String(deviceCode))]);
if (!row) return res.status(400).json({ error: "invalid_grant" });
const now = Date.now();
// Rate-limit impatient pollers, per the device-flow convention.
const tooSoon = row.last_polled_at && now - row.last_polled_at < (DEVICE_POLL_SECONDS - 1) * 1000;
await run(`UPDATE cli_device_codes SET last_polled_at = ? WHERE device_code_hash = ?`, [now, row.device_code_hash]);
if (tooSoon) return res.status(400).json({ error: "slow_down", interval: DEVICE_POLL_SECONDS });
if (row.status === "used") return res.status(400).json({ error: "invalid_grant" });
if (row.status === "denied") return res.status(400).json({ error: "access_denied" });
if (row.expires_at < now) return res.status(400).json({ error: "expired_token" });
if (row.status !== "approved") return res.status(400).json({ error: "authorization_pending", interval: DEVICE_POLL_SECONDS });
await run(`UPDATE cli_device_codes SET status = 'used' WHERE device_code_hash = ?`, [row.device_code_hash]);
const user = await get(`SELECT * FROM users WHERE id = ?`, [row.user_id]);
if (!user) return res.status(400).json({ error: "invalid_grant" });
const { plaintext } = await createApiKey(user.id, row.name || "logicsrc cli");
res.json({ access_token: plaintext, token_type: "bearer", user: { id: user.id, email: user.email || null, name: user.display_name } });
});
cliRouter.get("/api/me", async (req, res) => {
const found = await keyForBearer(bearer(req));
if (!found) return res.status(401).json({ error: "invalid, revoked, expired or missing API key" });
// /api/me answers "which person is this" -- a machine key is not one. It asks
// /api/credshare/me, which describes the key and its scope instead.
if (found.key.kind === "machine") return res.status(403).json({ error: "A machine API key has no person to describe. Use /api/credshare/me.", code: "machine_key_forbidden" });
const { user } = found;
res.json({ id: user.id, email: user.email || null, name: user.display_name });
});