feat(auth): add operator account CLI
- Add local and container-ready user management and token commands. - Document setup and verify commands against an isolated database.
This commit is contained in:
1 parent
fe19fb9d56
commit
768a799db0
6 files changed
+570
No files matched your search
@@ -10,6 +10,7 @@
|
||||
"migration:run": "node dist/database/migrate",
|
||||
"migration:show": "typeorm migration:show -d dist/database/data-source.js",
|
||||
"migration:generate": "typeorm migration:generate -d dist/database/data-source.js",
|
||||
"cli": "node dist/cli.js",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import "reflect-metadata";
|
||||
import dataSource from "./database/data-source";
|
||||
import { validateAppConfig } from "./config/app.config";
|
||||
import { PasswordService } from "./auth/password.service";
|
||||
import {
|
||||
OperatorCliError,
|
||||
createTerminalInput,
|
||||
runOperatorCommand,
|
||||
} from "./operator-cli/operator-cli";
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const config = validateAppConfig(process.env);
|
||||
if (!config.AUTH_ENABLED) {
|
||||
throw new OperatorCliError(
|
||||
"Operator account commands require AUTH_ENABLED=true.",
|
||||
);
|
||||
}
|
||||
|
||||
await dataSource.initialize();
|
||||
try {
|
||||
await runOperatorCommand(process.argv.slice(2), {
|
||||
dataSource,
|
||||
config,
|
||||
passwords: new PasswordService(),
|
||||
input: createTerminalInput(),
|
||||
output: { write: (message) => process.stdout.write(message) },
|
||||
});
|
||||
} finally {
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
if (error instanceof OperatorCliError) {
|
||||
console.error(error.message);
|
||||
} else if (
|
||||
error instanceof Error &&
|
||||
error.message === "This command requires an interactive terminal."
|
||||
) {
|
||||
console.error(error.message);
|
||||
} else {
|
||||
console.error(
|
||||
"Operator command failed. Check AUTH_ENABLED, DB_PATH, and that database migrations are up to date.",
|
||||
);
|
||||
}
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { Writable } from "node:stream";
|
||||
|
||||
export interface RawInput extends EventEmitter {
|
||||
isTTY?: boolean;
|
||||
isRaw?: boolean;
|
||||
pause(): this;
|
||||
resume(): this;
|
||||
setRawMode?(mode: boolean): this;
|
||||
}
|
||||
|
||||
/** Read a secret without echoing typed characters to the terminal. */
|
||||
export function readHiddenInput(
|
||||
input: RawInput,
|
||||
output: Pick<Writable, "write">,
|
||||
prompt: string,
|
||||
): Promise<string> {
|
||||
if (!input.isTTY || !input.setRawMode) {
|
||||
return Promise.reject(
|
||||
new Error("This command requires an interactive terminal."),
|
||||
);
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let value = "";
|
||||
const previousRawMode = input.isRaw ?? false;
|
||||
const finish = (error?: Error) => {
|
||||
input.off("data", onData);
|
||||
input.setRawMode?.(previousRawMode);
|
||||
input.pause();
|
||||
output.write("\n");
|
||||
if (error) reject(error);
|
||||
else resolve(value);
|
||||
};
|
||||
const onData = (chunk: Buffer | string) => {
|
||||
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;
|
||||
for (const character of text) {
|
||||
if (character === "\u0003") {
|
||||
finish(new Error("Input cancelled."));
|
||||
return;
|
||||
}
|
||||
if (character === "\r" || character === "\n") {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
if (character === "\u007f" || character === "\b") {
|
||||
value = value.slice(0, -1);
|
||||
continue;
|
||||
}
|
||||
value += character;
|
||||
}
|
||||
};
|
||||
|
||||
output.write(prompt);
|
||||
input.setRawMode(true);
|
||||
input.resume();
|
||||
input.on("data", onData);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import type { DataSource, Repository } from "typeorm";
|
||||
import { durationSeconds } from "../common/interval";
|
||||
import type { AppConfig } from "../config/app.config";
|
||||
import { issueJwt, safeUser } from "../auth/jwt.helpers";
|
||||
import { PasswordService } from "../auth/password.service";
|
||||
import { UserEntity } from "../auth/user.entity";
|
||||
|
||||
export interface OperatorCliInput {
|
||||
line(prompt: string): Promise<string>;
|
||||
secret(prompt: string): Promise<string>;
|
||||
}
|
||||
|
||||
export interface OperatorCliOutput {
|
||||
write(message: string): void;
|
||||
}
|
||||
|
||||
export interface OperatorCliContext {
|
||||
dataSource: Pick<DataSource, "getRepository">;
|
||||
config: Pick<
|
||||
AppConfig,
|
||||
"AUTH_ENABLED" | "AUTH_JWT_SECRET" | "AUTH_JWT_EXPIRES_IN"
|
||||
>;
|
||||
passwords: Pick<PasswordService, "hash">;
|
||||
input: OperatorCliInput;
|
||||
output: OperatorCliOutput;
|
||||
}
|
||||
|
||||
export class OperatorCliError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "OperatorCliError";
|
||||
}
|
||||
}
|
||||
|
||||
const USAGE = `Usage:
|
||||
node dist/cli.js user:create
|
||||
node dist/cli.js user:get <username>
|
||||
node dist/cli.js user:delete <username>
|
||||
node dist/cli.js user:token <username> [duration]
|
||||
|
||||
Durations use seconds, minutes, hours, or days (for example: 30m, 1h, 7d).`;
|
||||
|
||||
function validateUsername(raw: string): string {
|
||||
const username = raw.trim();
|
||||
if (!username) throw new OperatorCliError("Username cannot be empty.");
|
||||
if (username.length > 250) {
|
||||
throw new OperatorCliError("Username must be 250 characters or fewer.");
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
function checkEnabled(context: OperatorCliContext): void {
|
||||
if (!context.config.AUTH_ENABLED) {
|
||||
throw new OperatorCliError(
|
||||
"Operator account commands require AUTH_ENABLED=true.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function requireArguments(args: string[], min: number, max: number): void {
|
||||
if (args.length < min || args.length > max) {
|
||||
throw new OperatorCliError(USAGE);
|
||||
}
|
||||
}
|
||||
|
||||
function safeUserJson(user: UserEntity): string {
|
||||
return JSON.stringify(safeUser(user), null, 2);
|
||||
}
|
||||
|
||||
function isUsernameUniqueError(error: unknown): boolean {
|
||||
if (!error || typeof error !== "object") return false;
|
||||
const message = String(error);
|
||||
return (
|
||||
message.includes("SQLITE_CONSTRAINT_UNIQUE") ||
|
||||
message.includes("UNIQUE constraint failed: users.username")
|
||||
);
|
||||
}
|
||||
|
||||
async function createUser(
|
||||
users: Repository<UserEntity>,
|
||||
context: OperatorCliContext,
|
||||
): Promise<void> {
|
||||
const username = validateUsername(await context.input.line("Username: "));
|
||||
if (await users.findOneBy({ username })) {
|
||||
throw new OperatorCliError(`Username "${username}" already exists.`);
|
||||
}
|
||||
|
||||
const password = await context.input.secret("Password: ");
|
||||
if (!password) throw new OperatorCliError("Password cannot be empty.");
|
||||
if (password.length > 1024) {
|
||||
throw new OperatorCliError("Password must be 1024 characters or fewer.");
|
||||
}
|
||||
const confirmation = await context.input.secret("Confirm password: ");
|
||||
if (password !== confirmation) {
|
||||
throw new OperatorCliError("Passwords do not match.");
|
||||
}
|
||||
|
||||
const passwordHash = await context.passwords.hash(password);
|
||||
try {
|
||||
const user = await users.save(users.create({ username, passwordHash }));
|
||||
context.output.write(`Created user ${JSON.stringify(user.username)}.\n`);
|
||||
} catch (error) {
|
||||
if (isUsernameUniqueError(error)) {
|
||||
throw new OperatorCliError(`Username "${username}" already exists.`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function findUser(
|
||||
users: Repository<UserEntity>,
|
||||
username: string,
|
||||
): Promise<UserEntity> {
|
||||
const user = await users.findOneBy({ username: validateUsername(username) });
|
||||
if (!user) throw new OperatorCliError("No account found for that username.");
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function runOperatorCommand(
|
||||
args: string[],
|
||||
context: OperatorCliContext,
|
||||
): Promise<void> {
|
||||
const [command, ...commandArgs] = args;
|
||||
if (command === "--help" || command === "-h") {
|
||||
context.output.write(USAGE + "\n");
|
||||
return;
|
||||
}
|
||||
checkEnabled(context);
|
||||
|
||||
const users = context.dataSource.getRepository(UserEntity);
|
||||
switch (command) {
|
||||
case "user:create":
|
||||
requireArguments(commandArgs, 0, 0);
|
||||
await createUser(users, context);
|
||||
return;
|
||||
case "user:get": {
|
||||
requireArguments(commandArgs, 1, 1);
|
||||
const user = await findUser(users, commandArgs[0]);
|
||||
context.output.write(safeUserJson(user) + "\n");
|
||||
return;
|
||||
}
|
||||
case "user:delete": {
|
||||
requireArguments(commandArgs, 1, 1);
|
||||
const user = await findUser(users, commandArgs[0]);
|
||||
await users.remove(user);
|
||||
context.output.write(`Deleted user ${JSON.stringify(user.username)}.\n`);
|
||||
return;
|
||||
}
|
||||
case "user:token": {
|
||||
requireArguments(commandArgs, 1, 2);
|
||||
const user = await findUser(users, commandArgs[0]);
|
||||
const duration = commandArgs[1] ?? context.config.AUTH_JWT_EXPIRES_IN;
|
||||
const expiresIn = durationSeconds(duration);
|
||||
if (expiresIn === null) {
|
||||
throw new OperatorCliError(
|
||||
"Duration must be a positive number followed by s, m, h, or d (for example, 30m).",
|
||||
);
|
||||
}
|
||||
const { token, expiresAt } = issueJwt(
|
||||
user.id,
|
||||
expiresIn,
|
||||
context.config.AUTH_JWT_SECRET,
|
||||
);
|
||||
context.output.write(
|
||||
`Bearer token (expires ${expiresAt.toISOString()}):\n${token}\n`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
throw new OperatorCliError(USAGE);
|
||||
}
|
||||
}
|
||||
|
||||
export function createTerminalInput(): OperatorCliInput {
|
||||
return {
|
||||
async line(prompt: string): Promise<string> {
|
||||
const readline = createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stdout,
|
||||
});
|
||||
try {
|
||||
return await readline.question(prompt);
|
||||
} finally {
|
||||
readline.close();
|
||||
}
|
||||
},
|
||||
secret: (prompt: string) =>
|
||||
import("./hidden-input").then(({ readHiddenInput }) =>
|
||||
readHiddenInput(process.stdin, process.stdout, prompt),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { DataSource } from "typeorm";
|
||||
import { AuthService } from "../src/auth/auth.service";
|
||||
import { AuthFailure } from "../src/auth/auth.error";
|
||||
import { PasswordService } from "../src/auth/password.service";
|
||||
import { UserEntity } from "../src/auth/user.entity";
|
||||
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
|
||||
import { verifyJwt } from "../src/auth/jwt.helpers";
|
||||
import { dataSourceOptions } from "../src/database/data-source";
|
||||
import {
|
||||
OperatorCliContext,
|
||||
OperatorCliInput,
|
||||
OperatorCliOutput,
|
||||
runOperatorCommand,
|
||||
} from "../src/operator-cli/operator-cli";
|
||||
import { RawInput, readHiddenInput } from "../src/operator-cli/hidden-input";
|
||||
|
||||
const SECRET = "operator-cli-test-secret";
|
||||
|
||||
describe("operator account CLI", () => {
|
||||
let directory: string;
|
||||
let dataSource: DataSource;
|
||||
let passwords: PasswordService;
|
||||
const output: string[] = [];
|
||||
|
||||
const config = {
|
||||
AUTH_ENABLED: true,
|
||||
AUTH_JWT_SECRET: SECRET,
|
||||
AUTH_JWT_EXPIRES_IN: "24h",
|
||||
} as const;
|
||||
|
||||
function context(input: OperatorCliInput): OperatorCliContext {
|
||||
const outputWriter: OperatorCliOutput = {
|
||||
write: (message) => output.push(message),
|
||||
};
|
||||
return { dataSource, config, passwords, input, output: outputWriter };
|
||||
}
|
||||
|
||||
function prompts(
|
||||
lines: string[] = [],
|
||||
secrets: string[] = [],
|
||||
): OperatorCliInput {
|
||||
return {
|
||||
line: jest.fn(async () => lines.shift() ?? ""),
|
||||
secret: jest.fn(async () => secrets.shift() ?? ""),
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
directory = fs.mkdtempSync(path.join(os.tmpdir(), "liqa-operator-cli-"));
|
||||
dataSource = new DataSource({
|
||||
...dataSourceOptions(path.join(directory, "custom.db")),
|
||||
migrationsRun: true,
|
||||
});
|
||||
await dataSource.initialize();
|
||||
passwords = new PasswordService();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await dataSource?.destroy();
|
||||
fs.rmSync(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
beforeEach(() => output.splice(0));
|
||||
|
||||
it("creates an account with matching hidden passwords and prints only safe identity data", async () => {
|
||||
const input = prompts(
|
||||
[" alice "],
|
||||
["correct horse battery staple", "correct horse battery staple"],
|
||||
);
|
||||
await runOperatorCommand(["user:create"], context(input));
|
||||
|
||||
const user = await dataSource
|
||||
.getRepository(UserEntity)
|
||||
.findOneBy({ username: "alice" });
|
||||
expect(user).not.toBeNull();
|
||||
expect(user?.passwordHash).not.toContain("correct horse battery staple");
|
||||
expect(output.join("")).toContain('Created user "alice".');
|
||||
|
||||
output.splice(0);
|
||||
await runOperatorCommand(["user:get", "alice"], context(prompts()));
|
||||
const details = JSON.parse(output.join("")) as Record<string, unknown>;
|
||||
expect(details).toMatchObject({ id: user?.id, username: "alice" });
|
||||
expect(details.passwordHash).toBeUndefined();
|
||||
expect(JSON.stringify(details)).not.toContain(
|
||||
"correct horse battery staple",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects duplicate, empty and mismatched credentials without creating accounts", async () => {
|
||||
const users = dataSource.getRepository(UserEntity);
|
||||
const initialCount = await users.count();
|
||||
await expect(
|
||||
runOperatorCommand(["user:create"], context(prompts(["alice"], []))),
|
||||
).rejects.toThrow("already exists");
|
||||
|
||||
await expect(
|
||||
runOperatorCommand(["user:create"], context(prompts([" "], []))),
|
||||
).rejects.toThrow("Username cannot be empty");
|
||||
|
||||
await expect(
|
||||
runOperatorCommand(["user:create"], context(prompts(["bob"], ["", ""]))),
|
||||
).rejects.toThrow("Password cannot be empty");
|
||||
|
||||
await expect(
|
||||
runOperatorCommand(
|
||||
["user:create"],
|
||||
context(prompts(["bob"], ["first secret", "different secret"])),
|
||||
),
|
||||
).rejects.toThrow("Passwords do not match");
|
||||
expect(await users.count()).toBe(initialCount);
|
||||
expect(output.join("")).not.toContain("first secret");
|
||||
expect(output.join("")).not.toContain("different secret");
|
||||
});
|
||||
|
||||
it("issues default and custom duration JWTs accepted by the auth service, then deletion invalidates them", async () => {
|
||||
const users = dataSource.getRepository(UserEntity);
|
||||
const user = await users.findOneByOrFail({ username: "alice" });
|
||||
await runOperatorCommand(["user:token", "alice"], context(prompts()));
|
||||
const defaultLines = output.join("").trim().split("\n");
|
||||
const defaultToken = defaultLines[defaultLines.length - 1];
|
||||
const defaultClaims = verifyJwt(defaultToken, SECRET);
|
||||
expect(defaultClaims.sub).toBe(user.id);
|
||||
expect(defaultClaims.exp - defaultClaims.iat).toBe(86400);
|
||||
|
||||
output.splice(0);
|
||||
await runOperatorCommand(
|
||||
["user:token", "alice", "30m"],
|
||||
context(prompts()),
|
||||
);
|
||||
const customLines = output.join("").trim().split("\n");
|
||||
const customToken = customLines[customLines.length - 1];
|
||||
const customClaims = verifyJwt(customToken, SECRET);
|
||||
expect(customClaims.exp - customClaims.iat).toBe(1800);
|
||||
|
||||
const auth = new AuthService(
|
||||
users,
|
||||
dataSource.getRepository(RevokedTokenEntity),
|
||||
{
|
||||
get: (key: string) =>
|
||||
({
|
||||
AUTH_ENABLED: true,
|
||||
AUTH_COOKIE_NAME: "liqa_auth",
|
||||
AUTH_JWT_EXPIRES_IN: "24h",
|
||||
AUTH_JWT_SECRET: SECRET,
|
||||
})[key],
|
||||
} as never,
|
||||
passwords,
|
||||
);
|
||||
expect((await auth.authenticate(customToken)).user.id).toBe(user.id);
|
||||
|
||||
await runOperatorCommand(["user:delete", "alice"], context(prompts()));
|
||||
expect(await users.findOneBy({ id: user.id })).toBeNull();
|
||||
await expect(auth.authenticate(customToken)).rejects.toMatchObject({
|
||||
reason: "invalid-token",
|
||||
} satisfies Partial<AuthFailure>);
|
||||
});
|
||||
|
||||
it("rejects unknown targets, bad durations, and disabled account management", async () => {
|
||||
for (const command of ["user:get", "user:delete", "user:token"]) {
|
||||
await expect(
|
||||
runOperatorCommand([command, "missing"], context(prompts())),
|
||||
).rejects.toThrow("No account found");
|
||||
}
|
||||
await expect(
|
||||
runOperatorCommand(["user:token", "missing", "30m"], context(prompts())),
|
||||
).rejects.toThrow("No account found");
|
||||
|
||||
const user = await dataSource.getRepository(UserEntity).save(
|
||||
dataSource.getRepository(UserEntity).create({
|
||||
username: "duration-check",
|
||||
passwordHash: await passwords.hash("test password"),
|
||||
}),
|
||||
);
|
||||
await expect(
|
||||
runOperatorCommand(
|
||||
["user:token", user.username, "0h"],
|
||||
context(prompts()),
|
||||
),
|
||||
).rejects.toThrow("Duration must be a positive number");
|
||||
await expect(
|
||||
runOperatorCommand(["user:get", user.username], {
|
||||
...context(prompts()),
|
||||
config: { ...config, AUTH_ENABLED: false },
|
||||
}),
|
||||
).rejects.toThrow("require AUTH_ENABLED=true");
|
||||
});
|
||||
});
|
||||
|
||||
describe("hidden password input", () => {
|
||||
class FakeRawInput extends EventEmitter {
|
||||
isTTY = true;
|
||||
isRaw = false;
|
||||
modes: boolean[] = [];
|
||||
setRawMode(mode: boolean): this {
|
||||
this.isRaw = mode;
|
||||
this.modes.push(mode);
|
||||
return this;
|
||||
}
|
||||
pause(): this {
|
||||
return this;
|
||||
}
|
||||
resume(): this {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
it("collects input without echoing the password and restores terminal mode", async () => {
|
||||
const input = new FakeRawInput();
|
||||
let shown = "";
|
||||
const read = readHiddenInput(
|
||||
input as unknown as RawInput,
|
||||
{
|
||||
write: (value: string) => {
|
||||
shown += value;
|
||||
return true;
|
||||
},
|
||||
},
|
||||
"Password: ",
|
||||
);
|
||||
input.emit("data", Buffer.from("private-password\r"));
|
||||
|
||||
await expect(read).resolves.toBe("private-password");
|
||||
expect(shown).toBe("Password: \n");
|
||||
expect(shown).not.toContain("private-password");
|
||||
expect(input.modes).toEqual([true, false]);
|
||||
});
|
||||
|
||||
it("rejects secret prompts without a terminal", async () => {
|
||||
const input = new FakeRawInput();
|
||||
input.isTTY = false;
|
||||
await expect(
|
||||
readHiddenInput(
|
||||
input as unknown as RawInput,
|
||||
{ write: () => true },
|
||||
"Password: ",
|
||||
),
|
||||
).rejects.toThrow("requires an interactive terminal");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user