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:
agent committed 2026-11-09 14:31:29 -05:00
1 parent fe19fb9d56
commit 768a799db0
6 files changed
+570

No files matched your search

+47
View File
@@ -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;
});
+59
View File
@@ -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);
});
}
+193
View File
@@ -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),
),
};
}