feat(auth): deliver optional authentication across Liqa #24

Merged
ars9 merged 16 commits from agent-codex/liqa:master into master 2026-11-11 19:35:12 +02:00
6 changed files with 570 additions and 0 deletions
Showing only changes of commit 768a799db0 - Show all commits

No files matched your search

+27
View File
@@ -103,6 +103,33 @@ The SQLite schema is managed by TypeORM migrations in `server/src/database/migra
The scripts run from `server/`, so `DB_PATH` (default `data/liqa.db`) is relative to it, and they read `server/.env` if present, like the server does.
## Operator account commands
Authentication is opt-in. To manage accounts or issue tokens, set `AUTH_ENABLED=true` and `AUTH_JWT_SECRET` in the same environment used by the server. Apply database migrations before using the commands. Passwords are entered interactively without terminal echo; they are never accepted as command-line arguments.
Build the server and apply migrations locally, then run commands from the server workspace:
```bash
npm -w server run build
npm -w server run migration:run
npm -w server run cli -- user:create
npm -w server run cli -- user:get alice
npm -w server run cli -- user:token alice # uses AUTH_JWT_EXPIRES_IN (default 24h)
npm -w server run cli -- user:token alice 30m # optional lifetime
npm -w server run cli -- user:delete alice
```
The container image does not include npm or npx. Run the built CLI with Node inside the running service; it uses that container's configured `DB_PATH` and exits without starting the web server or schedulers:
```bash
docker compose exec liqa node dist/cli.js user:create
docker compose exec liqa node dist/cli.js user:get alice
docker compose exec liqa node dist/cli.js user:token alice 30m
docker compose exec liqa node dist/cli.js user:delete alice
```
`user:create` asks for a username and two matching passwords. The other commands require an existing username. Lookup output contains only the account id, username, and timestamps. Token output is a bearer credential: handle it as a secret and do not paste it into logs or shared history. User deletion removes the account, so the server rejects that user's previously issued tokens on their next authentication.
**Changing the schema** (adding or changing an entity):
1. Change the entity and build (`npm -w server run build`).
+1
View File
@@ -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\"",
+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),
),
};
}
+243
View File
@@ -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");
});
});