Compare commits

..
21 Commits
Author SHA1 Message Date
c0fe15dc01 Keep test output quiet with opt-in diagnostic logs (#25)
CI / changes (push) Successful in 4s
CI / server (push) Failing after 1h44m8s
CI / client (push) Successful in 1m52s
CI / image (push) Skipped
Test runs stay quiet by default. Diagnostic logs can be enabled explicitly when troubleshooting, while normal application logging and saved scenario output remain available.

Resolves #22.

---------

Co-authored-by: ars9 <ars9@pm.me>
Co-authored-by: agent <agent@halstation.halstation.local>
Reviewed-on: #25
Co-authored-by: agent-codex <agent-codex@ars9.space>
2026-11-11 22:23:44 +02:00
ars9 8b48d4812d Merge pull request 'feat(auth): deliver optional authentication across Liqa' (#24) from agent-codex/liqa:master into master
CI / changes (push) Successful in 31s
CI / server (push) Failing after 1h42m43s
CI / client (push) Successful in 2m55s
CI / image (push) Skipped
Reviewed-on: #24
2026-11-11 19:35:12 +02:00
ars9 ff9a700c86 Merge pull request 'test(auth): cover integrated account journey' (#6) from feat/task-57-auth-integration into master
CI / changes (pull_request) Canceled after 0s
CI / server (pull_request) Canceled after 0s
CI / client (pull_request) Canceled after 0s
CI / image (pull_request) Canceled after 0s
Reviewed-on: agent-codex/liqa#6
2026-11-09 23:25:48 +02:00
ars9 ea4f72c236 Merge pull request 'docs(auth): document optional authentication setup' (#5) from feat/task-56-auth-documentation into master
Reviewed-on: agent-codex/liqa#5
2026-11-09 23:24:38 +02:00
agent 9ff9579a7b test(auth): cover integrated account journey
- Exercise CLI provisioning through browser/API/MCP auth, run events, logout, and deletion.
- Allow integration coverage to reopen the same file-backed test database.
2026-11-09 15:58:49 -05:00
agent 9bdba32a34 docs(auth): document optional authentication setup
- Explain opt-in configuration, protected surfaces, migrations and cookie behavior.
- Document operator CLI, MCP bearer use, cleanup, and supported local origins.
2026-11-09 15:50:12 -05:00
ars9 d4d9bceb98 Merge pull request 'feat(auth): add operator account CLI' (#4) from feat/task-53-operator-cli-refresh into master
Reviewed-on: agent-codex/liqa#4
2026-11-09 22:35:48 +02:00
agent 768a799db0 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.
2026-11-09 14:31:29 -05:00
ars9 fe19fb9d56 Merge pull request 'feat(client): add cookie-backed browser authentication' (#3) from fix/task-55-authenticated-eventsource-repair-2 into master
Reviewed-on: agent-codex/liqa#3
2026-11-09 21:21:20 +02:00
agent f2bcbe07b6 fix(client): clarify login form styling
- Add spacing for the session-expired notice and distinguish login inputs.
- Assert those surfaces in expired-session light and dark stories.
2026-11-09 14:07:59 -05:00
agent 8676d6281c fix(client): focus password after invalid login
- Defer focus until submission finishes and the password field is cleared.
2026-11-05 04:32:25 -05:00
agent 92141a25fb feat(client): add cookie-backed authentication UI
- Add session-aware login, logout and protected navigation.
- Send cookie credentials for API and run-event requests with localized UI stories.
2026-11-05 04:18:11 -05:00
ars9 9e4b692444 Merge pull request 'feat(auth): clean expired revoked tokens' (#2) from feat/task-54-revocation-cleanup into master
Reviewed-on: agent-codex/liqa#2
2026-11-05 11:12:51 +02:00
agent 2976a08aef feat(auth): clean expired revoked tokens
- Remove expired token revocations at startup and on the configured cron.
- Verify expiry boundaries and disabled-auth behavior.
2026-11-05 02:48:53 -05:00
ars9 c3e8670515 Merge pull request 'feat(auth): add optional authentication' (#1) from feat/task-52-optional-auth-server into master
Reviewed-on: agent-codex/liqa#1
2026-11-05 00:31:56 +02:00
agent 1830feb71b refactor(auth): address server review feedback
- Extract auth DTOs, cookie/JWT helpers and the generic duration parser.
- Configure the session cookie and map domain auth failures to HTTP responses.
- Add typed Swagger responses and focused regression coverage.
2026-11-04 17:15:00 -05:00
agent 72e127888c fix(auth): redact passwords on normalized login paths
CI / changes (pull_request) Canceled after 0s
CI / server (pull_request) Canceled after 0s
CI / client (pull_request) Canceled after 0s
CI / image (pull_request) Canceled after 0s
- Normalize login paths before applying request-body redaction.
- Cover trailing-slash paths and assert the password never reaches logs.
2026-11-04 15:59:49 -05:00
agent de41571b5c feat(auth): add optional authentication boundary
- Add account, JWT session, revocation, cookie and bearer handling.
- Protect server surfaces while preserving public health, manifest and disabled mode.
- Add SQLite migration and focused server regression coverage.
2026-11-04 15:43:33 -05:00
ars9 d4bb274982 chore(release): cut minor release
CI / changes (push) Skipped
CI / server (push) Failing after 34m15s
CI / client (push) Successful in 2m43s
CI / image (push) Skipped
- bump version to 1.26.0
- add versioned e2e test export to the changelog
2026-10-08 18:54:34 +03:00
ars9 969f24ea73 Merge pull request 'feat: export e2e tests for a chosen scenario version' (#21) from feat/e2e-export-version into master
CI / changes (push) Successful in 16s
CI / server (push) Successful in 1m32s
CI / client (push) Successful in 1m32s
CI / image (push) Skipped
Reviewed-on: #21
2026-10-08 18:53:26 +03:00
ars9 81164f8494 feat: export e2e tests for a chosen scenario version
CI / changes (pull_request) Successful in 14s
CI / server (pull_request) Successful in 2m25s
CI / client (pull_request) Successful in 1m35s
CI / image (pull_request) Skipped
- GET /scenarios/:id/export-e2e and the export_e2e_test MCP tool take
  an optional version, defaulting to the latest
- build the test project from that version's steps, name and timeout
- put the version in the zip name (<scenario>-vN-e2e-test.zip), the
  generated package name and the README heading
- the Export e2e test button exports the version being viewed
- document the e2e export in scenario.md and mcp.md
2026-10-08 18:37:33 +03:00
101 changed files with 4022 additions and 81 deletions

No files matched your search

+13
View File
@@ -8,6 +8,19 @@
# NODE_ENV=development # NODE_ENV=development
# PORT=3000 # PORT=3000
## Application log output: console (default) or debug (controlled by DEBUG namespaces)
# LOG_MODE=console
## Optional account authentication (disabled unless explicitly enabled)
# AUTH_ENABLED=true
## Required when AUTH_ENABLED=true. Set a private, high-entropy value outside source control.
# AUTH_JWT_SECRET=replace-with-a-private-random-secret
## Browser cookie name and default JWT lifetime
# AUTH_COOKIE_NAME=liqa_auth
# AUTH_JWT_EXPIRES_IN=24h
## Expired logout revocations are cleaned at startup and on this cron schedule.
# AUTH_REVOKED_TOKEN_CLEANUP_CRON=0 3 * * *
## Origins allowed to call the API cross-origin (comma separated). Default: the ## Origins allowed to call the API cross-origin (comma separated). Default: the
## Vite dev server (http://localhost:5173) in development, the compose port ## Vite dev server (http://localhost:5173) in development, the compose port
## (http://localhost:13000) in production ## (http://localhost:13000) in production
+12
View File
@@ -2,6 +2,18 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## 1.26.0 - 2026-10-08
Changes since 1.25.0:
### Added
- e2e test export for a chosen scenario version: `GET /api/v1/scenarios/:id/export-e2e` and the `export_e2e_test` MCP tool take an optional `version` (defaults to the latest), and the test project is built from that version's steps, name and timeout. The Export e2e test button in the UI exports the version being viewed.
### Changed
- Exported e2e test archives include the version in their filename (`<scenario name>-v<N>-e2e-test.zip`), and the version also appears in the generated package name and README heading.
## 1.25.0 - 2026-10-07 ## 1.25.0 - 2026-10-07
Changes since 1.24.4: Changes since 1.24.4:
+2
View File
@@ -12,6 +12,8 @@ docker compose up -d --build
No configuration is needed: every setting has a default. To override one, copy `.env.example` to `.env` and uncomment it. No configuration is needed: every setting has a default. To override one, copy `.env.example` to `.env` and uncomment it.
Authentication is **disabled by default**. To enable operator-managed accounts, set `AUTH_ENABLED=true` and provide a private `AUTH_JWT_SECRET`; then rebuild/restart the service and provision an account with the CLI. See [operator authentication](docs/development.md#operator-account-commands) for setup and browser/API usage. Existing deployments remain unauthenticated until explicitly enabled.
Everything is served from one container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. Data is kept in `./data/`. Everything is served from one container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. Data is kept in `./data/`.
To see it work, import and run the [self-test example](examples/self-test/): a scenario that tests liqa itself using an environment, a credential and snippets. To see it work, import and run the [self-test example](examples/self-test/): a scenario that tests liqa itself using an environment, a credential and snippets.
@@ -0,0 +1,28 @@
import '../../src/i18n';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, within } from 'storybook/test';
import { AuthStatusPage } from '../../src/pages/auth/AuthStatusPage';
const meta: Meta<typeof AuthStatusPage> = {
title: 'Authentication/Session status',
component: AuthStatusPage,
parameters: { layout: 'fullscreen' },
tags: ['autodocs'],
args: { onRetry: fn() },
};
export default meta;
type Story = StoryObj<typeof AuthStatusPage>;
export const Checking: Story = {};
export const SessionCheckFailure: Story = {
args: { failed: true },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole('alert')).toHaveTextContent(
"Couldn't check your session. Try again.",
);
await userEvent.click(canvas.getByRole('button', { name: 'Retry' }));
await expect(args.onRetry).toHaveBeenCalledTimes(1);
},
};
@@ -0,0 +1,71 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect } from 'storybook/test';
import { auth } from '../../src/api/client';
import { createRunEventSource } from '../../src/hooks/useRunNotifications';
function TransportExample() {
return <p>Browser auth uses HttpOnly cookies for API and run-event requests.</p>;
}
const meta: Meta<typeof TransportExample> = {
title: 'Authentication/Cookie transport',
component: TransportExample,
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof TransportExample>;
export const CookieCredentials: Story = {
play: async () => {
const originalFetch = globalThis.fetch;
const localStorageLength = localStorage.length;
let requestInit: RequestInit | undefined;
globalThis.fetch = async (_input, init) => {
requestInit = init;
return new Response(
JSON.stringify({
user: {
id: 'synthetic-user-id',
username: 'synthetic-operator',
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
);
};
try {
const user = await auth.login('synthetic-operator', 'synthetic-password');
await expect(requestInit?.credentials).toBe('include');
await expect(user.username).toBe('synthetic-operator');
await expect(new Headers(requestInit?.headers).has('Authorization')).toBe(false);
await expect(localStorage.length).toBe(localStorageLength);
} finally {
globalThis.fetch = originalFetch;
}
},
};
export const EventStreamIncludesCookieCredentials: Story = {
play: async () => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'EventSource');
let options: EventSourceInit | undefined;
class StubEventSource {
constructor(_url: string | URL, init?: EventSourceInit) {
options = init;
}
close() {}
}
Object.defineProperty(globalThis, 'EventSource', {
configurable: true,
value: StubEventSource,
});
try {
createRunEventSource().close();
await expect(options?.withCredentials).toBe(true);
} finally {
if (previous) Object.defineProperty(globalThis, 'EventSource', previous);
else Reflect.deleteProperty(globalThis, 'EventSource');
}
},
};
@@ -0,0 +1,132 @@
import '../../src/i18n';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, userEvent, within } from 'storybook/test';
import { ApiError } from '../../src/api/client';
import { LoginForm } from '../../src/pages/auth/LoginForm';
const meta: Meta<typeof LoginForm> = {
title: 'Authentication/Login form',
component: LoginForm,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { onSubmit: async () => undefined },
decorators: [
(Story) => (
<div style={{ width: 'min(calc(100vw - 32px), 440px)' }}>
<Story />
</div>
),
],
};
export default meta;
type Story = StoryObj<typeof LoginForm>;
async function expectLoginSurfaces(canvasElement: HTMLElement) {
const canvas = within(canvasElement);
const card = canvasElement.querySelector('section');
const notice = canvas.getByText('Your session has expired. Sign in again to continue.');
const username = canvas.getByRole('textbox', { name: 'Username' });
if (!card) throw new Error('Login card was not rendered.');
await expect(window.getComputedStyle(notice).marginBottom).not.toBe('0px');
await expect(window.getComputedStyle(username).backgroundColor).not.toBe(
window.getComputedStyle(card).backgroundColor,
);
}
export const Initial: Story = {};
export const ExpiredSession: Story = {
args: { expired: true },
play: async ({ canvasElement }) => expectLoginSurfaces(canvasElement),
};
export const SignedOut: Story = { args: { signedOut: true } };
export const DarkTheme: Story = {
args: { expired: true },
decorators: [
(Story) => (
<div data-theme="dark" style={{ width: 440, padding: 24, background: 'var(--color-bg)' }}>
<Story />
</div>
),
],
play: async ({ canvasElement }) => expectLoginSurfaces(canvasElement),
};
export const NarrowViewport: Story = {
decorators: [
(Story) => (
<div style={{ width: 320, padding: 16, background: 'var(--color-bg)' }}>
<Story />
</div>
),
],
};
export const EmptyFieldValidation: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(canvas.getByText('Enter your username.')).toBeVisible();
await expect(canvas.getByRole('textbox', { name: 'Username' })).toHaveFocus();
await expect(canvas.getByLabelText('Password')).toHaveAttribute('aria-invalid', 'true');
},
};
export const InvalidCredentials: Story = {
args: {
onSubmit: async () => {
throw new ApiError(401, 'Unauthorized');
},
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
await userEvent.type(canvas.getByLabelText('Password'), 'wrong-password');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(await canvas.findByRole('alert')).toHaveTextContent(
'Username or password is incorrect.',
);
await expect(canvas.getByRole('textbox', { name: 'Username' })).toHaveValue('operator');
await expect(canvas.getByLabelText('Password')).toHaveValue('');
await expect(canvas.getByLabelText('Password')).toHaveFocus();
},
};
export const RequestFailureAndRetry: Story = {
args: {
onSubmit: (() => {
let attempts = 0;
return async () => {
attempts += 1;
if (attempts === 1) throw new ApiError(503, 'Unavailable');
};
})(),
},
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
await userEvent.type(canvas.getByLabelText('Password'), 'temporary');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(await canvas.findByRole('alert')).toHaveTextContent(
"Couldn't sign in. Check your connection and try again.",
);
await expect(canvas.getByLabelText('Password')).toHaveValue('temporary');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(canvas.queryByRole('alert')).not.toBeInTheDocument();
},
};
export const Submitting: Story = {
args: { onSubmit: () => new Promise(() => undefined) },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
await userEvent.type(canvas.getByLabelText('Password'), 'secret');
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
await expect(canvas.getByRole('status')).toHaveTextContent('Signing in…');
await expect(canvas.getByRole('button', { name: 'Signing in…' })).toBeDisabled();
},
};
@@ -0,0 +1,31 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect } from 'storybook/test';
import { safeReturnTo } from '../../src/auth/returnTo';
function ReturnToSafetyExample() {
return <p>Local return destinations are checked before use.</p>;
}
const meta: Meta<typeof ReturnToSafetyExample> = {
title: 'Authentication/Return destination safety',
component: ReturnToSafetyExample,
tags: ['autodocs'],
};
export default meta;
type Story = StoryObj<typeof ReturnToSafetyExample>;
export const Validation: Story = {
play: async () => {
await expect(safeReturnTo('/scenarios/123/runs/456?example=1#details')).toBe(
'/scenarios/123/runs/456?example=1#details',
);
await expect(safeReturnTo('/scenarios')).toBe('/scenarios');
await expect(safeReturnTo('//external.example/path')).toBeNull();
await expect(safeReturnTo('https://external.example/path')).toBeNull();
await expect(safeReturnTo('/%2f%2fexternal.example')).toBeNull();
await expect(safeReturnTo('/%5c%5cexternal.example')).toBeNull();
await expect(safeReturnTo('/login?returnTo=/scenarios')).toBeNull();
await expect(safeReturnTo('/auth/me')).toBeNull();
await expect(safeReturnTo('/%')).toBeNull();
},
};
@@ -0,0 +1,34 @@
import '../../src/i18n';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, within } from 'storybook/test';
import { SignOutControl } from '../../src/pages/auth/SignOutControl';
const meta: Meta<typeof SignOutControl> = {
title: 'Authentication/Sign out',
component: SignOutControl,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { onSignOut: fn() },
};
export default meta;
type Story = StoryObj<typeof SignOutControl>;
export const Ready: Story = {};
export const Pending: Story = {
args: { pending: true },
play: async ({ canvasElement }) => {
const button = within(canvasElement).getByRole('button', { name: 'Signing out…' });
await expect(button).toBeDisabled();
},
};
export const FailureAndRetry: Story = {
args: { failed: true },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole('alert')).toHaveTextContent("Couldn't sign out. Try again.");
await userEvent.click(canvas.getByRole('button', { name: 'Retry' }));
await expect(args.onSignOut).toHaveBeenCalledTimes(1);
},
};
+64
View File
@@ -38,6 +38,7 @@
.footerButtons { .footerButtons {
display: flex; display: flex;
flex-wrap: wrap;
align-items: center; align-items: center;
gap: var(--space-1); gap: var(--space-1);
} }
@@ -47,6 +48,7 @@
padding: var(--space-3) var(--space-2) var(--space-2); padding: var(--space-3) var(--space-2) var(--space-2);
border-top: var(--border-width) solid var(--color-border); border-top: var(--border-width) solid var(--color-border);
display: flex; display: flex;
flex-wrap: wrap;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: var(--space-2); gap: var(--space-2);
@@ -68,6 +70,68 @@
text-decoration: underline; text-decoration: underline;
} }
.signOut,
.expandForSignOut {
display: inline-flex;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
padding: 0;
color: var(--color-text-muted);
background: transparent;
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
cursor: pointer;
}
.signOut:hover,
.expandForSignOut:hover {
color: var(--color-text);
background: var(--color-secondary);
}
.signOut:focus-visible,
.expandForSignOut:focus-visible,
.logoutFailure button:focus-visible {
outline: 2px solid var(--color-primary-text);
outline-offset: 2px;
}
.signOut:disabled {
opacity: 0.55;
cursor: wait;
}
.logoutFailure {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2);
color: var(--color-error-fg);
background: var(--color-error-bg);
border-radius: var(--radius-sm);
font-size: var(--font-size-xs);
}
.logoutFailure button {
min-height: 32px;
color: inherit;
background: transparent;
border: var(--border-width) solid currentColor;
border-radius: var(--radius-sm);
cursor: pointer;
}
.expandForSignOut {
position: fixed;
left: 8px;
bottom: 12px;
z-index: 20;
background: var(--color-bg-subtle);
box-shadow: var(--shadow-sm);
}
.navItem { .navItem {
display: flex; display: flex;
align-items: center; align-items: center;
+77 -2
View File
@@ -1,5 +1,6 @@
import { lazy, Suspense } from 'react'; import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { NavLink, Navigate, Route, Routes } from 'react-router-dom'; import { LogOut } from 'lucide-react';
import { NavLink, Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react'; import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react';
import type { LucideIcon } from 'lucide-react'; import type { LucideIcon } from 'lucide-react';
@@ -8,6 +9,11 @@ import { NotificationToggle, SidePanel, ThemeSwitcher } from './ui';
import liqaLogo from './assets/liqa.svg'; import liqaLogo from './assets/liqa.svg';
import { useManifest } from './hooks/useManifest'; import { useManifest } from './hooks/useManifest';
import { useRunNotifications } from './hooks/useRunNotifications'; import { useRunNotifications } from './hooks/useRunNotifications';
import { useAuth } from './auth/useAuth';
import { safeReturnTo } from './auth/returnTo';
import { AuthStatusPage } from './pages/auth/AuthStatusPage';
import { LoginPage } from './pages/auth/LoginPage';
import { SignOutControl } from './pages/auth/SignOutControl';
const EnvironmentsPage = lazy(() => const EnvironmentsPage = lazy(() =>
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })), import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
@@ -109,12 +115,59 @@ const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator:
export default function App() { export default function App() {
const { t } = useTranslation(); const { t } = useTranslation();
const auth = useAuth();
const location = useLocation();
const [search] = useSearchParams();
const [collapsed, setCollapsed] = useState(false);
const [loggingOut, setLoggingOut] = useState(false);
const [logoutFailed, setLogoutFailed] = useState(false);
const focusSignOut = useRef(false);
const { version } = useManifest(); const { version } = useManifest();
const notifications = useRunNotifications(); const notifications = useRunNotifications();
useEffect(() => {
if (!collapsed && focusSignOut.current) {
focusSignOut.current = false;
document.querySelector<HTMLButtonElement>('[data-sign-out="true"]')?.focus();
}
}, [collapsed]);
async function signOut() {
if (loggingOut) return;
setLoggingOut(true);
setLogoutFailed(false);
try {
await auth.logout();
} catch {
setLogoutFailed(true);
} finally {
setLoggingOut(false);
}
}
const onLogin = location.pathname === '/login';
if (auth.enabled && (auth.status === 'checking' || auth.status === 'disabled')) {
return <AuthStatusPage />;
}
if (auth.enabled && auth.status === 'error') {
return <AuthStatusPage failed onRetry={() => void auth.checkSession()} />;
}
if (!auth.enabled && onLogin) return <Navigate to="/scenarios" replace />;
if (auth.enabled && auth.status === 'authenticated' && onLogin) {
return <Navigate to={safeReturnTo(search.get('returnTo')) ?? '/scenarios'} replace />;
}
if (auth.enabled && auth.status === 'unauthenticated' && !onLogin) {
const returnTo =
safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios';
return <Navigate to={`/login?returnTo=${encodeURIComponent(returnTo)}`} replace />;
}
if (onLogin) return <LoginPage />;
return ( return (
<div className={styles.shell}> <div className={styles.shell}>
<SidePanel <SidePanel
collapsed={collapsed}
onCollapsedChange={setCollapsed}
header={ header={
<div className={styles.header}> <div className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.brand} /> <img src={liqaLogo} alt="Liqa" className={styles.brand} />
@@ -148,6 +201,13 @@ export default function App() {
{notifications && ( {notifications && (
<NotificationToggle state={notifications.state} onToggle={notifications.toggle} /> <NotificationToggle state={notifications.state} onToggle={notifications.toggle} />
)} )}
{auth.enabled && auth.status === 'authenticated' && (
<SignOutControl
pending={loggingOut}
failed={logoutFailed}
onSignOut={() => void signOut()}
/>
)}
</div> </div>
<div className={styles.version}> <div className={styles.version}>
<span <span
@@ -173,6 +233,21 @@ export default function App() {
</div> </div>
</SidePanel> </SidePanel>
{collapsed && auth.enabled && auth.status === 'authenticated' && (
<button
type="button"
className={styles.expandForSignOut}
aria-label={t('auth.show_sign_out')}
title={t('auth.show_sign_out')}
onClick={() => {
focusSignOut.current = true;
setCollapsed(false);
}}
>
<LogOut size={18} aria-hidden="true" />
</button>
)}
<main className={styles.main}> <main className={styles.main}>
<Suspense fallback={<p>Loading…</p>}> <Suspense fallback={<p>Loading…</p>}>
<Routes> <Routes>
+57 -6
View File
@@ -31,7 +31,25 @@ const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/
/** URL of the server-sent events stream of run lifecycle events. */ /** URL of the server-sent events stream of run lifecycle events. */
export const RUN_EVENTS_URL = `${BASE_URL}/scenarios/runs/events`; export const RUN_EVENTS_URL = `${BASE_URL}/scenarios/runs/events`;
async function request<T>(path: string, init?: RequestInit): Promise<T> { export class ApiError extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message);
this.name = 'ApiError';
}
}
interface RequestOptions {
quietErrors?: boolean;
}
async function request<T>(
path: string,
init?: RequestInit,
options: RequestOptions = {},
): Promise<T> {
let res: Response; let res: Response;
try { try {
const headers = new Headers(init?.headers); const headers = new Headers(init?.headers);
@@ -41,18 +59,26 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
res = await fetch(`${BASE_URL}${path}`, { res = await fetch(`${BASE_URL}${path}`, {
...init, ...init,
credentials: init?.credentials ?? 'include',
headers, headers,
}); });
} catch (err) { } catch (err) {
const message = (err as Error).message || 'Network request failed'; const message = (err as Error).message || 'Network request failed';
emitApiErrorToast(message); if (!options.quietErrors) emitApiErrorToast(message);
throw new Error(message); throw new Error(message);
} }
if (!res.ok) { if (!res.ok) {
const text = await res.text().catch(() => res.statusText); const text = await res.text().catch(() => res.statusText);
const message = `${res.status} ${text}`; const message = `${res.status} ${text}`;
emitApiErrorToast(message); const error = new ApiError(res.status, message);
throw new Error(message); if (res.status === 401 && !path.startsWith('/auth/')) {
const event = new CustomEvent('liqa:unauthorized', { cancelable: true });
const handled = !window.dispatchEvent(event);
if (!handled && !options.quietErrors) emitApiErrorToast(message);
} else if (!options.quietErrors && !path.startsWith('/auth/')) {
emitApiErrorToast(message);
}
throw error;
} }
const contentLength = res.headers.get('content-length'); const contentLength = res.headers.get('content-length');
if (res.status === 204 || contentLength === '0') return undefined as T; if (res.status === 204 || contentLength === '0') return undefined as T;
@@ -65,6 +91,30 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
return text as T; return text as T;
} }
export interface AuthUser {
id: string;
username: string;
createdAt: string;
updatedAt: string;
}
export const auth = {
async login(username: string, password: string): Promise<AuthUser> {
const response = await request<{ user: AuthUser }>(
'/auth/login',
{ method: 'POST', body: JSON.stringify({ username, password }) },
{ quietErrors: true },
);
return response.user;
},
me(): Promise<AuthUser> {
return request('/auth/me', undefined, { quietErrors: true });
},
logout(): Promise<void> {
return request('/auth/logout', { method: 'POST' }, { quietErrors: true });
},
};
// ── Credentials ─────────────────────────────────────────────────────────────── // ── Credentials ───────────────────────────────────────────────────────────────
export const credentials = { export const credentials = {
@@ -275,8 +325,9 @@ export const scenarios = {
} }
return request(`/scenarios/${id}/export?${params.toString()}`); return request(`/scenarios/${id}/export?${params.toString()}`);
}, },
exportE2eTestUrl(id: string): string { exportE2eTestUrl(id: string, version?: number): string {
return `${BASE_URL}/scenarios/${id}/export-e2e`; const query = version === undefined ? '' : `?version=${version}`;
return `${BASE_URL}/scenarios/${id}/export-e2e${query}`;
}, },
usedSnippets(id: string): Promise<UsedSnippet[]> { usedSnippets(id: string): Promise<UsedSnippet[]> {
return request(`/scenarios/${id}/used-snippets`); return request(`/scenarios/${id}/used-snippets`);
+133
View File
@@ -0,0 +1,133 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { ApiError, auth as authApi, type AuthUser } from '../api/client';
import { refreshManifest } from '../lib/manifest';
import { useManifest } from '../hooks/useManifest';
import { loginPath, safeReturnTo } from './returnTo';
import { AuthContext } from './context';
import type { AuthStatus } from './context';
export function AuthProvider({ children }: { children: ReactNode }) {
const { auth: manifestAuth } = useManifest();
const enabled = manifestAuth.enabled;
const location = useLocation();
const navigate = useNavigate();
const queryClient = useQueryClient();
const [status, setStatus] = useState<AuthStatus>('checking');
const [user, setUser] = useState<AuthUser | null>(null);
const statusRef = useRef(status);
const enabledRef = useRef(enabled);
const handledUnauthorized = useRef(false);
const checkInFlight = useRef<Promise<void> | null>(null);
useEffect(() => {
enabledRef.current = enabled;
statusRef.current = status;
}, [enabled, status]);
const updateStatus = useCallback((next: AuthStatus) => {
statusRef.current = next;
setStatus(next);
}, []);
const checkSession = useCallback(async () => {
if (!enabledRef.current) {
setUser(null);
updateStatus('disabled');
return;
}
if (checkInFlight.current) return checkInFlight.current;
updateStatus('checking');
const check = authApi
.me()
.then((account) => {
setUser(account);
handledUnauthorized.current = false;
updateStatus('authenticated');
})
.catch((error: unknown) => {
setUser(null);
updateStatus(
error instanceof ApiError && error.status === 401 ? 'unauthenticated' : 'error',
);
})
.finally(() => {
checkInFlight.current = null;
});
checkInFlight.current = check;
return check;
}, [updateStatus]);
useEffect(() => {
if (!enabled) {
// This synchronizes the session state with the server's feature flag.
// eslint-disable-next-line react-hooks/set-state-in-effect
setUser(null);
updateStatus('disabled');
queryClient.clear();
return;
}
void checkSession();
}, [enabled, checkSession, queryClient, updateStatus]);
useEffect(() => {
const onUnauthorized = (event: Event) => {
if (!enabledRef.current) return;
if (handledUnauthorized.current) {
event.preventDefault();
return;
}
if (statusRef.current !== 'authenticated') return;
event.preventDefault();
handledUnauthorized.current = true;
queryClient.clear();
setUser(null);
updateStatus('unauthenticated');
const target =
safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios';
navigate(loginPath(target, true), { replace: true });
};
window.addEventListener('liqa:unauthorized', onUnauthorized);
return () => window.removeEventListener('liqa:unauthorized', onUnauthorized);
}, [location.hash, location.pathname, location.search, navigate, queryClient, updateStatus]);
const login = useCallback(
async (username: string, password: string) => {
let account: AuthUser;
try {
account = await authApi.login(username, password);
} catch (error) {
if (error instanceof ApiError && error.status === 404) await refreshManifest();
throw error;
}
queryClient.clear();
handledUnauthorized.current = false;
setUser(account);
updateStatus('authenticated');
},
[queryClient, updateStatus],
);
const logout = useCallback(async () => {
try {
await authApi.logout();
} catch (error) {
if (!(error instanceof ApiError && error.status === 401)) {
await checkSession();
throw error;
}
}
queryClient.clear();
setUser(null);
updateStatus('unauthenticated');
handledUnauthorized.current = false;
navigate('/login?notice=signedOut', { replace: true });
}, [checkSession, navigate, queryClient, updateStatus]);
return (
<AuthContext.Provider value={{ enabled, status, user, login, logout, checkSession }}>
{children}
</AuthContext.Provider>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { createContext } from 'react';
import type { AuthUser } from '../api/client';
export type AuthStatus = 'disabled' | 'checking' | 'authenticated' | 'unauthenticated' | 'error';
export interface AuthContextValue {
enabled: boolean;
status: AuthStatus;
user: AuthUser | null;
login: (username: string, password: string) => Promise<void>;
logout: () => Promise<void>;
checkSession: () => Promise<void>;
}
export const AuthContext = createContext<AuthContextValue | null>(null);
+45
View File
@@ -0,0 +1,45 @@
/** Return only a well-formed route on this app's origin. */
export function safeReturnTo(value: string | null | undefined): string | null {
if (
!value ||
!value.startsWith('/') ||
value.startsWith('//') ||
value.includes('\\') ||
/%(?:2f|5c)/i.test(value)
)
return null;
let decoded = value;
try {
for (let pass = 0; pass < 3; pass += 1) {
const next = decodeURIComponent(decoded);
if (next === decoded) break;
decoded = next;
}
} catch {
return null;
}
const containsControl = [...decoded].some((character) => {
const code = character.charCodeAt(0);
return code < 32 || code === 127;
});
if (decoded.startsWith('//') || decoded.includes('\\') || containsControl) {
return null;
}
try {
const target = new URL(value, window.location.origin);
if (target.origin !== window.location.origin) return null;
if (/^\/(?:login|auth)(?:\/|$)/i.test(target.pathname)) return null;
return `${target.pathname}${target.search}${target.hash}`;
} catch {
return null;
}
}
export function loginPath(returnTo: string, expired = false): string {
const query = new URLSearchParams();
query.set('returnTo', safeReturnTo(returnTo) ?? '/scenarios');
if (expired) query.set('expired', '1');
return `/login?${query.toString()}`;
}
+8
View File
@@ -0,0 +1,8 @@
import { useContext } from 'react';
import { AuthContext } from './context';
export function useAuth() {
const value = useContext(AuthContext);
if (!value) throw new Error('useAuth must be used inside AuthProvider');
return value;
}
+12 -2
View File
@@ -5,11 +5,16 @@ import { useTranslation } from 'react-i18next';
import { RUN_EVENTS_URL } from '../api/client'; import { RUN_EVENTS_URL } from '../api/client';
import type { RunEvent } from '../api/types'; import type { RunEvent } from '../api/types';
import type { NotificationToggleState } from '../ui'; import type { NotificationToggleState } from '../ui';
import { useAuth } from '../auth/useAuth';
const STORAGE_KEY = 'liqa-run-notifications'; const STORAGE_KEY = 'liqa-run-notifications';
const RETRY_MIN_MS = 1_000; const RETRY_MIN_MS = 1_000;
const RETRY_MAX_MS = 30_000; const RETRY_MAX_MS = 30_000;
export function createRunEventSource(): EventSource {
return new EventSource(RUN_EVENTS_URL, { withCredentials: true });
}
function supported(): boolean { function supported(): boolean {
return typeof window !== 'undefined' && 'Notification' in window && 'EventSource' in window; return typeof window !== 'undefined' && 'Notification' in window && 'EventSource' in window;
} }
@@ -41,6 +46,7 @@ export function useRunNotifications(): {
state: NotificationToggleState; state: NotificationToggleState;
toggle: () => void; toggle: () => void;
} | null { } | null {
const auth = useAuth();
const isSupported = supported(); const isSupported = supported();
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -81,7 +87,11 @@ export function useRunNotifications(): {
handlers.current = { t, navigate }; handlers.current = { t, navigate };
}); });
const active = isSupported && enabled && permission === 'granted'; const active =
isSupported &&
enabled &&
permission === 'granted' &&
(!auth.enabled || auth.status === 'authenticated');
useEffect(() => { useEffect(() => {
if (!active) return; if (!active) return;
@@ -122,7 +132,7 @@ export function useRunNotifications(): {
}; };
const connect = () => { const connect = () => {
source = new EventSource(RUN_EVENTS_URL); source = createRunEventSource();
source.addEventListener('open', () => { source.addEventListener('open', () => {
retryDelay = RETRY_MIN_MS; retryDelay = RETRY_MIN_MS;
}); });
+20
View File
@@ -1,4 +1,24 @@
{ {
"auth": {
"page_title": "Sign in",
"sign_in": "Sign in",
"signing_in": "Signing in…",
"username": "Username",
"password": "Password",
"username_required": "Enter your username.",
"password_required": "Enter your password.",
"invalid_credentials": "Username or password is incorrect.",
"sign_in_failed": "Couldn't sign in. Check your connection and try again.",
"checking_session": "Checking your session…",
"session_check_failed": "Couldn't check your session. Try again.",
"retry": "Retry",
"session_expired": "Your session has expired. Sign in again to continue.",
"sign_out": "Sign out",
"signing_out": "Signing out…",
"signed_out": "You have signed out.",
"sign_out_failed": "Couldn't sign out. Try again.",
"show_sign_out": "Expand the menu to sign out"
},
"common": { "common": {
"button_cancel": "Cancel", "button_cancel": "Cancel",
"button_confirm": "Confirm", "button_confirm": "Confirm",
+9 -1
View File
@@ -8,12 +8,16 @@ export interface Manifest {
runLogs: { runLogs: {
dataLimits: LogDataLimits; dataLimits: LogDataLimits;
}; };
auth: {
enabled: boolean;
};
} }
export const DEFAULT_MANIFEST: Manifest = { export const DEFAULT_MANIFEST: Manifest = {
name: 'liqa', name: 'liqa',
version: __APP_VERSION__, version: __APP_VERSION__,
runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS }, runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS },
auth: { enabled: false },
}; };
const STORAGE_KEY = 'liqa-manifest'; const STORAGE_KEY = 'liqa-manifest';
@@ -39,6 +43,7 @@ function normalize(raw: unknown): Manifest | null {
return { return {
name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name, name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name,
version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version, version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version,
auth: { enabled: m.auth?.enabled === true },
runLogs: { runLogs: {
dataLimits: { dataLimits: {
bytes: num(limits.bytes, DEFAULT_LOG_DATA_LIMITS.bytes), bytes: num(limits.bytes, DEFAULT_LOG_DATA_LIMITS.bytes),
@@ -77,7 +82,10 @@ const listeners = new Set<() => void>();
* silent: the cached (or default) manifest stays in use. * silent: the cached (or default) manifest stays in use.
*/ */
export function refreshManifest(): Promise<void> { export function refreshManifest(): Promise<void> {
inFlight ??= fetch(MANIFEST_URL, { headers: { Accept: 'application/json' } }) inFlight ??= fetch(MANIFEST_URL, {
headers: { Accept: 'application/json' },
credentials: 'include',
})
.then((res) => (res.ok ? res.json() : null)) .then((res) => (res.ok ? res.json() : null))
.then((raw: unknown) => { .then((raw: unknown) => {
const next = normalize(raw); const next = normalize(raw);
+13 -2
View File
@@ -6,15 +6,26 @@ import './i18n';
import './ui/tokens.css'; import './ui/tokens.css';
import App from './App'; import App from './App';
import { ToastProvider } from './ui'; import { ToastProvider } from './ui';
import { AuthProvider } from './auth/AuthContext';
import { ApiError } from './api/client';
const queryClient = new QueryClient(); const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: (failureCount, error) =>
error instanceof ApiError && error.status === 401 ? false : failureCount < 3,
},
},
});
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<ToastProvider> <ToastProvider>
<BrowserRouter> <BrowserRouter>
<App /> <AuthProvider>
<App />
</AuthProvider>
</BrowserRouter> </BrowserRouter>
</ToastProvider> </ToastProvider>
</QueryClientProvider> </QueryClientProvider>
@@ -0,0 +1,57 @@
.page {
min-height: 100vh;
padding: 24px;
display: flex;
flex-direction: column;
color: var(--color-text);
background: var(--color-bg);
font-family: var(--font-family);
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
}
.logo {
display: block;
width: auto;
height: 32px;
padding: 3px 6px;
background: #e6edea;
border-radius: var(--radius-md);
}
.main {
flex: 1;
display: grid;
place-items: center;
padding: var(--space-6) 0;
}
.message {
width: min(100%, 440px);
display: flex;
flex-direction: column;
align-items: stretch;
gap: var(--space-4);
margin: 0;
padding: var(--space-6);
text-align: center;
background: var(--color-bg);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-sm);
}
.message p {
margin: 0;
color: var(--color-error-fg);
}
@media (max-width: 480px) {
.page {
padding: 16px;
}
}
+38
View File
@@ -0,0 +1,38 @@
import { useTranslation } from 'react-i18next';
import { Button, ThemeSwitcher } from '../../ui';
import { usePageTitle } from '../../hooks/usePageTitle';
import liqaLogo from '../../assets/liqa.svg';
import styles from './AuthStatusPage.module.css';
export function AuthStatusPage({
failed = false,
onRetry,
}: {
failed?: boolean;
onRetry?: () => void;
}) {
const { t } = useTranslation();
usePageTitle(t('auth.page_title'));
return (
<div className={styles.page}>
<header className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.logo} />
<ThemeSwitcher />
</header>
<main className={styles.main} aria-live="polite">
{failed ? (
<section className={styles.message}>
<p role="alert">{t('auth.session_check_failed')}</p>
<Button type="button" size="lg" onClick={onRetry}>
{t('auth.retry')}
</Button>
</section>
) : (
<p className={styles.message} role="status">
{t('auth.checking_session')}
</p>
)}
</main>
</div>
);
}
@@ -0,0 +1,65 @@
.card {
width: min(100%, 400px);
padding: 24px;
color: var(--color-text);
background: var(--color-bg);
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-sm);
}
.title {
margin: 0 0 var(--space-5);
font-size: var(--font-size-lg);
line-height: 1.3;
text-align: center;
}
.title:focus {
outline: 2px solid var(--color-primary-text);
outline-offset: 4px;
border-radius: var(--radius-sm);
}
.notice,
.formError {
margin: 0;
padding: var(--space-3) var(--space-4);
color: var(--color-error-fg);
background: var(--color-error-bg);
border-radius: var(--radius-md);
font-size: var(--font-size-sm);
}
.notice {
margin-bottom: var(--space-4);
}
.form .loginInput {
background: var(--color-bg-subtle);
}
.form {
display: flex;
flex-direction: column;
gap: var(--space-4);
}
.submit {
width: 100%;
}
.status {
margin: 0;
color: var(--color-text-muted);
font-size: var(--font-size-sm);
}
@media (max-width: 480px) {
.card {
padding: var(--space-4);
border: 0;
border-radius: 0;
box-shadow: none;
}
}
+133
View File
@@ -0,0 +1,133 @@
import { useEffect, useRef, useState, type FormEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { ApiError } from '../../api/client';
import { Button, Input } from '../../ui';
import styles from './LoginForm.module.css';
export interface LoginFormProps {
expired?: boolean;
signedOut?: boolean;
onSubmit: (username: string, password: string) => Promise<void>;
}
export function LoginForm({ expired = false, signedOut = false, onSubmit }: LoginFormProps) {
const { t } = useTranslation();
const titleRef = useRef<HTMLHeadingElement>(null);
const formRef = useRef<HTMLFormElement>(null);
const focusPasswordAfterInvalidCredentialsRef = useRef(false);
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [usernameError, setUsernameError] = useState('');
const [passwordError, setPasswordError] = useState('');
const [formError, setFormError] = useState('');
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
titleRef.current?.focus();
}, []);
useEffect(() => {
if (!submitting && focusPasswordAfterInvalidCredentialsRef.current) {
focusPasswordAfterInvalidCredentialsRef.current = false;
formRef.current?.querySelector<HTMLInputElement>('input[name="password"]')?.focus();
}
}, [submitting]);
function focusInput(name: string) {
formRef.current?.querySelector<HTMLInputElement>(`input[name="${name}"]`)?.focus();
}
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (submitting) return;
setFormError('');
const missingUsername = username.trim().length === 0;
const missingPassword = password.length === 0;
setUsernameError(missingUsername ? t('auth.username_required') : '');
setPasswordError(missingPassword ? t('auth.password_required') : '');
if (missingUsername || missingPassword) {
focusInput(missingUsername ? 'username' : 'password');
return;
}
setSubmitting(true);
try {
await onSubmit(username, password);
} catch (error) {
if (error instanceof ApiError && error.status === 401) {
setFormError(t('auth.invalid_credentials'));
setPassword('');
focusPasswordAfterInvalidCredentialsRef.current = true;
} else {
setFormError(t('auth.sign_in_failed'));
}
} finally {
setSubmitting(false);
}
}
return (
<section className={styles.card} aria-labelledby="login-title">
<h1 id="login-title" ref={titleRef} tabIndex={-1} className={styles.title}>
{t('auth.sign_in')}
</h1>
{expired && <p className={styles.notice}>{t('auth.session_expired')}</p>}
{signedOut && <p className={styles.notice}>{t('auth.signed_out')}</p>}
<form
ref={formRef}
className={styles.form}
onSubmit={(event) => void handleSubmit(event)}
noValidate
>
<Input
name="username"
className={styles.loginInput}
label={t('auth.username')}
autoComplete="username"
autoCapitalize="none"
autoCorrect="off"
value={username}
onChange={(event) => {
setUsername(event.target.value);
if (usernameError) setUsernameError('');
}}
error={usernameError || undefined}
disabled={submitting}
/>
<Input
name="password"
className={styles.loginInput}
type="password"
label={t('auth.password')}
autoComplete="current-password"
value={password}
onChange={(event) => {
setPassword(event.target.value);
if (passwordError) setPasswordError('');
}}
error={passwordError || undefined}
disabled={submitting}
/>
{formError && (
<p className={styles.formError} role="alert">
{formError}
</p>
)}
{submitting && (
<p className={styles.status} role="status" aria-live="polite">
{t('auth.signing_in')}
</p>
)}
<Button
type="submit"
size="lg"
loading={submitting}
disabled={submitting}
className={styles.submit}
>
{t(submitting ? 'auth.signing_in' : 'auth.sign_in')}
</Button>
</form>
</section>
);
}
@@ -0,0 +1,44 @@
.page {
min-height: 100vh;
padding: 24px;
display: flex;
flex-direction: column;
color: var(--color-text);
background: var(--color-bg);
font-family: var(--font-family);
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-4);
}
.logo {
display: block;
width: auto;
height: 32px;
padding: 3px 6px;
background: #e6edea;
border-radius: var(--radius-md);
}
.main {
flex: 1;
min-height: 0;
display: grid;
place-items: center;
padding: var(--space-6) 0;
}
@media (max-width: 480px) {
.page {
padding: 16px;
}
.main {
align-items: start;
padding-top: clamp(40px, 12vh, 96px);
}
}
+41
View File
@@ -0,0 +1,41 @@
import { useCallback } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAuth } from '../../auth/useAuth';
import { safeReturnTo } from '../../auth/returnTo';
import { usePageTitle } from '../../hooks/usePageTitle';
import { ThemeSwitcher } from '../../ui';
import liqaLogo from '../../assets/liqa.svg';
import { LoginForm } from './LoginForm';
import styles from './LoginPage.module.css';
export function LoginPage() {
const auth = useAuth();
const navigate = useNavigate();
const [search] = useSearchParams();
const { t } = useTranslation();
const returnTo = safeReturnTo(search.get('returnTo')) ?? '/scenarios';
const expired = search.get('expired') === '1';
const signedOut = search.get('notice') === 'signedOut';
usePageTitle(t('auth.page_title'));
const handleSubmit = useCallback(
async (username: string, password: string) => {
await auth.login(username, password);
navigate(returnTo, { replace: true });
},
[auth, navigate, returnTo],
);
return (
<div className={styles.page}>
<header className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.logo} />
<ThemeSwitcher />
</header>
<main className={styles.main}>
<LoginForm expired={expired} signedOut={signedOut} onSubmit={handleSubmit} />
</main>
</div>
);
}
@@ -0,0 +1,57 @@
.root {
display: flex;
flex-direction: column;
gap: var(--space-2);
min-width: 0;
}
.button {
min-height: 44px;
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
color: var(--color-text);
background: transparent;
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
font: inherit;
font-size: var(--font-size-xs);
cursor: pointer;
}
.button:hover:not(:disabled) {
background: var(--color-secondary);
}
.button:focus-visible,
.failure button:focus-visible {
outline: 2px solid var(--color-primary-text);
outline-offset: 2px;
}
.button:disabled {
opacity: 0.55;
cursor: wait;
}
.failure {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2);
color: var(--color-error-fg);
background: var(--color-error-bg);
border-radius: var(--radius-sm);
font-size: var(--font-size-xs);
}
.failure button {
min-height: 32px;
color: inherit;
background: transparent;
border: var(--border-width) solid currentColor;
border-radius: var(--radius-sm);
cursor: pointer;
}
+39
View File
@@ -0,0 +1,39 @@
import { LogOut } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import styles from './SignOutControl.module.css';
export function SignOutControl({
pending = false,
failed = false,
onSignOut,
}: {
pending?: boolean;
failed?: boolean;
onSignOut: () => void;
}) {
const { t } = useTranslation();
return (
<div className={styles.root}>
<button
type="button"
className={styles.button}
onClick={onSignOut}
disabled={pending}
data-sign-out="true"
aria-label={t(pending ? 'auth.signing_out' : 'auth.sign_out')}
title={t(pending ? 'auth.signing_out' : 'auth.sign_out')}
>
<LogOut size={16} aria-hidden="true" />
<span>{t(pending ? 'auth.signing_out' : 'auth.sign_out')}</span>
</button>
{failed && (
<div className={styles.failure} role="alert">
<span>{t('auth.sign_out_failed')}</span>
<button type="button" onClick={onSignOut} disabled={pending}>
{t('auth.retry')}
</button>
</div>
)}
</div>
);
}
@@ -504,7 +504,10 @@ export function ScenarioDetailPage() {
variant="secondary" variant="secondary"
size="sm" size="sm"
onClick={() => onClick={() =>
handleFileDownload(scenarios.exportE2eTestUrl(id!), `${scenario.name}-e2e-test.zip`) handleFileDownload(
scenarios.exportE2eTestUrl(id!, scenario.version),
`${scenario.name}-v${scenario.version}-e2e-test.zip`,
)
} }
> >
<FileArchive size={14} /> <FileArchive size={14} />
+6
View File
@@ -88,3 +88,9 @@
@keyframes spin { @keyframes spin {
to { transform: rotate(360deg); } to { transform: rotate(360deg); }
} }
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ export function SidePanel({
style={{ '--side-panel-width': `${width}px` } as React.CSSProperties} style={{ '--side-panel-width': `${width}px` } as React.CSSProperties}
aria-expanded={!collapsed} aria-expanded={!collapsed}
> >
<div className={styles.inner}> <div className={styles.inner} aria-hidden={collapsed} inert={collapsed}>
{header && <div className={styles.header}>{header}</div>} {header && <div className={styles.header}>{header}</div>}
<div className={styles.content}>{children}</div> <div className={styles.content}>{children}</div>
</div> </div>
+6
View File
@@ -35,6 +35,12 @@
Everything runs in one container built from the root `Dockerfile`: the server serves the API, MCP and Swagger, and also the built client. See [development.md](development.md) for running it. Everything runs in one container built from the root `Dockerfile`: the server serves the API, MCP and Swagger, and also the built client. See [development.md](development.md) for running it.
## Optional authentication boundary
Account authentication is off unless `AUTH_ENABLED=true`. When enabled, the global guard protects REST and MCP controller routes and the run-events stream. The public routes are `GET /health`, `GET /healthz`, `GET /manifest.json` and `POST /api/v1/auth/login`; the manifest reports the auth-enabled flag so the client can choose its login flow. UI assets and the Swagger UI remain reachable, but API operations require authentication. Protected requests accept a bearer token or the `AUTH_COOKIE_NAME` cookie (`liqa_auth` by default). Browser login sets an HttpOnly, SameSite=Strict cookie and logout revokes the presented token and expires the cookie; HTTPS requests also get the Secure attribute. See [development.md](development.md#enabling-authentication) for operator setup and lifecycle details.
The authentication service stores users and hashed revoked-token identifiers in SQLite. Revocation records are retained through token expiry, then removed at startup and by the `AUTH_REVOKED_TOKEN_CLEANUP_CRON` job (`0 3 * * *` by default); no cleanup job is registered while auth is disabled. Authentication checks that the token is not revoked and that its account still exists, so deleting an account invalidates its outstanding tokens at the next request.
## Server components (`server/src/`) ## Server components (`server/src/`)
- **McpService** (`mcp/`) registers the MCP tools and delegates to the services below. Each request gets a fresh MCP server over the Streamable HTTP transport. - **McpService** (`mcp/`) registers the MCP tools and delegates to the services below. Each request gets a fresh MCP server over the Streamable HTTP transport.
+55 -1
View File
@@ -30,6 +30,7 @@ All settings are validated at startup by `server/src/config/app.config.ts`.
| `NODE_ENV` | `development` | `production` in the Docker image. Shown in the startup log, and selects the default CORS origins | | `NODE_ENV` | `development` | `production` in the Docker image. Shown in the startup log, and selects the default CORS origins |
| `CORS_ORIGINS` | *(empty)* | Comma-separated origins allowed to call the API cross-origin. When empty: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) unless `NODE_ENV=production`, then the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) | | `CORS_ORIGINS` | *(empty)* | Comma-separated origins allowed to call the API cross-origin. When empty: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) unless `NODE_ENV=production`, then the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) |
| `PORT` | `3000` | HTTP port | | `PORT` | `3000` | HTTP port |
| `LOG_MODE` | `console` | `console` preserves the default server output; `debug` routes application diagnostics through the `debug` package and only emits namespaces enabled by `DEBUG` (for example, `DEBUG=liqa:*`). |
| `DB_PATH` | `data/liqa.db` | SQLite database file | | `DB_PATH` | `data/liqa.db` | SQLite database file |
| `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored | | `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored |
| `FILE_RUN_EXPIRATION_DAYS` | `7` | How long run artifacts (downloads, failure dumps, traces) are kept | | `FILE_RUN_EXPIRATION_DAYS` | `7` | How long run artifacts (downloads, failure dumps, traces) are kept |
@@ -41,6 +42,11 @@ All settings are validated at startup by `server/src/config/app.config.ts`.
| `RUN_LOG_DATA_COLLAPSE_LINES` | `5` | Same, for the number of lines | | `RUN_LOG_DATA_COLLAPSE_LINES` | `5` | Same, for the number of lines |
| `CLIENT_DIR` | *(empty)* | Directory with the built client to serve at `/` (the Docker image sets it to `client`); empty means the server doesn't serve the UI | | `CLIENT_DIR` | *(empty)* | Directory with the built client to serve at `/` (the Docker image sets it to `client`); empty means the server doesn't serve the UI |
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to a Chromium binary to use instead of Playwright's own. Not set in Docker: the image ships Playwright's `chromium-headless-shell` (matching the Playwright version) under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`. | | `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to a Chromium binary to use instead of Playwright's own. Not set in Docker: the image ships Playwright's `chromium-headless-shell` (matching the Playwright version) under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`. |
| `AUTH_ENABLED` | `false` | Opt-in account authentication. With the default `false`, the existing UI, REST API and MCP remain available without accounts. |
| `AUTH_JWT_SECRET` | *(empty)* | Required and non-empty when `AUTH_ENABLED=true`. Keep it private and stable across restarts; changing it invalidates existing tokens. |
| `AUTH_COOKIE_NAME` | `liqa_auth` | Name of the browser's HttpOnly session cookie. |
| `AUTH_JWT_EXPIRES_IN` | `24h` | Default lifetime for browser sessions and CLI-issued tokens. Positive durations use `s`, `m`, `h` or `d`. |
| `AUTH_REVOKED_TOKEN_CLEANUP_CRON` | `0 3 * * *` | When expired logout revocations are cleaned. Cleanup also runs once at startup and is disabled when auth is off. |
--- ---
@@ -103,6 +109,54 @@ 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. 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.
### Enabling authentication
Authentication is disabled by default, so a fresh install needs no auth settings. For Docker Compose, set these in the project `.env` (keep it out of version control):
```dotenv
AUTH_ENABLED=true
AUTH_JWT_SECRET=<private-random-secret>
```
Use a long, randomly generated secret from your secret manager; do not use the placeholder literally or commit a real value. `AUTH_ENABLED` accepts only `true` or `false`. When enabled, startup fails if the signing secret is blank or the configured token lifetime/cleanup schedule is invalid. Rebuild/restart the container after changing its configuration. Compose applies pending migrations before starting the server. For local development, export the same variables in the server process environment (or put them in `server/.env`); run `npm -w server run build` and `npm -w server run migration:run` before account commands or server startup. Migrations add the user and revoked-token tables and are required even when authentication is disabled.
When auth is enabled, REST and MCP controller routes require a valid bearer token or browser cookie except `GET /health`, `GET /healthz`, `GET /manifest.json`, and `POST /api/v1/auth/login`. Login is public so a browser can establish its session. The manifest exposes whether auth is enabled; health endpoints return service status. The UI assets and Swagger UI at `/docs` remain reachable, while API operations invoked from Swagger require authentication. MCP at `/mcp` and the run-events stream are protected. When auth is disabled, the guard allows existing requests through.
## 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. The CLI uses the same `DB_PATH` as the server; locally it resolves the default `data/liqa.db` relative to `server/`, while inside the container it uses the configured path (normally `/app/data/liqa.db`, persisted by the `./data:/app/data` volume).
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; password entry is hidden and requires an interactive terminal. A duplicate username, blank username/password, mismatch or invalid input fails with a nonzero exit. The other commands require an existing username; lookup output contains only the account id, username and timestamps. Unknown usernames fail with `No account found for that username.` and a nonzero exit. A token duration must be a positive number followed by `s`, `m`, `h` or `d` (for example `30m`, `1h`, `7d`); omitted duration uses `AUTH_JWT_EXPIRES_IN` (`24h` by default). 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. General CLI failures print a concise hint to check auth settings, `DB_PATH` and migrations.
### Browser sessions, logout and development origins
With auth enabled, the UI asks for credentials at `/login`. `POST /api/v1/auth/login` sets a signed session in an HttpOnly, `SameSite=Strict` cookie (default name `liqa_auth`) whose expiry matches the JWT lifetime. The cookie gets the `Secure` attribute when the request is HTTPS, including when the server sees `X-Forwarded-Proto: https`; serve production traffic over HTTPS and configure trusted proxy headers accordingly. JavaScript cannot read the token. `POST /api/v1/auth/logout` revokes the presented token and clears the cookie. Revoked tokens remain rejected until their expiration; deleted accounts also cause their tokens to be rejected on the next authentication.
Expired revocation rows are removed at startup and by `AUTH_REVOKED_TOKEN_CLEANUP_CRON` (default `0 3 * * *`, daily at 03:00 server time). The cleanup is not scheduled when authentication is disabled. Browser run notifications use the authenticated `GET /api/v1/scenarios/runs/events` event stream.
For local Vite development, the server's default CORS origins are `http://localhost:5173` and `http://127.0.0.1:5173` outside production. Vite has no API proxy: set `VITE_API_URL=http://localhost:3000/api/v1` when using a local server, or use `npm -w client run dev:compose-api` to target `http://localhost:13000`. The API's default CORS list also permits the compose origins `http://localhost:13000` and `http://127.0.0.1:13000` in production. Keep the UI and API on the same host name (`localhost` with `localhost`, or `127.0.0.1` with `127.0.0.1`) so the strict cookie remains same-site. For a different origin, set `CORS_ORIGINS` to the exact comma-separated UI origins; use HTTPS in deployed environments.
**Changing the schema** (adding or changing an entity): **Changing the schema** (adding or changing an entity):
1. Change the entity and build (`npm -w server run build`). 1. Change the entity and build (`npm -w server run build`).
@@ -138,7 +192,7 @@ Watch mode:
npm -w server run test:watch npm -w server run test:watch
``` ```
Print the NestJS logs of the test app (they're silenced by default; `DEBUG=test`): Server application logs use debug output during tests. They remain quiet unless the `test` namespace is enabled. To see NestJS and application logs:
```bash ```bash
npm -w server run test:debug npm -w server run test:debug
+14 -1
View File
@@ -2,6 +2,19 @@
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport), e.g. `http://localhost:13000/mcp` with the compose setup. Each request is served by a fresh MCP server, so there is no MCP session state between calls. The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport), e.g. `http://localhost:13000/mcp` with the compose setup. Each request is served by a fresh MCP server, so there is no MCP session state between calls.
Authentication is disabled by default. When `AUTH_ENABLED=true`, MCP requests must include a valid bearer token from the operator CLI (`user:token`); browser cookies are accepted by the HTTP API, but MCP clients should use the bearer header. For an MCP client that supports custom HTTP headers, configure the endpoint and header like this (replace the synthetic token with a privately issued token):
```json
{
"url": "https://liqa.example/mcp",
"headers": {
"Authorization": "Bearer <synthetic-token>"
}
}
```
Keep the token secret and renew it when it expires. See [development.md](development.md#operator-account-commands) for provisioning and token issuance. With auth disabled, omit the authorization header.
The server registers the following tools. All entity IDs are UUIDs; list tools are paginated (`page`, `limit`, and where noted `orderBy` / `orderDir`). Errors are returned as MCP tool errors (`isError: true`) with the message as text. The server registers the following tools. All entity IDs are UUIDs; list tools are paginated (`page`, `limit`, and where noted `orderBy` / `orderDir`). Errors are returned as MCP tool errors (`isError: true`) with the message as text.
## Sessions ## Sessions
@@ -61,7 +74,7 @@ The server registers the following tools. All entity IDs are UUIDs; list tools a
| `export_scenario` | Export one scenario version (optional `version`, defaults to the latest) | | `export_scenario` | Export one scenario version (optional `version`, defaults to the latest) |
| `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in [scenario.md](scenario.md)) | | `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in [scenario.md](scenario.md)) |
| `import_yaml` | Import any mix of environments, credentials, snippets and scenarios from YAML (see "Import" in [scenario.md](scenario.md)) | | `import_yaml` | Import any mix of environments, credentials, snippets and scenarios from YAML (see "Import" in [scenario.md](scenario.md)) |
| `export_e2e_test` | Export a scenario as a standalone Playwright test project (zip, base64) | | `export_e2e_test` | Export one scenario version as a standalone Playwright test project (zip, base64; optional `version`, defaults to the latest) |
Changes to scenario content (fields and steps) create a new scenario version; credential assignments and files are not versioned. Changes to scenario content (fields and steps) create a new scenario version; credential assignments and files are not versioned.
+4
View File
@@ -114,6 +114,10 @@ steps:
execCode: await context.page.goto(context.getEnv("base_url")); execCode: await context.page.goto(context.getEnv("base_url"));
``` ```
### E2e test export
`GET /scenarios/:id/export-e2e` (the "Export e2e test" button, the `export_e2e_test` MCP tool) exports one scenario version as a standalone Playwright test project, zipped as `<scenario>-v<N>-e2e-test.zip`. It takes an optional `version` (default: the latest). Snippets are bundled the same way as in the scenario export: the latest version for plain `runSnippet("alias")` calls, plus each version pinned with `alias@N`. The environment, credentials and files are the scenario's current ones; they are not versioned.
## Playwright traces ## Playwright traces
A run can record a [Playwright trace](https://playwright.dev/docs/trace-viewer) of its browser context (screenshots and DOM snapshots). When the run finishes, the trace is uploaded to the run's files as `trace.zip`. Download it from the run detail page, then open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev. A run can record a [Playwright trace](https://playwright.dev/docs/trace-viewer) of its browser context (screenshots and DOM snapshots). When the run finishes, the trace is uploaded to the run's files as `trace.zip`. Download it from the run detail page, then open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
+3 -3
View File
@@ -1,12 +1,12 @@
{ {
"name": "liqa", "name": "liqa",
"version": "1.25.0", "version": "1.26.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "liqa", "name": "liqa",
"version": "1.25.0", "version": "1.26.0",
"license": "MIT", "license": "MIT",
"workspaces": [ "workspaces": [
"server", "server",
@@ -17464,6 +17464,7 @@
"better-sqlite3": "^12.8.0", "better-sqlite3": "^12.8.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.4", "class-validator": "^0.14.4",
"debug": "^4.4.3",
"effect": "^3.21.0", "effect": "^3.21.0",
"jsdom": "^29.0.2", "jsdom": "^29.0.2",
"playwright": "^1.59.1", "playwright": "^1.59.1",
@@ -17487,7 +17488,6 @@
"@types/mozilla__readability": "^0.4.2", "@types/mozilla__readability": "^0.4.2",
"@types/node": "^25.5.2", "@types/node": "^25.5.2",
"@types/supertest": "^7.2.0", "@types/supertest": "^7.2.0",
"debug": "^4.4.3",
"eslint": "^10.2.0", "eslint": "^10.2.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"jest": "^30.3.0", "jest": "^30.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "liqa", "name": "liqa",
"version": "1.25.0", "version": "1.26.0",
"private": true, "private": true,
"license": "MIT", "license": "MIT",
"author": "Andrii Arsenin", "author": "Andrii Arsenin",
+1
View File
@@ -6,6 +6,7 @@ module.exports = {
transform: { transform: {
'^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }], '^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }],
}, },
setupFiles: ['<rootDir>/test/logging.setup.js'],
moduleNameMapper: { moduleNameMapper: {
'^jsdom$': '<rootDir>/test/__mocks__/jsdom.ts', '^jsdom$': '<rootDir>/test/__mocks__/jsdom.ts',
'^playwright$': '<rootDir>/test/__mocks__/playwright.ts', '^playwright$': '<rootDir>/test/__mocks__/playwright.ts',
+2 -1
View File
@@ -10,6 +10,7 @@
"migration:run": "node dist/database/migrate", "migration:run": "node dist/database/migrate",
"migration:show": "typeorm migration:show -d dist/database/data-source.js", "migration:show": "typeorm migration:show -d dist/database/data-source.js",
"migration:generate": "typeorm migration:generate -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\"", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"", "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"", "lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
@@ -37,6 +38,7 @@
"better-sqlite3": "^12.8.0", "better-sqlite3": "^12.8.0",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.4", "class-validator": "^0.14.4",
"debug": "^4.4.3",
"effect": "^3.21.0", "effect": "^3.21.0",
"jsdom": "^29.0.2", "jsdom": "^29.0.2",
"playwright": "^1.59.1", "playwright": "^1.59.1",
@@ -60,7 +62,6 @@
"@types/mozilla__readability": "^0.4.2", "@types/mozilla__readability": "^0.4.2",
"@types/node": "^25.5.2", "@types/node": "^25.5.2",
"@types/supertest": "^7.2.0", "@types/supertest": "^7.2.0",
"debug": "^4.4.3",
"eslint": "^10.2.0", "eslint": "^10.2.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"jest": "^30.3.0", "jest": "^30.3.0",
+2
View File
@@ -4,6 +4,7 @@ import { ScheduleModule } from "@nestjs/schedule";
import { ServeStaticModule } from "@nestjs/serve-static"; import { ServeStaticModule } from "@nestjs/serve-static";
import { TypeOrmModule } from "@nestjs/typeorm"; import { TypeOrmModule } from "@nestjs/typeorm";
import { BrowserModule } from "./browser/browser.module"; import { BrowserModule } from "./browser/browser.module";
import { AuthModule } from "./auth/auth.module";
import { clientStaticOptions } from "./common/client-static"; import { clientStaticOptions } from "./common/client-static";
import { dataSourceOptions } from "./database/data-source"; import { dataSourceOptions } from "./database/data-source";
import { AppConfig, validateAppConfig } from "./config/app.config"; import { AppConfig, validateAppConfig } from "./config/app.config";
@@ -36,6 +37,7 @@ import { SnippetModule } from "./snippet/snippet.module";
dataSourceOptions(config.get("DB_PATH")), dataSourceOptions(config.get("DB_PATH")),
}), }),
BrowserModule, BrowserModule,
AuthModule,
EnvironmentModule, EnvironmentModule,
CredentialModule, CredentialModule,
ScenarioModule, ScenarioModule,
+1
View File
@@ -0,0 +1 @@
export const AUTH_COOKIE_NAME = "liqa_auth";
+112
View File
@@ -0,0 +1,112 @@
import {
Body,
Controller,
Get,
HttpCode,
NotFoundException,
Post,
Req,
Res,
UnauthorizedException,
} from "@nestjs/common";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import type { Request, Response } from "express";
import { AuthenticatedRequest } from "./auth.guard";
import { AuthService, AuthSession, SafeUser } from "./auth.service";
import { Public } from "./public.decorator";
import { LoginDto } from "./dto/login.dto";
import {
clearedSessionCookie,
loginResponse,
sessionCookie,
sessionUser,
} from "./auth.helpers";
import { AuthFailure } from "./auth.error";
import { LoginResponseDto, SafeUserDto } from "./dto/auth-response.dto";
@ApiTags("auth")
@Controller("auth")
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post("login")
@HttpCode(200)
@Public()
@ApiOperation({ summary: "Sign in and start a browser session" })
@ApiResponse({
status: 200,
description: "Signed in; session cookie set",
type: LoginResponseDto,
})
@ApiResponse({ status: 401, description: "Invalid username or password" })
async login(
@Body() dto: LoginDto,
@Req() request: Request,
@Res({ passthrough: true }) response: Response,
): Promise<{ user: SafeUser }> {
if (!this.auth.enabled)
throw new NotFoundException("Authentication is disabled.");
let session: AuthSession;
try {
session = await this.auth.login(dto.username, dto.password);
} catch (error) {
if (error instanceof AuthFailure && error.reason === "disabled") {
throw new NotFoundException("Authentication is disabled.");
}
if (
error instanceof AuthFailure &&
error.reason === "invalid-credentials"
) {
throw new UnauthorizedException("Invalid username or password.");
}
throw error;
}
response.setHeader(
"Set-Cookie",
sessionCookie(request, session, this.auth.cookieName),
);
return loginResponse(session.user);
}
@Get("me")
@ApiBearerAuth()
@ApiOperation({ summary: "Return the current authenticated user" })
@ApiResponse({
status: 200,
description: "Safe account identity",
type: SafeUserDto,
})
@ApiResponse({ status: 401, description: "Missing or invalid credential" })
me(@Req() request: AuthenticatedRequest): SafeUser {
if (!this.auth.enabled) {
throw new NotFoundException("Authentication is disabled.");
}
if (!request.authSession) throw new UnauthorizedException();
return sessionUser(request.authSession);
}
@Post("logout")
@HttpCode(204)
@ApiBearerAuth()
@ApiOperation({ summary: "Revoke the current session and clear its cookie" })
@ApiResponse({ status: 204, description: "Session revoked" })
async logout(
@Req() request: AuthenticatedRequest,
@Res({ passthrough: true }) response: Response,
): Promise<void> {
if (!this.auth.enabled) {
throw new NotFoundException("Authentication is disabled.");
}
if (!request.authSession) throw new UnauthorizedException();
await this.auth.revoke(request.authSession);
response.setHeader(
"Set-Cookie",
clearedSessionCookie(request, this.auth.cookieName),
);
}
}
+9
View File
@@ -0,0 +1,9 @@
export type AuthFailureReason =
"disabled" | "invalid-credentials" | "invalid-token";
export class AuthFailure extends Error {
constructor(readonly reason: AuthFailureReason) {
super(reason);
this.name = "AuthFailure";
}
}
+43
View File
@@ -0,0 +1,43 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import type { Request } from "express";
import { AuthService, AuthSession } from "./auth.service";
import { requestToken } from "./auth.helpers";
import { IS_PUBLIC_KEY } from "./public.decorator";
import { AuthFailure } from "./auth.error";
export interface AuthenticatedRequest extends Request {
authSession?: AuthSession;
}
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly auth: AuthService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic || !this.auth.enabled) return true;
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
const token = requestToken(request, this.auth.cookieName);
if (!token) throw new UnauthorizedException();
try {
request.authSession = await this.auth.authenticate(token);
} catch (error) {
if (error instanceof AuthFailure) throw new UnauthorizedException();
throw error;
}
return true;
}
}
+74
View File
@@ -0,0 +1,74 @@
import type { Request } from "express";
import { AUTH_COOKIE_NAME } from "./auth.constants";
import type { AuthSession, SafeUser } from "./auth.service";
export function isHttps(request: Request): boolean {
const forwarded = request.get("x-forwarded-proto")?.split(",")[0].trim();
return request.secure || forwarded === "https";
}
export function sessionCookie(
request: Request,
session: AuthSession,
cookieName = AUTH_COOKIE_NAME,
): string {
const maxAge = Math.max(
0,
Math.floor((session.expiresAt.getTime() - Date.now()) / 1000),
);
const options = ["Path=/", "HttpOnly", "SameSite=Strict"];
if (isHttps(request)) options.push("Secure");
options.push(
`Max-Age=${maxAge}`,
`Expires=${session.expiresAt.toUTCString()}`,
);
return `${cookieName}=${encodeURIComponent(session.token)}; ${options.join("; ")}`;
}
export function clearedSessionCookie(
request: Request,
cookieName = AUTH_COOKIE_NAME,
): string {
const options = ["Path=/", "HttpOnly", "SameSite=Strict"];
if (isHttps(request)) options.push("Secure");
options.push("Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT");
return `${cookieName}=; ${options.join("; ")}`;
}
export function loginResponse(user: SafeUser): { user: SafeUser } {
return { user };
}
export function sessionUser(session: AuthSession): SafeUser {
return session.user;
}
export function cookieToken(
header: string | undefined,
cookieName = AUTH_COOKIE_NAME,
): string | undefined {
if (!header) return undefined;
for (const item of header.split(";")) {
const separator = item.indexOf("=");
if (separator < 0 || item.slice(0, separator).trim() !== cookieName) {
continue;
}
try {
return decodeURIComponent(item.slice(separator + 1).trim());
} catch {
return undefined;
}
}
return undefined;
}
export function requestToken(
request: Request,
cookieName = AUTH_COOKIE_NAME,
): string | undefined {
const authorization = request.get("authorization");
if (authorization) {
return /^Bearer\s+(.+)$/i.exec(authorization)?.[1].trim();
}
return cookieToken(request.get("cookie"), cookieName);
}
+23
View File
@@ -0,0 +1,23 @@
import { Module } from "@nestjs/common";
import { APP_GUARD } from "@nestjs/core";
import { TypeOrmModule } from "@nestjs/typeorm";
import { AuthController } from "./auth.controller";
import { AuthGuard } from "./auth.guard";
import { AuthService } from "./auth.service";
import { PasswordService } from "./password.service";
import { RevokedTokenEntity } from "./revoked-token.entity";
import { RevokedTokenCleanupService } from "./revoked-token-cleanup.service";
import { UserEntity } from "./user.entity";
@Module({
imports: [TypeOrmModule.forFeature([UserEntity, RevokedTokenEntity])],
controllers: [AuthController],
providers: [
AuthService,
PasswordService,
RevokedTokenCleanupService,
{ provide: APP_GUARD, useClass: AuthGuard },
],
exports: [AuthService, PasswordService],
})
export class AuthModule {}
+102
View File
@@ -0,0 +1,102 @@
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { AppConfig } from "../config/app.config";
import { durationSeconds } from "../common/interval";
import { PasswordService } from "./password.service";
import { RevokedTokenEntity } from "./revoked-token.entity";
import { UserEntity } from "./user.entity";
import { AuthFailure } from "./auth.error";
import { issueJwt, safeUser, tokenHash, verifyJwt } from "./jwt.helpers";
export interface SafeUser {
id: string;
username: string;
createdAt: Date;
updatedAt: Date;
}
export interface AuthSession {
user: SafeUser;
token: string;
expiresAt: Date;
}
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserEntity)
private readonly users: Repository<UserEntity>,
@InjectRepository(RevokedTokenEntity)
private readonly revokedTokens: Repository<RevokedTokenEntity>,
private readonly config: ConfigService<AppConfig, true>,
private readonly passwords: PasswordService,
) {}
get enabled(): boolean {
return this.config.get("AUTH_ENABLED");
}
get cookieName(): string {
return this.config.get("AUTH_COOKIE_NAME");
}
async login(username: string, password: string): Promise<AuthSession> {
if (!this.enabled) {
throw new AuthFailure("disabled");
}
const user = await this.users.findOneBy({ username });
const valid = user
? await this.passwords.verify(password, user.passwordHash)
: false;
if (!user || !valid) {
throw new AuthFailure("invalid-credentials");
}
return this.issueToken(user);
}
issueToken(
user: Pick<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
): AuthSession {
if (!this.enabled) {
throw new AuthFailure("disabled");
}
const expiresIn = durationSeconds(this.config.get("AUTH_JWT_EXPIRES_IN"));
if (expiresIn === null) {
throw new Error("AUTH_JWT_EXPIRES_IN is not a valid positive duration.");
}
const { token, expiresAt } = issueJwt(
user.id,
expiresIn,
this.config.get("AUTH_JWT_SECRET"),
);
return {
user: safeUser(user),
token,
expiresAt,
};
}
async authenticate(token: string): Promise<AuthSession> {
const payload = verifyJwt(token, this.config.get("AUTH_JWT_SECRET"));
const digest = tokenHash(token);
if (await this.revokedTokens.findOneBy({ tokenHash: digest })) {
throw new AuthFailure("invalid-token");
}
const user = await this.users.findOneBy({ id: payload.sub });
if (!user) throw new AuthFailure("invalid-token");
return {
user: safeUser(user),
token,
expiresAt: new Date(payload.exp * 1000),
};
}
async revoke(session: AuthSession): Promise<void> {
await this.revokedTokens.save({
tokenHash: tokenHash(session.token),
expiresAt: session.expiresAt,
});
}
}
+20
View File
@@ -0,0 +1,20 @@
import { ApiProperty } from "@nestjs/swagger";
export class SafeUserDto {
@ApiProperty()
id!: string;
@ApiProperty()
username!: string;
@ApiProperty({ type: String, format: "date-time" })
createdAt!: Date;
@ApiProperty({ type: String, format: "date-time" })
updatedAt!: Date;
}
export class LoginResponseDto {
@ApiProperty({ type: SafeUserDto })
user!: SafeUserDto;
}
+13
View File
@@ -0,0 +1,13 @@
import { IsNotEmpty, IsString, MaxLength } from "class-validator";
export class LoginDto {
@IsString()
@IsNotEmpty()
@MaxLength(250)
username!: string;
@IsString()
@IsNotEmpty()
@MaxLength(1024)
password!: string;
}
+98
View File
@@ -0,0 +1,98 @@
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { AuthFailure } from "./auth.error";
import { SafeUser } from "./auth.service";
import { UserEntity } from "./user.entity";
export interface JwtPayload {
sub: string;
iat: number;
exp: number;
}
export function safeUser(
user: Pick<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
): SafeUser {
return {
id: user.id,
username: user.username,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
};
}
export function tokenHash(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
function base64UrlJson(value: unknown): string {
return Buffer.from(JSON.stringify(value)).toString("base64url");
}
function sign(unsigned: string, secret: string): string {
return createHmac("sha256", secret).update(unsigned).digest("base64url");
}
export function issueJwt(
userId: string,
expiresIn: number,
secret: string,
): { token: string; expiresAt: Date } {
const issuedAt = Math.floor(Date.now() / 1000);
const payload: JwtPayload = {
sub: userId,
iat: issuedAt,
exp: issuedAt + expiresIn,
};
const unsigned = `${base64UrlJson({ alg: "HS256", typ: "JWT" })}.${base64UrlJson(payload)}`;
return {
token: `${unsigned}.${sign(unsigned, secret)}`,
expiresAt: new Date(payload.exp * 1000),
};
}
export function verifyJwt(token: string, secret: string): JwtPayload {
const parts = token.split(".");
if (parts.length !== 3 || parts.some((part) => part.length === 0))
throw new AuthFailure("invalid-token");
const [encodedHeader, encodedPayload, encodedSignature] = parts;
let header: unknown;
let payload: unknown;
let supplied: Buffer;
try {
header = JSON.parse(
Buffer.from(encodedHeader, "base64url").toString("utf8"),
);
payload = JSON.parse(
Buffer.from(encodedPayload, "base64url").toString("utf8"),
);
supplied = Buffer.from(encodedSignature, "base64url");
} catch {
throw new AuthFailure("invalid-token");
}
if (
!header ||
typeof header !== "object" ||
(header as { alg?: unknown }).alg !== "HS256"
)
throw new AuthFailure("invalid-token");
const unsigned = `${encodedHeader}.${encodedPayload}`;
const expected = Buffer.from(sign(unsigned, secret), "base64url");
if (
expected.length !== supplied.length ||
!timingSafeEqual(expected, supplied)
)
throw new AuthFailure("invalid-token");
if (!payload || typeof payload !== "object")
throw new AuthFailure("invalid-token");
const claims = payload as Partial<JwtPayload>;
const now = Math.floor(Date.now() / 1000);
if (
typeof claims.sub !== "string" ||
!claims.sub ||
!Number.isSafeInteger(claims.iat) ||
!Number.isSafeInteger(claims.exp) ||
(claims.exp as number) <= now
)
throw new AuthFailure("invalid-token");
return claims as JwtPayload;
}
+95
View File
@@ -0,0 +1,95 @@
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
import { Injectable } from "@nestjs/common";
// N=2^14 is the baseline scrypt CPU/memory cost; verify permits bounded future upgrades.
const SCRYPT_N = 16384;
// r=8 and p=1 are the standard scrypt block size and parallelization for this cost.
const SCRYPT_R = 8;
const SCRYPT_P = 1;
// A 128-bit random salt prevents practical salt collisions across stored passwords.
const SALT_BYTES = 16;
// 512-bit output gives ample margin for password verification.
const HASH_BYTES = 64;
function derive(
password: string,
salt: Buffer,
length: number,
N: number,
r: number,
p: number,
): Promise<Buffer> {
const maxmem = 128 * N * r + 2 * 1024 * 1024;
return new Promise((resolve, reject) => {
scrypt(password, salt, length, { N, r, p, maxmem }, (error, key) => {
if (error) reject(error);
else resolve(key as Buffer);
});
});
}
@Injectable()
export class PasswordService {
async hash(password: string): Promise<string> {
const salt = randomBytes(SALT_BYTES);
const hash = await derive(
password,
salt,
HASH_BYTES,
SCRYPT_N,
SCRYPT_R,
SCRYPT_P,
);
return [
"scrypt",
SCRYPT_N,
SCRYPT_R,
SCRYPT_P,
salt.toString("base64url"),
hash.toString("base64url"),
].join("$");
}
async verify(password: string, encodedHash: string): Promise<boolean> {
const [algorithm, rawN, rawR, rawP, rawSalt, rawHash, ...extra] =
encodedHash.split("$");
if (
algorithm !== "scrypt" ||
extra.length > 0 ||
!rawN ||
!rawR ||
!rawP ||
!rawSalt ||
!rawHash
) {
return false;
}
const N = Number(rawN);
const r = Number(rawR);
const p = Number(rawP);
const salt = Buffer.from(rawSalt, "base64url");
const expected = Buffer.from(rawHash, "base64url");
if (
!Number.isSafeInteger(N) ||
N < 16384 ||
N > 65536 ||
(N & (N - 1)) !== 0 ||
!Number.isSafeInteger(r) ||
r < 1 ||
r > 16 ||
!Number.isSafeInteger(p) ||
p < 1 ||
p > 4 ||
salt.length < 16 ||
salt.length > 64 ||
expected.length < 32 ||
expected.length > 128
) {
return false;
}
const actual = await derive(password, salt, expected.length, N, r, p);
return timingSafeEqual(actual, expected);
}
}
+4
View File
@@ -0,0 +1,4 @@
import { SetMetadata } from "@nestjs/common";
export const IS_PUBLIC_KEY = Symbol("isPublic");
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
@@ -0,0 +1,76 @@
import { Injectable, OnModuleInit } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { SchedulerRegistry } from "@nestjs/schedule";
import { InjectRepository } from "@nestjs/typeorm";
import { CronJob } from "cron";
import { LessThanOrEqual, Repository } from "typeorm";
import { createAppLogger } from "../common/app-logger";
import { AppConfig } from "../config/app.config";
import { RevokedTokenEntity } from "./revoked-token.entity";
export const AUTH_REVOKED_TOKEN_CLEANUP_JOB = "auth-revoked-token-cleanup";
@Injectable()
export class RevokedTokenCleanupService implements OnModuleInit {
private readonly logger = createAppLogger(RevokedTokenCleanupService.name);
private readonly enabled: boolean;
private readonly cleanupCron: string;
constructor(
@InjectRepository(RevokedTokenEntity)
private readonly revokedTokens: Repository<RevokedTokenEntity>,
config: ConfigService<AppConfig, true>,
private readonly schedulerRegistry: SchedulerRegistry,
) {
this.enabled = config.get("AUTH_ENABLED");
this.cleanupCron = config.get("AUTH_REVOKED_TOKEN_CLEANUP_CRON");
}
async onModuleInit(): Promise<void> {
if (!this.enabled) return;
const job = CronJob.from({
cronTime: this.cleanupCron,
start: false,
waitForCompletion: true,
onTick: async () => {
try {
await this.cleanupExpiredTokens();
} catch (error) {
this.logger.error(
`Failed to clean up expired revoked tokens: ${this.errorMessage(error)}`,
);
}
},
});
this.schedulerRegistry.addCronJob(AUTH_REVOKED_TOKEN_CLEANUP_JOB, job);
job.start();
this.logger.debug(
`Revoked-token cleanup cron registered: ${this.cleanupCron}`,
);
try {
await this.cleanupExpiredTokens();
} catch (error) {
this.logger.error(
`Failed to clean up expired revoked tokens at startup: ${this.errorMessage(error)}`,
);
}
}
async cleanupExpiredTokens(): Promise<void> {
if (!this.enabled) return;
const now = new Date();
const result = await this.revokedTokens.delete({
expiresAt: LessThanOrEqual(now),
});
if (result.affected) {
this.logger.debug(`Cleaned up ${result.affected} expired revoked tokens`);
}
}
private errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
}
+11
View File
@@ -0,0 +1,11 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
/** A SHA-256 digest of a JWT that has been logged out. */
@Entity("revoked_tokens")
export class RevokedTokenEntity {
@PrimaryColumn({ length: 64 })
tokenHash: string;
@Column({ type: "datetime" })
expiresAt: Date;
}
+26
View File
@@ -0,0 +1,26 @@
import {
Column,
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from "typeorm";
/** Local operator-managed account. Password hashes are never returned by the API. */
@Entity("users")
export class UserEntity {
@PrimaryGeneratedColumn("uuid")
id: string;
@Column({ unique: true })
username: string;
@Column("text")
passwordHash: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
+7 -1
View File
@@ -1,5 +1,10 @@
import { Body, Controller, Post } from "@nestjs/common"; import { Body, Controller, Post } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { CodeExecutorService } from "../code-executor/code-executor.service"; import { CodeExecutorService } from "../code-executor/code-executor.service";
import { CredentialService } from "../credential/credential.service"; import { CredentialService } from "../credential/credential.service";
import { EnvironmentService } from "../environment/environment.service"; import { EnvironmentService } from "../environment/environment.service";
@@ -8,6 +13,7 @@ import { ExecDto } from "./dto/exec.dto";
import { OpenDto } from "./dto/open.dto"; import { OpenDto } from "./dto/open.dto";
@ApiTags("browser") @ApiTags("browser")
@ApiBearerAuth()
@Controller() @Controller()
export class BrowserController { export class BrowserController {
constructor( constructor(
+2 -2
View File
@@ -12,7 +12,7 @@ import type {
ScriptLogger, ScriptLogger,
} from "../code-executor/code-executor.service"; } from "../code-executor/code-executor.service";
import { CodeExecutorService } from "../code-executor/code-executor.service"; import { CodeExecutorService } from "../code-executor/code-executor.service";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
import type { EnvironmentData } from "../environment/environment.entity"; import type { EnvironmentData } from "../environment/environment.entity";
import { SessionContextService } from "../session/session-context.service"; import { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service"; import { SessionService } from "../session/session.service";
@@ -28,7 +28,7 @@ export interface OpenResult {
@Injectable() @Injectable()
export class BrowserService { export class BrowserService {
private readonly logger = new TraceLogger(BrowserService.name); private readonly logger = createAppLogger(BrowserService.name);
constructor( constructor(
private readonly sessionContextService: SessionContextService, private readonly sessionContextService: SessionContextService,
+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;
});
@@ -8,7 +8,7 @@ import { parse } from "acorn";
import type { BrowserContext, Page } from "playwright"; import type { BrowserContext, Page } from "playwright";
import { URL } from "node:url"; import { URL } from "node:url";
import { downloadFile as downloadFileImpl } from "../common/file-downloader"; import { downloadFile as downloadFileImpl } from "../common/file-downloader";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
import type { EnvironmentData } from "../environment/environment.entity"; import type { EnvironmentData } from "../environment/environment.entity";
import type { FileStorageService } from "../file/file-storage.service"; import type { FileStorageService } from "../file/file-storage.service";
import type { DomNode } from "./dom-helpers"; import type { DomNode } from "./dom-helpers";
@@ -115,7 +115,7 @@ export interface ExecContext {
@Injectable() @Injectable()
export class CodeExecutorService { export class CodeExecutorService {
private readonly logger = new TraceLogger(CodeExecutorService.name); private readonly logger = createAppLogger(CodeExecutorService.name);
/** /**
* Validates `code` by wrapping it in an async function body and attempting * Validates `code` by wrapping it in an async function body and attempting
+14
View File
@@ -0,0 +1,14 @@
import { ConsoleLoggerOptions } from "@nestjs/common";
import { LogMode } from "../config/app.config";
import { DebugLogger } from "./debug-logger";
import { TraceLogger } from "./trace-logger";
/** Select the application's logger implementation at the configuration boundary. */
export function createAppLogger(
context?: string,
options?: ConsoleLoggerOptions,
) {
return process.env.LOG_MODE === LogMode.Debug
? new DebugLogger(context, options)
: new TraceLogger(context, options);
}
+66
View File
@@ -0,0 +1,66 @@
import { ConsoleLogger, ConsoleLoggerOptions, LogLevel } from "@nestjs/common";
// eslint-disable-next-line @typescript-eslint/no-require-imports
import createDebug = require("debug");
import { getTraceId } from "./trace-context";
/** Logger that routes all framework and application diagnostics through DEBUG. */
export class DebugLogger extends ConsoleLogger {
private readonly loggerContext: string;
constructor(context?: string, options: ConsoleLoggerOptions = {}) {
super(context as string, options);
this.loggerContext = context ?? "Application";
}
override log(...args: Parameters<ConsoleLogger["log"]>): void {
this.write("log", args);
}
override error(...args: Parameters<ConsoleLogger["error"]>): void {
this.write("error", args);
}
override warn(...args: Parameters<ConsoleLogger["warn"]>): void {
this.write("warn", args);
}
override debug(...args: Parameters<ConsoleLogger["debug"]>): void {
this.write("debug", args);
}
override verbose(...args: Parameters<ConsoleLogger["verbose"]>): void {
this.write("verbose", args);
}
override fatal(...args: Parameters<ConsoleLogger["fatal"]>): void {
this.write("fatal", args);
}
private write(level: LogLevel, args: unknown[]): void {
const [message, ...optionalParams] = args;
const last = optionalParams[optionalParams.length - 1];
const lastIsErrorStack =
level === "error" &&
optionalParams.length === 1 &&
typeof last === "string" &&
/(?:\n|^\s*at\s)/.test(last);
const context =
typeof last === "string" && !lastIsErrorStack ? last : this.loggerContext;
const details =
typeof last === "string" && !lastIsErrorStack
? optionalParams.slice(0, -1)
: optionalParams;
const traceId = getTraceId();
const tracedContext = traceId ? `${context}:${traceId}` : context;
const namespace =
process.env.NODE_ENV === "test"
? "test"
: `liqa:${context.toLowerCase()}`;
const stringify = (value: unknown): string => {
if (value instanceof Error) return value.stack ?? value.message;
if (typeof value === "string") return value;
try {
return JSON.stringify(value);
} catch {
return String(value);
}
};
const output = `[${level.toUpperCase()}] [${tracedContext}] ${stringify(message)}${details.length ? ` ${details.map(stringify).filter(Boolean).join(" ")}` : ""}`;
createDebug(namespace)("%s", output);
}
}
+11
View File
@@ -0,0 +1,11 @@
/** Parse a positive duration (seconds, minutes, hours, or days) into seconds. */
export function durationSeconds(value: string): number | null {
const match = /^(\d+)(s|m|h|d)$/.exec(value);
if (!match) return null;
const amount = Number(match[1]);
const multiplier = { s: 1, m: 60, h: 3600, d: 86400 }[
match[2] as "s" | "m" | "h" | "d"
];
const seconds = amount * multiplier;
return Number.isSafeInteger(seconds) && seconds > 0 ? seconds : null;
}
+6 -6
View File
@@ -1,6 +1,7 @@
import { ConsoleLogger, ConsoleLoggerOptions, LogLevel } from "@nestjs/common"; import { ConsoleLogger, ConsoleLoggerOptions, LogLevel } from "@nestjs/common";
import { getTraceId } from "./trace-context"; import { getTraceId } from "./trace-context";
/** Runtime console logger. Output is always written using Nest's console behavior. */
export class TraceLogger extends ConsoleLogger { export class TraceLogger extends ConsoleLogger {
constructor(context?: string, options: ConsoleLoggerOptions = {}) { constructor(context?: string, options: ConsoleLoggerOptions = {}) {
super(context as string, options); super(context as string, options);
@@ -10,6 +11,11 @@ export class TraceLogger extends ConsoleLogger {
return new Date().toISOString(); return new Date().toISOString();
} }
protected override formatContext(context: string): string {
const traceId = getTraceId();
return super.formatContext(traceId ? `${context}:${traceId}` : context);
}
protected override formatMessage( protected override formatMessage(
logLevel: LogLevel, logLevel: LogLevel,
message: unknown, message: unknown,
@@ -22,10 +28,4 @@ export class TraceLogger extends ConsoleLogger {
const level = this.colorize(logLevel.toUpperCase(), logLevel); const level = this.colorize(logLevel.toUpperCase(), logLevel);
return `${this.getTimestamp()} ${level} ${contextMessage}${output}${timestampDiff}\n`; return `${this.getTimestamp()} ${level} ${contextMessage}${output}${timestampDiff}\n`;
} }
protected override formatContext(context: string): string {
const traceId = getTraceId();
const traced = traceId ? `${context}:${traceId}` : context;
return super.formatContext(traced);
}
} }
+65 -1
View File
@@ -1,5 +1,7 @@
import "reflect-metadata";
import { plainToInstance } from "class-transformer"; import { plainToInstance } from "class-transformer";
import { import {
IsBoolean,
IsEnum, IsEnum,
IsInt, IsInt,
IsString, IsString,
@@ -10,12 +12,19 @@ import {
import { appPackage } from "../common/app-package"; import { appPackage } from "../common/app-package";
import { durationSeconds } from "../common/interval";
export enum TraceMode { export enum TraceMode {
On = "on", On = "on",
RetainOnFailure = "retain-on-failure", RetainOnFailure = "retain-on-failure",
Off = "off", Off = "off",
} }
export enum LogMode {
Console = "console",
Debug = "debug",
}
export class AppConfig { export class AppConfig {
/** `production` in the Docker image; also selects the default CORS origins. */ /** `production` in the Docker image; also selects the default CORS origins. */
@IsString() @IsString()
@@ -36,6 +45,10 @@ export class AppConfig {
@IsString() @IsString()
APP_VERSION: string = appPackage().version; APP_VERSION: string = appPackage().version;
/** Route application diagnostics through `debug` instead of the console. */
@IsEnum(LogMode)
LOG_MODE: LogMode = LogMode.Console;
@IsString() @IsString()
DB_PATH: string = "data/liqa.db"; DB_PATH: string = "data/liqa.db";
@@ -74,15 +87,66 @@ export class AppConfig {
@IsInt() @IsInt()
@Min(0) @Min(0)
RUN_LOG_DATA_COLLAPSE_LINES: number = 5; RUN_LOG_DATA_COLLAPSE_LINES: number = 5;
/** Authentication is opt-in so existing deployments remain unchanged. */
@IsBoolean()
AUTH_ENABLED: boolean = false;
/** Required only when AUTH_ENABLED is true. */
@IsString()
AUTH_JWT_SECRET: string = "";
/** Cookie name used for browser sessions. */
@IsString()
AUTH_COOKIE_NAME: string = "liqa_auth";
@IsString()
AUTH_JWT_EXPIRES_IN: string = "24h";
@IsString()
AUTH_REVOKED_TOKEN_CLEANUP_CRON: string = "0 3 * * *";
} }
export function validateAppConfig(config: Record<string, unknown>): AppConfig { export function validateAppConfig(config: Record<string, unknown>): AppConfig {
const validated = plainToInstance(AppConfig, config, { const authEnabled = config.AUTH_ENABLED;
if (
authEnabled !== undefined &&
authEnabled !== true &&
authEnabled !== false &&
authEnabled !== "true" &&
authEnabled !== "false"
) {
throw new Error("AUTH_ENABLED must be either true or false.");
}
const normalized = {
...config,
AUTH_ENABLED: authEnabled === true || authEnabled === "true",
};
const validated = plainToInstance(AppConfig, normalized, {
enableImplicitConversion: true, enableImplicitConversion: true,
}); });
const errors = validateSync(validated, { skipMissingProperties: false }); const errors = validateSync(validated, { skipMissingProperties: false });
if (errors.length > 0) { if (errors.length > 0) {
throw new Error(errors.toString()); throw new Error(errors.toString());
} }
if (validated.AUTH_ENABLED && !validated.AUTH_JWT_SECRET.trim()) {
throw new Error("AUTH_JWT_SECRET must be set when AUTH_ENABLED=true.");
}
if (
validated.AUTH_ENABLED &&
durationSeconds(validated.AUTH_JWT_EXPIRES_IN) === null
) {
throw new Error(
"AUTH_JWT_EXPIRES_IN must be a positive duration such as 30m, 1h, or 24h.",
);
}
if (
validated.AUTH_ENABLED &&
!validated.AUTH_REVOKED_TOKEN_CLEANUP_CRON.trim()
) {
throw new Error(
"AUTH_REVOKED_TOKEN_CLEANUP_CRON must be set when AUTH_ENABLED=true.",
);
}
return validated; return validated;
} }
@@ -10,7 +10,12 @@ import {
Post, Post,
Query, Query,
} from "@nestjs/common"; } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { CredentialQueryDto } from "./dto/credential-query.dto"; import { CredentialQueryDto } from "./dto/credential-query.dto";
import { CredentialService } from "./credential.service"; import { CredentialService } from "./credential.service";
import { CreateCredentialDto } from "./dto/create-credential.dto"; import { CreateCredentialDto } from "./dto/create-credential.dto";
@@ -18,6 +23,7 @@ import { CredentialExportDto } from "./dto/credential-export.dto";
import { UpdateCredentialDto } from "./dto/update-credential.dto"; import { UpdateCredentialDto } from "./dto/update-credential.dto";
@ApiTags("credentials") @ApiTags("credentials")
@ApiBearerAuth()
@Controller("credentials") @Controller("credentials")
export class CredentialController { export class CredentialController {
constructor(private readonly credentialService: CredentialService) {} constructor(private readonly credentialService: CredentialService) {}
+4
View File
@@ -1,4 +1,6 @@
import { CredentialEntity } from "../credential/credential.entity"; import { CredentialEntity } from "../credential/credential.entity";
import { RevokedTokenEntity } from "../auth/revoked-token.entity";
import { UserEntity } from "../auth/user.entity";
import { EnvironmentEntity } from "../environment/environment.entity"; import { EnvironmentEntity } from "../environment/environment.entity";
import { FileEntity } from "../file/file.entity"; import { FileEntity } from "../file/file.entity";
import { ScenarioFileEntity } from "../file/scenario-file.entity"; import { ScenarioFileEntity } from "../file/scenario-file.entity";
@@ -16,6 +18,8 @@ import { SnippetEntity } from "../snippet/snippet.entity";
/** Every TypeORM entity of the app (used by the app, the migrations CLI and tests). */ /** Every TypeORM entity of the app (used by the app, the migrations CLI and tests). */
export const ENTITIES = [ export const ENTITIES = [
UserEntity,
RevokedTokenEntity,
SessionEntity, SessionEntity,
EnvironmentEntity, EnvironmentEntity,
CredentialEntity, CredentialEntity,
@@ -0,0 +1,23 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class AddAuthUsersAndRevokedTokens1793823870652 implements MigrationInterface {
name = "AddAuthUsersAndRevokedTokens1793823870652";
public async up(queryRunner: QueryRunner): Promise<void> {
if (!(await queryRunner.hasTable("users"))) {
await queryRunner.query(
`CREATE TABLE "users" ("id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, "passwordHash" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_fe0bb3f6520ee0469504521e710" UNIQUE ("username"))`,
);
}
if (!(await queryRunner.hasTable("revoked_tokens"))) {
await queryRunner.query(
`CREATE TABLE "revoked_tokens" ("tokenHash" varchar(64) PRIMARY KEY NOT NULL, "expiresAt" datetime NOT NULL)`,
);
}
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "revoked_tokens"`);
await queryRunner.query(`DROP TABLE "users"`);
}
}
+2
View File
@@ -1,6 +1,7 @@
import { Initial1790793447827 } from "./1790793447827-Initial"; import { Initial1790793447827 } from "./1790793447827-Initial";
import { AddRunLogContext1790848194828 } from "./1790848194828-AddRunLogContext"; import { AddRunLogContext1790848194828 } from "./1790848194828-AddRunLogContext";
import { AddRunLogData1790850734763 } from "./1790850734763-AddRunLogData"; import { AddRunLogData1790850734763 } from "./1790850734763-AddRunLogData";
import { AddAuthUsersAndRevokedTokens1793823870652 } from "./1793823870652-AddAuthUsersAndRevokedTokens";
/** /**
* All migrations, oldest first. Listed explicitly (instead of a glob) so the * All migrations, oldest first. Listed explicitly (instead of a glob) so the
@@ -10,4 +11,5 @@ export const MIGRATIONS = [
Initial1790793447827, Initial1790793447827,
AddRunLogContext1790848194828, AddRunLogContext1790848194828,
AddRunLogData1790850734763, AddRunLogData1790850734763,
AddAuthUsersAndRevokedTokens1793823870652,
]; ];
@@ -10,7 +10,12 @@ import {
Post, Post,
Query, Query,
} from "@nestjs/common"; } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { EnvironmentQueryDto } from "./dto/environment-query.dto"; import { EnvironmentQueryDto } from "./dto/environment-query.dto";
import { CreateEnvironmentDto } from "./dto/create-environment.dto"; import { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto"; import { EnvironmentExportDto } from "./dto/environment-export.dto";
@@ -18,6 +23,7 @@ import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentService } from "./environment.service"; import { EnvironmentService } from "./environment.service";
@ApiTags("environments") @ApiTags("environments")
@ApiBearerAuth()
@Controller("environments") @Controller("environments")
export class EnvironmentController { export class EnvironmentController {
constructor(private readonly environmentService: EnvironmentService) {} constructor(private readonly environmentService: EnvironmentService) {}
+2 -2
View File
@@ -7,7 +7,7 @@ import * as fs from "node:fs/promises";
import * as path from "node:path"; import * as path from "node:path";
import { CronJob } from "cron"; import { CronJob } from "cron";
import { Repository } from "typeorm"; import { Repository } from "typeorm";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
import { AppConfig } from "../config/app.config"; import { AppConfig } from "../config/app.config";
import { FileEntity } from "./file.entity"; import { FileEntity } from "./file.entity";
import { ScenarioFileEntity } from "./scenario-file.entity"; import { ScenarioFileEntity } from "./scenario-file.entity";
@@ -27,7 +27,7 @@ export interface FileMetadata {
@Injectable() @Injectable()
export class FileStorageService implements OnModuleInit { export class FileStorageService implements OnModuleInit {
private static readonly DEFAULT_PAGE_SIZE = 20; private static readonly DEFAULT_PAGE_SIZE = 20;
private readonly logger = new TraceLogger(FileStorageService.name); private readonly logger = createAppLogger(FileStorageService.name);
private readonly filesDir: string; private readonly filesDir: string;
private readonly fileRunExpirationDays: number; private readonly fileRunExpirationDays: number;
private readonly fileCleanupCron: string; private readonly fileCleanupCron: string;
+2 -2
View File
@@ -7,11 +7,11 @@ import {
InternalServerErrorException, InternalServerErrorException,
} from "@nestjs/common"; } from "@nestjs/common";
import type { Request, Response } from "express"; import type { Request, Response } from "express";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
@Catch(BadRequestException, InternalServerErrorException) @Catch(BadRequestException, InternalServerErrorException)
export class HttpExceptionFilter implements ExceptionFilter { export class HttpExceptionFilter implements ExceptionFilter {
private readonly logger = new TraceLogger(HttpExceptionFilter.name); private readonly logger = createAppLogger(HttpExceptionFilter.name);
catch(exception: HttpException, host: ArgumentsHost): void { catch(exception: HttpException, host: ArgumentsHost): void {
const ctx = host.switchToHttp(); const ctx = host.switchToHttp();
+3
View File
@@ -1,10 +1,12 @@
import { Controller, Get } from "@nestjs/common"; import { Controller, Get } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { Public } from "../auth/public.decorator";
@ApiTags("health") @ApiTags("health")
@Controller() @Controller()
export class HealthController { export class HealthController {
@Get("health") @Get("health")
@Public()
@ApiOperation({ summary: "Health check" }) @ApiOperation({ summary: "Health check" })
@ApiResponse({ status: 200, description: "Service is healthy" }) @ApiResponse({ status: 200, description: "Service is healthy" })
health(): { status: string } { health(): { status: string } {
@@ -12,6 +14,7 @@ export class HealthController {
} }
@Get("healthz") @Get("healthz")
@Public()
@ApiOperation({ summary: "Health check" }) @ApiOperation({ summary: "Health check" })
@ApiResponse({ status: 200, description: "Service is healthy" }) @ApiResponse({ status: 200, description: "Service is healthy" })
healthz(): { status: string } { healthz(): { status: string } {
+2
View File
@@ -1,5 +1,6 @@
import { BadRequestException, Body, Controller, Post } from "@nestjs/common"; import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
import { import {
ApiBearerAuth,
ApiBody, ApiBody,
ApiConsumes, ApiConsumes,
ApiOperation, ApiOperation,
@@ -10,6 +11,7 @@ import { YAML_CONTENT_TYPES } from "../common/body-parsers";
import { ImportService } from "./import.service"; import { ImportService } from "./import.service";
@ApiTags("import") @ApiTags("import")
@ApiBearerAuth()
@Controller("import") @Controller("import")
export class ImportController { export class ImportController {
constructor(private readonly importService: ImportService) {} constructor(private readonly importService: ImportService) {}
+24 -3
View File
@@ -6,11 +6,29 @@ import {
} from "@nestjs/common"; } from "@nestjs/common";
import type { Request, Response } from "express"; import type { Request, Response } from "express";
import { Observable, tap } from "rxjs"; import { Observable, tap } from "rxjs";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
export function redactAuthRequestBody(path: string, body: unknown): unknown {
const normalizedPath = path.toLowerCase().replace(/\/+$/, "");
if (
(normalizedPath !== "/auth/login" &&
normalizedPath !== "/api/v1/auth/login") ||
!body ||
typeof body !== "object" ||
Array.isArray(body)
) {
return body;
}
const requestBody = body as Record<string, unknown>;
return {
...requestBody,
password: requestBody.password ? "[REDACTED]" : requestBody.password,
};
}
@Injectable() @Injectable()
export class LoggingInterceptor implements NestInterceptor { export class LoggingInterceptor implements NestInterceptor {
private readonly logger = new TraceLogger(LoggingInterceptor.name); private readonly logger = createAppLogger(LoggingInterceptor.name);
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> { intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const http = context.switchToHttp(); const http = context.switchToHttp();
@@ -18,8 +36,11 @@ export class LoggingInterceptor implements NestInterceptor {
const res = http.getResponse<Response>(); const res = http.getResponse<Response>();
const { method, url, body } = req; const { method, url, body } = req;
const start = Date.now(); const start = Date.now();
const safeBody = redactAuthRequestBody(req.path, body);
const bodyStr = const bodyStr =
body && Object.keys(body).length ? ` ${JSON.stringify(body)}` : ""; safeBody && Object.keys(safeBody).length
? ` ${JSON.stringify(safeBody)}`
: "";
this.logger.debug(`→ ${method} ${url}${bodyStr}`); this.logger.debug(`→ ${method} ${url}${bodyStr}`);
+9 -5
View File
@@ -8,7 +8,7 @@ import { AppModule } from "./app.module";
import { appPackage } from "./common/app-package"; import { appPackage } from "./common/app-package";
import { configureBodyParsers } from "./common/body-parsers"; import { configureBodyParsers } from "./common/body-parsers";
import { corsOrigins } from "./common/cors"; import { corsOrigins } from "./common/cors";
import { TraceLogger } from "./common/trace-logger"; import { createAppLogger } from "./common/app-logger";
import { AppConfig } from "./config/app.config"; import { AppConfig } from "./config/app.config";
import { HttpExceptionFilter } from "./filters/http-exception.filter"; import { HttpExceptionFilter } from "./filters/http-exception.filter";
import { LoggingInterceptor } from "./interceptors/logging.interceptor"; import { LoggingInterceptor } from "./interceptors/logging.interceptor";
@@ -17,9 +17,12 @@ import { TraceInterceptor } from "./interceptors/trace.interceptor";
// Guard against uncaught exceptions thrown inside Playwright event listener // Guard against uncaught exceptions thrown inside Playwright event listener
// callbacks (e.g. a bad waitForURL predicate). Without this, Node.js v15+ // callbacks (e.g. a bad waitForURL predicate). Without this, Node.js v15+
// crashes the process on any unhandled rejection or uncaught exception. // crashes the process on any unhandled rejection or uncaught exception.
const processLogger = new TraceLogger("Process"); const processLogger = createAppLogger("Process");
process.on("uncaughtException", (err) => { process.on("uncaughtException", (err) => {
processLogger.error(`Uncaught exception (process kept alive): ${err.message}`, err.stack); processLogger.error(
`Uncaught exception (process kept alive): ${err.message}`,
err.stack,
);
}); });
process.on("unhandledRejection", (reason) => { process.on("unhandledRejection", (reason) => {
processLogger.error( processLogger.error(
@@ -32,9 +35,9 @@ process.on("unhandledRejection", (reason) => {
async function bootstrap() { async function bootstrap() {
const { name: pkgName, version: pkgVersion } = appPackage(); const { name: pkgName, version: pkgVersion } = appPackage();
const API_PREFIX = "api/v1"; const API_PREFIX = "api/v1";
const logger = new TraceLogger("Bootstrap"); const logger = createAppLogger("Bootstrap");
const app = await NestFactory.create<NestExpressApplication>(AppModule, { const app = await NestFactory.create<NestExpressApplication>(AppModule, {
logger: new TraceLogger("Bootstrap", { timestamp: true }), logger: createAppLogger("Bootstrap", { timestamp: true }),
}); });
// The schema is managed by migrations; refuse to run against an outdated one. // The schema is managed by migrations; refuse to run against an outdated one.
@@ -74,6 +77,7 @@ async function bootstrap() {
.setTitle(pkgName) .setTitle(pkgName)
.setDescription(`${pkgName} API`) .setDescription(`${pkgName} API`)
.setVersion(pkgVersion) .setVersion(pkgVersion)
.addBearerAuth()
.build(); .build();
const document = SwaggerModule.createDocument(app, swaggerConfig); const document = SwaggerModule.createDocument(app, swaggerConfig);
@@ -2,6 +2,7 @@ import { Controller, Get, Header } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger"; import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";
import { AppConfig } from "../config/app.config"; import { AppConfig } from "../config/app.config";
import { Public } from "../auth/public.decorator";
import { ManifestDto } from "./manifest.dto"; import { ManifestDto } from "./manifest.dto";
@ApiTags("manifest") @ApiTags("manifest")
@@ -10,6 +11,7 @@ export class ManifestController {
constructor(private readonly config: ConfigService<AppConfig, true>) {} constructor(private readonly config: ConfigService<AppConfig, true>) {}
@Get("manifest.json") @Get("manifest.json")
@Public()
// Clients cache the manifest themselves; the browser just revalidates it (ETag) // Clients cache the manifest themselves; the browser just revalidates it (ETag)
@Header("Cache-Control", "no-cache") @Header("Cache-Control", "no-cache")
@ApiOperation({ summary: "Public client configuration and app version" }) @ApiOperation({ summary: "Public client configuration and app version" })
@@ -18,6 +20,7 @@ export class ManifestController {
return { return {
name: this.config.get("APP_NAME"), name: this.config.get("APP_NAME"),
version: this.config.get("APP_VERSION"), version: this.config.get("APP_VERSION"),
auth: { enabled: this.config.get("AUTH_ENABLED") },
runLogs: { runLogs: {
dataLimits: { dataLimits: {
bytes: this.config.get("RUN_LOG_DATA_COLLAPSE_BYTES"), bytes: this.config.get("RUN_LOG_DATA_COLLAPSE_BYTES"),
+11 -2
View File
@@ -2,13 +2,15 @@ import { ApiProperty } from "@nestjs/swagger";
export class RunLogDataLimitsDto { export class RunLogDataLimitsDto {
@ApiProperty({ @ApiProperty({
description: "Data blocks over this many bytes (pretty-printed) start collapsed", description:
"Data blocks over this many bytes (pretty-printed) start collapsed",
example: 256, example: 256,
}) })
bytes!: number; bytes!: number;
@ApiProperty({ @ApiProperty({
description: "Data blocks over this many lines (pretty-printed) start collapsed", description:
"Data blocks over this many lines (pretty-printed) start collapsed",
example: 5, example: 5,
}) })
lines!: number; lines!: number;
@@ -26,6 +28,13 @@ export class ManifestDto {
@ApiProperty({ example: "1.4.0" }) @ApiProperty({ example: "1.4.0" })
version!: string; version!: string;
@ApiProperty({
description: "Whether account authentication is enabled.",
type: "object",
properties: { enabled: { type: "boolean", example: false } },
})
auth!: { enabled: boolean };
@ApiProperty({ type: RunLogsManifestDto }) @ApiProperty({ type: RunLogsManifestDto })
runLogs!: RunLogsManifestDto; runLogs!: RunLogsManifestDto;
} }
+7 -1
View File
@@ -1,9 +1,15 @@
import { Controller, Delete, Get, Post, Req, Res } from "@nestjs/common"; import { Controller, Delete, Get, Post, Req, Res } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import type { Request, Response } from "express"; import type { Request, Response } from "express";
import { McpService } from "./mcp.service"; import { McpService } from "./mcp.service";
@ApiTags("mcp") @ApiTags("mcp")
@ApiBearerAuth()
@Controller("mcp") @Controller("mcp")
export class McpController { export class McpController {
constructor(private readonly mcpService: McpService) {} constructor(private readonly mcpService: McpService) {}
+9 -3
View File
@@ -1343,15 +1343,21 @@ export class McpService {
"export_e2e_test", "export_e2e_test",
{ {
description: description:
"Export a scenario as a standalone, plug-and-play Playwright e2e test project (package.json, playwright.config.ts, test.spec.ts, .env), zipped and returned as base64", "Export one version of a scenario as a standalone, plug-and-play Playwright e2e test project (package.json, playwright.config.ts, test.spec.ts, .env), zipped and returned as base64",
inputSchema: { inputSchema: {
id: z.uuid().describe("Scenario ID to export"), id: z.uuid().describe("Scenario ID to export"),
version: z
.number()
.int()
.min(1)
.optional()
.describe("Scenario version to export. Defaults to the latest"),
}, },
}, },
async ({ id }) => { async ({ id, version }) => {
try { try {
const { filename, buffer } = const { filename, buffer } =
await this.e2eExportService.buildE2eTestPackage(id); await this.e2eExportService.buildE2eTestPackage(id, version);
return { return {
content: [ content: [
{ {
+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),
),
};
}
+16 -8
View File
@@ -42,8 +42,16 @@ export class E2eExportService {
private readonly snippetService: SnippetService, private readonly snippetService: SnippetService,
) {} ) {}
async buildE2eTestPackage(scenarioId: string): Promise<{ filename: string; buffer: Buffer }> { /** Builds the package for the latest version, or `version` when given. */
async buildE2eTestPackage(
scenarioId: string,
version?: number,
): Promise<{ filename: string; buffer: Buffer }> {
const scenario = await this.scenarioService.findOne(scenarioId); const scenario = await this.scenarioService.findOne(scenarioId);
const content = await this.scenarioService.findVersion(
scenarioId,
version ?? scenario.version,
);
const [credentialMap, snippetMap, attachedFiles] = await Promise.all([ const [credentialMap, snippetMap, attachedFiles] = await Promise.all([
this.scenarioService.buildCredentialMap(scenarioId), this.scenarioService.buildCredentialMap(scenarioId),
this.snippetService.buildSnippetMap(), this.snippetService.buildSnippetMap(),
@@ -51,10 +59,10 @@ export class E2eExportService {
]); ]);
const envData = scenario.environment?.data ?? {}; const envData = scenario.environment?.data ?? {};
const slug = slugify(scenario.name); const slug = `${slugify(content.name)}-v${content.version}`;
const files: Record<string, string | Buffer> = { const files: Record<string, string | Buffer> = {
"package.json": this.buildPackageJson(slug), "package.json": this.buildPackageJson(slug),
"playwright.config.ts": this.buildPlaywrightConfig(scenario.timeoutSeconds), "playwright.config.ts": this.buildPlaywrightConfig(content.timeoutSeconds),
".env": this.buildEnvFile(envData), ".env": this.buildEnvFile(envData),
"credentials.json": JSON.stringify(credentialMap, null, 2) + "\n", "credentials.json": JSON.stringify(credentialMap, null, 2) + "\n",
".gitignore": [ ".gitignore": [
@@ -65,7 +73,7 @@ export class E2eExportService {
".env", ".env",
"credentials.json", "credentials.json",
].join("\n") + "\n", ].join("\n") + "\n",
"README.md": this.buildReadme(scenario.name, scenario.description), "README.md": this.buildReadme(content.name, content.version, content.description),
}; };
// Bundle any files attached to the scenario so getScenarioFiles works offline. // Bundle any files attached to the scenario so getScenarioFiles works offline.
@@ -97,7 +105,7 @@ export class E2eExportService {
// Bundle only the snippets actually referenced (directly or transitively via // Bundle only the snippets actually referenced (directly or transitively via
// other snippets) by this scenario's steps, as individual .js files under snippets/. // other snippets) by this scenario's steps, as individual .js files under snippets/.
const usedAliases = resolveUsedSnippetAliases( const usedAliases = resolveUsedSnippetAliases(
scenario.steps.map((s) => s.execCode ?? ""), content.steps.map((s) => s.execCode ?? ""),
snippetMap, snippetMap,
); );
const snippetManifest: { alias: string; filename: string }[] = []; const snippetManifest: { alias: string; filename: string }[] = [];
@@ -116,7 +124,7 @@ export class E2eExportService {
snippetManifest.push({ alias, filename }); snippetManifest.push({ alias, filename });
} }
files["test.spec.ts"] = this.buildTestSpec(scenario, snippetManifest, fileManifest); files["test.spec.ts"] = this.buildTestSpec(content, snippetManifest, fileManifest);
const buffer = await this.zip(files); const buffer = await this.zip(files);
return { filename: `${slug}-e2e-test.zip`, buffer }; return { filename: `${slug}-e2e-test.zip`, buffer };
@@ -173,9 +181,9 @@ export default defineConfig({
); );
} }
private buildReadme(scenarioName: string, description: string | null): string { private buildReadme(scenarioName: string, version: number, description: string | null): string {
const descriptionSection = description?.trim() ? `${description.trim()}\n\n` : ""; const descriptionSection = description?.trim() ? `${description.trim()}\n\n` : "";
return `# ${scenarioName} - standalone e2e test return `# ${scenarioName} (v${version}) - standalone e2e test
${descriptionSection}## Setup ${descriptionSection}## Setup
@@ -19,7 +19,7 @@ import {
} from "../code-executor/code-executor.service"; } from "../code-executor/code-executor.service";
import { ExecContextBuilder } from "../code-executor/exec-context.builder"; import { ExecContextBuilder } from "../code-executor/exec-context.builder";
import { traceStorage } from "../common/trace-context"; import { traceStorage } from "../common/trace-context";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
import { import {
EnvironmentData, EnvironmentData,
EnvironmentEntity, EnvironmentEntity,
@@ -42,7 +42,7 @@ interface BrowserHandle {
@Injectable() @Injectable()
export class ScenarioSchedulerService implements OnModuleInit { export class ScenarioSchedulerService implements OnModuleInit {
private readonly logger = new TraceLogger(ScenarioSchedulerService.name); private readonly logger = createAppLogger(ScenarioSchedulerService.name);
private readonly activeRuns = new Set<string>(); private readonly activeRuns = new Set<string>();
private readonly runBrowsers = new Map<string, BrowserHandle>(); private readonly runBrowsers = new Map<string, BrowserHandle>();
// Cache credential maps per run (built once when a run starts) // Cache credential maps per run (built once when a run starts)
+23 -7
View File
@@ -16,7 +16,12 @@ import {
UploadedFile, UploadedFile,
} from "@nestjs/common"; } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express"; import { FileInterceptor } from "@nestjs/platform-express";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { Response } from "express"; import { Response } from "express";
import { interval, map, merge, type Observable } from "rxjs"; import { interval, map, merge, type Observable } from "rxjs";
import type { File as MulterFile } from "multer"; import type { File as MulterFile } from "multer";
@@ -40,6 +45,7 @@ interface SseMessage {
} }
@ApiTags("scenarios") @ApiTags("scenarios")
@ApiBearerAuth()
@Controller("scenarios") @Controller("scenarios")
export class ScenarioController { export class ScenarioController {
private static readonly HEARTBEAT_MS = 25_000; private static readonly HEARTBEAT_MS = 25_000;
@@ -60,7 +66,10 @@ export class ScenarioController {
} }
@Post("import") @Post("import")
@ApiOperation({ summary: "Import a scenario from an export payload (single object or array)" }) @ApiOperation({
summary:
"Import a scenario from an export payload (single object or array)",
})
@ApiResponse({ status: 201, description: "Scenario imported" }) @ApiResponse({ status: 201, description: "Scenario imported" })
importScenario(@Body() payload: unknown) { importScenario(@Body() payload: unknown) {
return this.scenarioService.importScenario( return this.scenarioService.importScenario(
@@ -200,15 +209,19 @@ export class ScenarioController {
@Get(":id/export-e2e") @Get(":id/export-e2e")
@ApiOperation({ @ApiOperation({
summary: "Export a scenario as a standalone, plug-and-play Playwright e2e test (zip)", summary:
"Export a scenario as a standalone, plug-and-play Playwright e2e test (zip)",
}) })
@ApiResponse({ status: 200, description: "Zip archive" }) @ApiResponse({ status: 200, description: "Zip archive" })
@ApiResponse({ status: 404, description: "Scenario not found" }) @ApiResponse({ status: 404, description: "Scenario or version not found" })
async exportE2eTest( async exportE2eTest(
@Param("id", ParseUUIDPipe) id: string, @Param("id", ParseUUIDPipe) id: string,
@Query("version", new ParseIntPipe({ optional: true }))
version: number | undefined,
@Res() res: Response, @Res() res: Response,
) { ) {
const { filename, buffer } = await this.e2eExportService.buildE2eTestPackage(id); const { filename, buffer } =
await this.e2eExportService.buildE2eTestPackage(id, version);
res.setHeader("Content-Type", "application/zip"); res.setHeader("Content-Type", "application/zip");
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`); res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
res.setHeader("Content-Length", buffer.length); res.setHeader("Content-Length", buffer.length);
@@ -265,7 +278,8 @@ export class ScenarioController {
@Get(":id/used-snippets") @Get(":id/used-snippets")
@ApiOperation({ @ApiOperation({
summary: "List snippets referenced (directly or transitively) by this scenario's steps", summary:
"List snippets referenced (directly or transitively) by this scenario's steps",
}) })
@ApiResponse({ status: 200 }) @ApiResponse({ status: 200 })
@ApiResponse({ status: 404, description: "Scenario not found" }) @ApiResponse({ status: 404, description: "Scenario not found" })
@@ -370,7 +384,9 @@ export class ScenarioController {
const fmt = format === "csv" ? "csv" : "md"; const fmt = format === "csv" ? "csv" : "md";
const content = await this.scenarioService.exportRunLogs(id, runId, fmt); const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
const contentType = const contentType =
fmt === "csv" ? "text/csv; charset=utf-8" : "text/markdown; charset=utf-8"; fmt === "csv"
? "text/csv; charset=utf-8"
: "text/markdown; charset=utf-8";
const ext = fmt === "csv" ? "csv" : "md"; const ext = fmt === "csv" ? "csv" : "md";
res.setHeader("Content-Type", contentType); res.setHeader("Content-Type", contentType);
res.setHeader( res.setHeader(
@@ -5,7 +5,7 @@ import {
OnModuleDestroy, OnModuleDestroy,
} from "@nestjs/common"; } from "@nestjs/common";
import type { Browser, BrowserContext, Page } from "playwright"; import type { Browser, BrowserContext, Page } from "playwright";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
import { SessionService } from "./session.service"; import { SessionService } from "./session.service";
export interface SessionHandle { export interface SessionHandle {
@@ -21,7 +21,7 @@ export interface SessionHandle {
*/ */
@Injectable() @Injectable()
export class SessionContextService implements OnModuleDestroy { export class SessionContextService implements OnModuleDestroy {
private readonly logger = new TraceLogger(SessionContextService.name); private readonly logger = createAppLogger(SessionContextService.name);
private readonly handles = new Map<string, SessionHandle>(); private readonly handles = new Map<string, SessionHandle>();
constructor(private readonly sessionService: SessionService) {} constructor(private readonly sessionService: SessionService) {}
@@ -1,7 +1,7 @@
import { Injectable } from "@nestjs/common"; import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config"; import { ConfigService } from "@nestjs/config";
import { Interval } from "@nestjs/schedule"; import { Interval } from "@nestjs/schedule";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
import { AppConfig } from "../config/app.config"; import { AppConfig } from "../config/app.config";
import { SessionContextService } from "./session-context.service"; import { SessionContextService } from "./session-context.service";
import { SessionService } from "./session.service"; import { SessionService } from "./session.service";
@@ -13,7 +13,7 @@ import { SessionService } from "./session.service";
*/ */
@Injectable() @Injectable()
export class SessionSchedulerService { export class SessionSchedulerService {
private readonly logger = new TraceLogger(SessionSchedulerService.name); private readonly logger = createAppLogger(SessionSchedulerService.name);
constructor( constructor(
private readonly sessionService: SessionService, private readonly sessionService: SessionService,
+7 -1
View File
@@ -8,7 +8,12 @@ import {
ParseUUIDPipe, ParseUUIDPipe,
Query, Query,
} from "@nestjs/common"; } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { SessionQueryDto } from "./session-query.dto"; import { SessionQueryDto } from "./session-query.dto";
import { SessionContextService } from "./session-context.service"; import { SessionContextService } from "./session-context.service";
import { SessionService } from "./session.service"; import { SessionService } from "./session.service";
@@ -19,6 +24,7 @@ function maskToken(token: string, head = 6, tail = 4): string {
} }
@ApiTags("sessions") @ApiTags("sessions")
@ApiBearerAuth()
@Controller("sessions") @Controller("sessions")
export class SessionController { export class SessionController {
constructor( constructor(
+2 -2
View File
@@ -6,7 +6,7 @@ import {
PaginatedResult, PaginatedResult,
PaginationQueryDto, PaginationQueryDto,
} from "../common/dto/pagination.dto"; } from "../common/dto/pagination.dto";
import { TraceLogger } from "../common/trace-logger"; import { createAppLogger } from "../common/app-logger";
import { SessionEntity } from "./session.entity"; import { SessionEntity } from "./session.entity";
export type SessionOrderBy = export type SessionOrderBy =
@@ -19,7 +19,7 @@ export type SessionOrderBy =
@Injectable() @Injectable()
export class SessionService implements OnApplicationBootstrap { export class SessionService implements OnApplicationBootstrap {
private readonly logger = new TraceLogger(SessionService.name); private readonly logger = createAppLogger(SessionService.name);
constructor( constructor(
@InjectRepository(SessionEntity) @InjectRepository(SessionEntity)
+7 -1
View File
@@ -11,7 +11,12 @@ import {
Post, Post,
Query, Query,
} from "@nestjs/common"; } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger"; import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { SnippetQueryDto } from "./dto/snippet-query.dto"; import { SnippetQueryDto } from "./dto/snippet-query.dto";
import { CreateSnippetDto } from "./dto/create-snippet.dto"; import { CreateSnippetDto } from "./dto/create-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto"; import { SnippetExportDto } from "./dto/snippet-export.dto";
@@ -19,6 +24,7 @@ import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetService } from "./snippet.service"; import { SnippetService } from "./snippet.service";
@ApiTags("snippets") @ApiTags("snippets")
@ApiBearerAuth()
@Controller("snippets") @Controller("snippets")
export class SnippetController { export class SnippetController {
constructor(private readonly snippetService: SnippetService) {} constructor(private readonly snippetService: SnippetService) {}
+6 -2
View File
@@ -48,8 +48,11 @@ import { ManifestController } from "../src/manifest/manifest.controller";
import { HttpExceptionFilter } from "../src/filters/http-exception.filter"; import { HttpExceptionFilter } from "../src/filters/http-exception.filter";
import { LoggingInterceptor } from "../src/interceptors/logging.interceptor"; import { LoggingInterceptor } from "../src/interceptors/logging.interceptor";
import { validateAppConfig } from "../src/config/app.config"; import { validateAppConfig } from "../src/config/app.config";
import { AuthModule } from "../src/auth/auth.module";
export async function buildTestApp(): Promise<INestApplication> { export async function buildTestApp(
databasePath = ":memory:",
): Promise<INestApplication> {
// Each test app stores files in its own temp dir: suites run in parallel and // Each test app stores files in its own temp dir: suites run in parallel and
// some clean up their files dir, which must not affect other suites. // some clean up their files dir, which must not affect other suites.
const filesDir = fs.mkdtempSync(path.join(os.tmpdir(), "liqa-test-files-")); const filesDir = fs.mkdtempSync(path.join(os.tmpdir(), "liqa-test-files-"));
@@ -64,11 +67,12 @@ export async function buildTestApp(): Promise<INestApplication> {
}), }),
// The real migrations, not synchronize, so tests use the schema production gets // The real migrations, not synchronize, so tests use the schema production gets
TypeOrmModule.forRoot({ TypeOrmModule.forRoot({
...dataSourceOptions(":memory:"), ...dataSourceOptions(databasePath),
migrationsRun: true, migrationsRun: true,
}), }),
ScheduleModule.forRoot(), ScheduleModule.forRoot(),
BrowserModule, BrowserModule,
AuthModule,
SessionModule, SessionModule,
EnvironmentModule, EnvironmentModule,
ScenarioModule, ScenarioModule,
+64
View File
@@ -0,0 +1,64 @@
import "reflect-metadata";
import { LogMode, validateAppConfig } from "../src/config/app.config";
import { durationSeconds } from "../src/common/interval";
describe("Authentication configuration", () => {
it("defaults authentication off with a 24-hour token lifetime and cleanup schedule", () => {
const config = validateAppConfig({});
expect(config.AUTH_ENABLED).toBe(false);
expect(config.AUTH_JWT_EXPIRES_IN).toBe("24h");
expect(config.AUTH_COOKIE_NAME).toBe("liqa_auth");
expect(config.AUTH_REVOKED_TOKEN_CLEANUP_CRON).toBe("0 3 * * *");
});
it("defaults to console logging and accepts debug logging", () => {
expect(validateAppConfig({}).LOG_MODE).toBe(LogMode.Console);
expect(validateAppConfig({ LOG_MODE: "debug" }).LOG_MODE).toBe(
LogMode.Debug,
);
});
it("rejects unsupported logging modes", () => {
expect(() => validateAppConfig({ LOG_MODE: "silent" })).toThrow();
});
it("parses explicit true and false values without JavaScript truthiness", () => {
expect(validateAppConfig({ AUTH_ENABLED: "false" }).AUTH_ENABLED).toBe(
false,
);
expect(
validateAppConfig({ AUTH_ENABLED: "true", AUTH_JWT_SECRET: "test" })
.AUTH_ENABLED,
).toBe(true);
});
it("requires a signing secret and usable token lifetime only when enabled", () => {
expect(() => validateAppConfig({ AUTH_ENABLED: "true" })).toThrow(
"AUTH_JWT_SECRET must be set when AUTH_ENABLED=true",
);
expect(() =>
validateAppConfig({
AUTH_ENABLED: "true",
AUTH_JWT_SECRET: "test",
AUTH_JWT_EXPIRES_IN: "0h",
}),
).toThrow("AUTH_JWT_EXPIRES_IN must be a positive duration");
expect(
validateAppConfig({
AUTH_ENABLED: "false",
AUTH_JWT_EXPIRES_IN: "invalid",
}).AUTH_ENABLED,
).toBe(false);
});
it("rejects non-boolean auth settings and parses common positive durations", () => {
expect(() => validateAppConfig({ AUTH_ENABLED: "yes" })).toThrow(
"AUTH_ENABLED must be either true or false",
);
expect(durationSeconds("30m")).toBe(1800);
expect(durationSeconds("24h")).toBe(86400);
expect(durationSeconds("2d")).toBe(172800);
expect(durationSeconds("0s")).toBeNull();
});
});
+41
View File
@@ -0,0 +1,41 @@
import { INestApplication } from "@nestjs/common";
import request from "supertest";
import { buildTestApp } from "./app.harness";
describe("authentication disabled", () => {
const envKeys = ["AUTH_ENABLED", "AUTH_JWT_SECRET"] as const;
const previousEnv = new Map<string, string | undefined>();
let app: INestApplication;
beforeAll(async () => {
for (const key of envKeys) previousEnv.set(key, process.env[key]);
process.env.AUTH_ENABLED = "false";
delete process.env.AUTH_JWT_SECRET;
app = await buildTestApp();
});
afterAll(async () => {
await app?.close();
for (const key of envKeys) {
const value = previousEnv.get(key);
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
it("starts without a secret and leaves existing REST behavior public", async () => {
await request(app.getHttpServer()).get("/scenarios").expect(200);
await request(app.getHttpServer()).get("/health").expect(200);
const manifest = await request(app.getHttpServer())
.get("/manifest.json")
.expect(200);
expect(manifest.body.auth).toEqual({ enabled: false });
});
it("returns not found for login while authentication is disabled", async () => {
await request(app.getHttpServer())
.post("/auth/login")
.send({ username: "nobody", password: "synthetic" })
.expect(404);
});
});
+57
View File
@@ -0,0 +1,57 @@
import { AuthSession } from "../src/auth/auth.service";
import {
clearedSessionCookie,
cookieToken,
requestToken,
sessionCookie,
} from "../src/auth/auth.helpers";
import { Public, IS_PUBLIC_KEY } from "../src/auth/public.decorator";
describe("authentication helpers", () => {
const request = {
secure: false,
get: (name: string) =>
name === "x-forwarded-proto" ? undefined : undefined,
} as never;
const session: AuthSession = {
user: {
id: "u",
username: "user",
createdAt: new Date(0),
updatedAt: new Date(0),
},
token: "a.token.value",
expiresAt: new Date(Date.now() + 60_000),
};
it("sets and clears a configurable cookie name", () => {
expect(sessionCookie(request, session, "custom_session")).toContain(
"custom_session=a.token.value",
);
expect(clearedSessionCookie(request, "custom_session")).toContain(
"custom_session=;",
);
});
it("reads only the selected cookie and supports bearer credentials", () => {
expect(
cookieToken("other=x; custom_session=encoded%20value", "custom_session"),
).toBe("encoded value");
expect(
requestToken(
{
get: (name: string) =>
name === "authorization" ? "Bearer token" : undefined,
} as never,
"x",
),
).toBe("token");
});
it("stores public-route metadata under a Symbol key", () => {
class PublicController {}
Public()(PublicController);
expect(typeof IS_PUBLIC_KEY).toBe("symbol");
expect(Reflect.getMetadata(IS_PUBLIC_KEY, PublicController)).toBe(true);
});
});
+290
View File
@@ -0,0 +1,290 @@
import { INestApplication } from "@nestjs/common";
import { getRepositoryToken } from "@nestjs/typeorm";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { DataSource, Repository } from "typeorm";
import request from "supertest";
import { EnvironmentService } from "../src/environment/environment.service";
import { ScenarioSchedulerService } from "../src/scenario/scenario-scheduler.service";
import { ScenarioService } from "../src/scenario/scenario.service";
import { PasswordService } from "../src/auth/password.service";
import { UserEntity } from "../src/auth/user.entity";
import {
OperatorCliInput,
runOperatorCommand,
} from "../src/operator-cli/operator-cli";
import { buildTestApp } from "./app.harness";
const AUTH_SECRET = "synthetic-integration-secret-for-tests";
const USER_PASSWORD = "synthetic-integration-password";
function cookiePair(response: request.Response): string {
const cookies = response.headers["set-cookie"];
if (!Array.isArray(cookies) || typeof cookies[0] !== "string") {
throw new Error("Login response did not set an auth cookie");
}
return cookies[0].split(";")[0];
}
function cookieToken(cookie: string): string {
return decodeURIComponent(cookie.slice(cookie.indexOf("=") + 1));
}
function cliInput(): OperatorCliInput {
const lines = ["integration-user"];
const secrets = [USER_PASSWORD, USER_PASSWORD];
return {
line: async () => lines.shift() ?? "",
secret: async () => secrets.shift() ?? "",
};
}
describe("authentication integration journey", () => {
const envKeys = [
"AUTH_ENABLED",
"AUTH_JWT_SECRET",
"AUTH_JWT_EXPIRES_IN",
"AUTH_REVOKED_TOKEN_CLEANUP_CRON",
] as const;
const previousEnv = new Map<string, string | undefined>();
let directory: string;
let databasePath: string;
let app: INestApplication;
beforeAll(async () => {
for (const key of envKeys) previousEnv.set(key, process.env[key]);
process.env.AUTH_ENABLED = "true";
process.env.AUTH_JWT_SECRET = AUTH_SECRET;
process.env.AUTH_JWT_EXPIRES_IN = "1h";
process.env.AUTH_REVOKED_TOKEN_CLEANUP_CRON = "0 3 * * *";
directory = fs.mkdtempSync(path.join(os.tmpdir(), "liqa-auth-e2e-"));
databasePath = path.join(directory, "liqa.db");
app = await buildTestApp(databasePath);
});
afterAll(async () => {
await app?.close();
if (directory) fs.rmSync(directory, { recursive: true, force: true });
for (const key of envKeys) {
const value = previousEnv.get(key);
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
it("carries a CLI-created account through login, protected APIs, events, logout and deletion", async () => {
const dataSource = app.get(DataSource);
const passwords = app.get(PasswordService);
await runOperatorCommand(["user:create"], {
dataSource,
config: {
AUTH_ENABLED: true,
AUTH_JWT_SECRET: AUTH_SECRET,
AUTH_JWT_EXPIRES_IN: "1h",
},
passwords,
input: cliInput(),
output: { write: () => undefined },
});
const users = app.get<Repository<UserEntity>>(
getRepositoryToken(UserEntity),
);
const createdUser = await users.findOneByOrFail({
username: "integration-user",
});
expect(createdUser.passwordHash).not.toBe(USER_PASSWORD);
const listener = await app.listen(0, "127.0.0.1");
const address = listener.address();
if (!address || typeof address === "string") {
throw new Error("Could not determine ephemeral test server port");
}
const login = await request(app.getHttpServer())
.post("/auth/login")
.send({ username: "integration-user", password: USER_PASSWORD })
.expect(200);
expect(login.body.user).toMatchObject({
id: createdUser.id,
username: "integration-user",
});
const cookie = cookiePair(login);
const token = cookieToken(cookie);
await request(app.getHttpServer())
.get("/auth/me")
.set("Cookie", cookie)
.expect(200)
.then(({ body }) => expect(body.id).toBe(createdUser.id));
await request(app.getHttpServer())
.get("/scenarios")
.set("Authorization", `Bearer ${token}`)
.expect(200);
const mcpRequest = {
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2024-11-05",
capabilities: {},
clientInfo: { name: "auth-integration-test", version: "1" },
},
};
for (const credential of [
{ name: "Cookie", value: cookie },
{ name: "Authorization", value: `Bearer ${token}` },
]) {
await request(app.getHttpServer())
.post("/mcp")
.set(credential.name, credential.value)
.set("Content-Type", "application/json")
.set("Accept", "application/json, text/event-stream")
.send(mcpRequest)
.expect(200);
}
const abort = new AbortController();
const eventResponse = await fetch(
`http://127.0.0.1:${address.port}/scenarios/runs/events`,
{
headers: { Authorization: `Bearer ${token}` },
signal: abort.signal,
},
);
expect(eventResponse.status).toBe(200);
expect(eventResponse.headers.get("content-type")).toContain(
"text/event-stream",
);
const scenarios = app.get(ScenarioService);
const environments = app.get(EnvironmentService);
const scheduler = app.get(ScenarioSchedulerService);
const scenario = await scenarios.create({ name: "auth integration run" });
await scenarios.createStep(scenario.id, {
title: "Return a deterministic result",
execCode: "return 'integration-ok';",
});
const environment = await environments.create({
name: "auth integration environment",
data: {},
});
const run = await scenarios.createRun(scenario.id, environment.id);
await scheduler.pickUpPendingRuns();
const reader = eventResponse.body?.getReader();
if (!reader) throw new Error("Run events response has no readable body");
let eventText = "";
const readFinishedEvent = async () => {
const decoder = new TextDecoder();
while (
!eventText.includes(`"runId":"${run.id}"`) ||
!eventText.includes("event: run.finished")
) {
const { value, done } = await reader.read();
if (done) throw new Error("Run events stream closed before completion");
eventText += decoder.decode(value, { stream: true });
}
return eventText;
};
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const output = await Promise.race([
readFinishedEvent(),
new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error("Timed out waiting for run.finished SSE")),
5000,
);
}),
]);
expect(output).toContain("event: run.started");
expect(output).toContain("event: run.finished");
expect(output).toContain(`"runId":"${run.id}"`);
expect(output).toContain('"status":"pass"');
} finally {
if (timer) clearTimeout(timer);
abort.abort();
await reader.cancel().catch(() => undefined);
}
await request(app.getHttpServer())
.post("/auth/logout")
.set("Cookie", cookie)
.expect(204);
await request(app.getHttpServer())
.get("/scenarios")
.set("Cookie", cookie)
.expect(401);
await request(app.getHttpServer())
.get("/scenarios")
.set("Authorization", `Bearer ${token}`)
.expect(401);
const deletionInput = {
line: async () => "delete-user",
secret: async () => USER_PASSWORD,
};
await runOperatorCommand(["user:create"], {
dataSource,
config: {
AUTH_ENABLED: true,
AUTH_JWT_SECRET: AUTH_SECRET,
AUTH_JWT_EXPIRES_IN: "1h",
},
passwords,
input: deletionInput,
output: { write: () => undefined },
});
const deletionLogin = await request(app.getHttpServer())
.post("/auth/login")
.send({ username: "delete-user", password: USER_PASSWORD })
.expect(200);
const deletionCookie = cookiePair(deletionLogin);
const deletionToken = cookieToken(deletionCookie);
await runOperatorCommand(["user:delete", "delete-user"], {
dataSource,
config: {
AUTH_ENABLED: true,
AUTH_JWT_SECRET: AUTH_SECRET,
AUTH_JWT_EXPIRES_IN: "1h",
},
passwords,
input: deletionInput,
output: { write: () => undefined },
});
await request(app.getHttpServer())
.get("/scenarios")
.set("Cookie", deletionCookie)
.expect(401);
await request(app.getHttpServer())
.get("/scenarios")
.set("Authorization", `Bearer ${deletionToken}`)
.expect(401);
const migrationsBeforeRestart = await dataSource.query(
"SELECT timestamp FROM migrations ORDER BY timestamp",
);
await app.close();
app = await buildTestApp(databasePath);
const reopenedDataSource = app.get(DataSource);
expect(await reopenedDataSource.showMigrations()).toBe(false);
await expect(
reopenedDataSource.query(
"SELECT timestamp FROM migrations ORDER BY timestamp",
),
).resolves.toEqual(migrationsBeforeRestart);
await expect(
reopenedDataSource
.getRepository(UserEntity)
.findOneBy({ username: "integration-user" }),
).resolves.toMatchObject({ username: "integration-user" });
await expect(
reopenedDataSource
.getRepository(UserEntity)
.findOneBy({ username: "delete-user" }),
).resolves.toBeNull();
});
});
+258
View File
@@ -0,0 +1,258 @@
import { INestApplication } from "@nestjs/common";
import { getRepositoryToken } from "@nestjs/typeorm";
import request from "supertest";
import { Repository } from "typeorm";
import { filter, firstValueFrom, timeout } from "rxjs";
import { AuthService } from "../src/auth/auth.service";
import { tokenHash } from "../src/auth/jwt.helpers";
import { PasswordService } from "../src/auth/password.service";
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
import { EnvironmentService } from "../src/environment/environment.service";
import { RunEventsService } from "../src/scenario/run-events.service";
import { ScenarioSchedulerService } from "../src/scenario/scenario-scheduler.service";
import { ScenarioService } from "../src/scenario/scenario.service";
import { UserEntity } from "../src/auth/user.entity";
import { buildTestApp } from "./app.harness";
function firstSetCookie(response: {
headers: Record<string, unknown>;
}): string {
const value = response.headers["set-cookie"];
return Array.isArray(value) ? String(value[0]) : String(value);
}
describe("optional authentication", () => {
const envKeys = [
"AUTH_ENABLED",
"AUTH_JWT_SECRET",
"AUTH_JWT_EXPIRES_IN",
"AUTH_REVOKED_TOKEN_CLEANUP_CRON",
] as const;
const previousEnv = new Map<string, string | undefined>();
let app: INestApplication;
let users: Repository<UserEntity>;
let passwords: PasswordService;
let auth: AuthService;
let revokedTokens: Repository<RevokedTokenEntity>;
let user: UserEntity;
beforeAll(async () => {
for (const key of envKeys) previousEnv.set(key, process.env[key]);
process.env.AUTH_ENABLED = "true";
process.env.AUTH_JWT_SECRET = "auth-test-secret-only";
process.env.AUTH_JWT_EXPIRES_IN = "1h";
app = await buildTestApp();
users = app.get<Repository<UserEntity>>(getRepositoryToken(UserEntity));
passwords = app.get(PasswordService);
auth = app.get(AuthService);
revokedTokens = app.get<Repository<RevokedTokenEntity>>(
getRepositoryToken(RevokedTokenEntity),
);
user = await users.save(
users.create({
username: "alice",
passwordHash: await passwords.hash("correct-test-password"),
}),
);
});
afterAll(async () => {
await app?.close();
for (const key of envKeys) {
const value = previousEnv.get(key);
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
it("keeps health and the secret-free auth flag public while protecting REST, MCP, and run events", async () => {
await request(app.getHttpServer()).get("/health").expect(200);
const manifest = await request(app.getHttpServer())
.get("/manifest.json")
.expect(200);
expect(manifest.body.auth).toEqual({ enabled: true });
expect(JSON.stringify(manifest.body)).not.toContain("AUTH_JWT_SECRET");
expect(JSON.stringify(manifest.body)).not.toContain(
"auth-test-secret-only",
);
await request(app.getHttpServer()).get("/scenarios").expect(401);
await request(app.getHttpServer())
.get("/scenarios/runs/events")
.expect(401);
await request(app.getHttpServer())
.post("/mcp")
.send({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} })
.expect(401);
});
it("continues processing scheduled scenarios without an HTTP credential", async () => {
const environments = app.get(EnvironmentService);
const scenarios = app.get(ScenarioService);
const scheduler = app.get(ScenarioSchedulerService);
const events = app.get(RunEventsService);
const environment = await environments.create({
name: "auth-scheduler-environment",
data: {},
});
const scenario = await scenarios.create({
name: "auth-scheduler-scenario",
});
await scenarios.createStep(scenario.id, {
title: "Return a value",
execCode: "return 1;",
});
const run = await scenarios.createRun(scenario.id, environment.id);
const finished = firstValueFrom(
events.stream().pipe(
filter(
(event) => event.type === "run.finished" && event.runId === run.id,
),
timeout({ first: 5000 }),
),
);
await scheduler.pickUpPendingRuns();
await finished;
expect((await scenarios.findRun(scenario.id, run.id)).status).toBe("pass");
});
it("logs in with a strict HttpOnly cookie and returns only safe identity fields", async () => {
const response = await request(app.getHttpServer())
.post("/auth/login")
.set("x-forwarded-proto", "https")
.send({ username: "alice", password: "correct-test-password" })
.expect(200);
expect(response.body.user).toMatchObject({
id: user.id,
username: "alice",
});
expect(response.body.user.passwordHash).toBeUndefined();
expect(response.body.token).toBeUndefined();
expect(JSON.stringify(response.body)).not.toContain(
"correct-test-password",
);
const cookie = firstSetCookie(response);
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("SameSite=Strict");
expect(cookie).toContain("Secure");
expect(cookie).toContain("Max-Age=");
});
it("rejects unknown or incorrect credentials without returning account data", async () => {
for (const username of ["alice", "missing-user"]) {
const response = await request(app.getHttpServer())
.post("/auth/login")
.send({ username, password: "wrong-test-password" })
.expect(401);
expect(JSON.stringify(response.body)).not.toContain("passwordHash");
expect(JSON.stringify(response.body)).not.toContain(
"wrong-test-password",
);
}
});
it("accepts cookie and Bearer credentials and keeps the password hash private", async () => {
const login = await request(app.getHttpServer())
.post("/auth/login")
.send({ username: "alice", password: "correct-test-password" })
.expect(200);
const cookiePair = firstSetCookie(login).split(";")[0];
const token = decodeURIComponent(
cookiePair.slice(cookiePair.indexOf("=") + 1),
);
const cookieMe = await request(app.getHttpServer())
.get("/auth/me")
.set("Cookie", cookiePair)
.expect(200);
expect(cookieMe.body).toMatchObject({ id: user.id, username: "alice" });
expect(cookieMe.body.passwordHash).toBeUndefined();
await request(app.getHttpServer())
.get("/scenarios")
.set("Cookie", cookiePair)
.expect(200);
await request(app.getHttpServer())
.get("/scenarios")
.set("Authorization", `Bearer ${token}`)
.expect(200);
const mcp = await request(app.getHttpServer())
.post("/mcp")
.set("Authorization", `Bearer ${token}`)
.set("Content-Type", "application/json")
.set("Accept", "application/json, text/event-stream")
.send({
jsonrpc: "2.0",
id: 1,
method: "initialize",
params: {
protocolVersion: "2024-11-05",
capabilities: {},
clientInfo: { name: "auth-test", version: "0" },
},
})
.expect(200);
expect(mcp.text).toContain("protocolVersion");
});
it("rejects tampered and expired tokens and deleted users", async () => {
const valid = auth.issueToken(user).token;
const tampered = `${valid.slice(0, -2)}${valid.endsWith("A") ? "B" : "A"}A`;
await request(app.getHttpServer())
.get("/auth/me")
.set("Authorization", `Bearer ${tampered}`)
.expect(401);
const now = Date.now();
const oldClock = jest
.spyOn(Date, "now")
.mockReturnValue(now - 2 * 3600_000);
const expired = auth.issueToken(user).token;
oldClock.mockRestore();
await request(app.getHttpServer())
.get("/auth/me")
.set("Authorization", `Bearer ${expired}`)
.expect(401);
const removedUser = await users.save(
users.create({
username: "deleted-user",
passwordHash: await passwords.hash("temporary-test-password"),
}),
);
const deletedUserToken = auth.issueToken(removedUser).token;
await users.delete({ id: removedUser.id });
await request(app.getHttpServer())
.get("/auth/me")
.set("Authorization", `Bearer ${deletedUserToken}`)
.expect(401);
});
it("persists only the token digest on logout and rejects token reuse", async () => {
const login = await request(app.getHttpServer())
.post("/auth/login")
.send({ username: "alice", password: "correct-test-password" })
.expect(200);
const cookiePair = firstSetCookie(login).split(";")[0];
const token = decodeURIComponent(
cookiePair.slice(cookiePair.indexOf("=") + 1),
);
const logout = await request(app.getHttpServer())
.post("/auth/logout")
.set("Cookie", cookiePair)
.expect(204);
expect(firstSetCookie(logout)).toContain("Max-Age=0");
const storedRevocation = await revokedTokens.findOneBy({
tokenHash: tokenHash(token),
});
expect(storedRevocation?.tokenHash).not.toBe(token);
await request(app.getHttpServer())
.get("/scenarios")
.set("Authorization", `Bearer ${token}`)
.expect(401);
});
});
+62
View File
@@ -0,0 +1,62 @@
import { CallHandler, ExecutionContext } from "@nestjs/common";
import { of } from "rxjs";
import { DebugLogger } from "../src/common/debug-logger";
import {
LoggingInterceptor,
redactAuthRequestBody,
} from "../src/interceptors/logging.interceptor";
describe("redactAuthRequestBody", () => {
it("redacts login passwords on local and API-prefixed route paths", () => {
const body = { username: "operator", password: "synthetic-secret" };
expect(redactAuthRequestBody("/auth/login", body)).toEqual({
username: "operator",
password: "[REDACTED]",
});
expect(redactAuthRequestBody("/api/v1/auth/login", body)).toEqual({
username: "operator",
password: "[REDACTED]",
});
expect(redactAuthRequestBody("/api/v1/auth/login/", body)).toEqual({
username: "operator",
password: "[REDACTED]",
});
expect(redactAuthRequestBody("/API/V1/AUTH/LOGIN/", body)).toEqual({
username: "operator",
password: "[REDACTED]",
});
expect(redactAuthRequestBody("/api/v1/scenarios", body)).toBe(body);
});
it("never logs a password received on the accepted trailing-slash login path", () => {
const loggedMessages: unknown[][] = [];
const debug = jest
.spyOn(DebugLogger.prototype, "debug")
.mockImplementation((...args: unknown[]) => {
loggedMessages.push(args);
});
const context = {
switchToHttp: () => ({
getRequest: () => ({
method: "POST",
url: "/api/v1/auth/login/",
path: "/api/v1/auth/login/",
body: { username: "operator", password: "synthetic-login-secret" },
}),
getResponse: () => ({ statusCode: 200 }),
}),
} as unknown as ExecutionContext;
const handler = {
handle: () => of({ user: { username: "operator" } }),
} as CallHandler;
try {
new LoggingInterceptor().intercept(context, handler).subscribe();
const output = JSON.stringify(loggedMessages);
expect(output).toContain("[REDACTED]");
expect(output).not.toContain("synthetic-login-secret");
} finally {
debug.mockRestore();
}
});
});
+2
View File
@@ -0,0 +1,2 @@
// Application logs should stay quiet during tests unless DEBUG enables them.
process.env.LOG_MODE = 'debug';
+14
View File
@@ -1,9 +1,22 @@
import { INestApplication } from "@nestjs/common"; import { INestApplication } from "@nestjs/common";
import request from "supertest"; import request from "supertest";
import { appPackage } from "../src/common/app-package"; import { appPackage } from "../src/common/app-package";
import { ManifestDto } from "../src/manifest/manifest.dto";
import { buildTestApp } from "./app.harness"; import { buildTestApp } from "./app.harness";
describe("GET /manifest.json", () => { describe("GET /manifest.json", () => {
it("describes the manifest auth flag without describing authentication as optional", () => {
const authProperty = Reflect.getMetadata(
"swagger/apiModelProperties",
ManifestDto.prototype,
"auth",
) as { description: string };
expect(authProperty.description).toBe(
"Whether account authentication is enabled.",
);
expect(authProperty.description).not.toContain("optional");
});
let app: INestApplication; let app: INestApplication;
afterEach(async () => { afterEach(async () => {
@@ -21,6 +34,7 @@ describe("GET /manifest.json", () => {
expect(res.body).toEqual({ expect(res.body).toEqual({
name: appPackage().name, name: appPackage().name,
version: appPackage().version, version: appPackage().version,
auth: { enabled: false },
runLogs: { dataLimits: { bytes: 256, lines: 5 } }, runLogs: { dataLimits: { bytes: 256, lines: 5 } },
}); });
expect(res.headers["cache-control"]).toBe("no-cache"); expect(res.headers["cache-control"]).toBe("no-cache");
+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");
});
});
+116
View File
@@ -0,0 +1,116 @@
import { ConfigService } from "@nestjs/config";
import { SchedulerRegistry } from "@nestjs/schedule";
import { CronJob } from "cron";
import { DataSource, Repository } from "typeorm";
import { AppConfig } from "../src/config/app.config";
import { dataSourceOptions } from "../src/database/data-source";
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
import {
AUTH_REVOKED_TOKEN_CLEANUP_JOB,
RevokedTokenCleanupService,
} from "../src/auth/revoked-token-cleanup.service";
describe("RevokedTokenCleanupService", () => {
let dataSource: DataSource;
let repository: Repository<RevokedTokenEntity>;
let addCronJob: jest.Mock;
let registry: SchedulerRegistry;
async function createService(
enabled: boolean,
cron = "0 3 * * *",
): Promise<RevokedTokenCleanupService> {
const config = {
get: jest.fn((key: keyof AppConfig) => {
if (key === "AUTH_ENABLED") return enabled;
if (key === "AUTH_REVOKED_TOKEN_CLEANUP_CRON") return cron;
throw new Error(`Unexpected config key ${key}`);
}),
} as unknown as ConfigService<AppConfig, true>;
return new RevokedTokenCleanupService(repository, config, registry);
}
beforeEach(async () => {
dataSource = new DataSource(dataSourceOptions(":memory:"));
await dataSource.initialize();
await dataSource.runMigrations();
repository = dataSource.getRepository(RevokedTokenEntity);
addCronJob = jest.fn();
registry = { addCronJob } as unknown as SchedulerRegistry;
});
afterEach(async () => {
await dataSource.destroy();
jest.useRealTimers();
});
it("deletes only expired revocations, including expiry at the current instant", async () => {
const now = new Date("2026-11-05T12:00:00.000Z");
jest.useFakeTimers().setSystemTime(now);
await repository.insert([
{ tokenHash: "a".repeat(64), expiresAt: new Date(now.getTime() - 1) },
{ tokenHash: "b".repeat(64), expiresAt: now },
{ tokenHash: "c".repeat(64), expiresAt: new Date(now.getTime() + 1) },
]);
const service = await createService(true);
await service.cleanupExpiredTokens();
const retained = await repository.find();
expect(retained.map(({ tokenHash }) => tokenHash)).toEqual([
"c".repeat(64),
]);
});
it("tolerates an empty table and repeated cleanup runs", async () => {
const service = await createService(true);
await expect(service.cleanupExpiredTokens()).resolves.toBeUndefined();
await expect(service.cleanupExpiredTokens()).resolves.toBeUndefined();
await expect(repository.count()).resolves.toBe(0);
});
it("cleans at startup and registers the configured in-process cron job", async () => {
const now = new Date("2026-11-05T12:00:00.000Z");
jest.useFakeTimers().setSystemTime(now);
await repository.insert({
tokenHash: "d".repeat(64),
expiresAt: new Date(now.getTime() - 1),
});
const service = await createService(true, "*/5 * * * *");
await service.onModuleInit();
expect(addCronJob).toHaveBeenCalledTimes(1);
expect(addCronJob).toHaveBeenCalledWith(
AUTH_REVOKED_TOKEN_CLEANUP_JOB,
expect.any(CronJob),
);
expect(await repository.count()).toBe(0);
const job = addCronJob.mock.calls[0][1] as CronJob;
expect(job.cronTime.source).toBe("*/5 * * * *");
await repository.insert({
tokenHash: "e".repeat(64),
expiresAt: new Date(now.getTime() - 1),
});
await job.fireOnTick();
expect(await repository.count()).toBe(0);
job.stop();
});
it("does not schedule or write cleanup data when authentication is disabled", async () => {
const service = await createService(false);
await repository.insert({
tokenHash: "f".repeat(64),
expiresAt: new Date("2020-01-01T00:00:00.000Z"),
});
await service.onModuleInit();
await service.cleanupExpiredTokens();
expect(addCronJob).not.toHaveBeenCalled();
expect(await repository.count()).toBe(1);
});
});
+107
View File
@@ -0,0 +1,107 @@
// eslint-disable-next-line @typescript-eslint/no-require-imports
import createDebug = require("debug");
import { createAppLogger } from "../src/common/app-logger";
import { DebugLogger } from "../src/common/debug-logger";
import { TraceLogger } from "../src/common/trace-logger";
import { traceStorage } from "../src/common/trace-context";
import { LogMode } from "../src/config/app.config";
describe("application logger selection and output", () => {
const originalLogMode = process.env.LOG_MODE;
const originalNodeEnv = process.env.NODE_ENV;
const originalDebug = createDebug.disable();
let stdout: jest.SpyInstance;
let stderr: jest.SpyInstance;
beforeEach(() => {
stdout = jest.spyOn(process.stdout, "write").mockImplementation(() => true);
stderr = jest.spyOn(process.stderr, "write").mockImplementation(() => true);
createDebug.disable();
});
afterEach(() => {
stdout.mockRestore();
stderr.mockRestore();
createDebug.disable();
if (originalDebug) createDebug.enable(originalDebug);
if (originalLogMode === undefined) delete process.env.LOG_MODE;
else process.env.LOG_MODE = originalLogMode;
if (originalNodeEnv === undefined) delete process.env.NODE_ENV;
else process.env.NODE_ENV = originalNodeEnv;
});
it("keeps console output as the default", () => {
delete process.env.LOG_MODE;
expect(createAppLogger("Runtime")).toBeInstanceOf(TraceLogger);
expect(
createAppLogger("Runtime").log("visible by default"),
).toBeUndefined();
expect(stdout).toHaveBeenCalled();
expect(stderr).not.toHaveBeenCalled();
});
it("keeps TraceLogger on console regardless of LOG_MODE", () => {
process.env.LOG_MODE = LogMode.Debug;
new TraceLogger("Runtime").log("trace logger stays on console");
expect(stdout).toHaveBeenCalled();
expect(stderr).not.toHaveBeenCalled();
});
it("preserves timestamp, level and trace context in console output", () => {
const before = Date.now();
traceStorage.run({ traceId: "trace-console" }, () => {
new TraceLogger("Runtime", { colors: false }).log("legacy format");
});
const output = stdout.mock.calls.flat().join("");
const timestamp = output.match(/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z/);
expect(timestamp).not.toBeNull();
expect(Date.parse(timestamp![0])).toBeGreaterThanOrEqual(before);
expect(output).toContain(" LOG [Runtime:trace-console] legacy format");
});
it("writes debug-mode output only when its namespace is enabled", () => {
process.env.LOG_MODE = LogMode.Debug;
process.env.NODE_ENV = "production";
createDebug.enable("liqa:other");
expect(createAppLogger("Runtime")).toBeInstanceOf(DebugLogger);
createAppLogger("Runtime").warn("quiet without matching namespace");
expect(stdout).not.toHaveBeenCalled();
expect(stderr).not.toHaveBeenCalled();
});
it("routes matching debug output with level, context, trace id and error detail", () => {
process.env.LOG_MODE = LogMode.Debug;
process.env.NODE_ENV = "production";
createDebug.enable("liqa:runtime");
traceStorage.run({ traceId: "trace-123" }, () => {
createAppLogger("Runtime").error(
"request failed",
"synthetic stack\n at test()",
"Runtime",
);
});
const output = stderr.mock.calls.flat().join("");
expect(stdout).not.toHaveBeenCalled();
expect(output).toContain("[ERROR] [Runtime:trace-123] request failed");
expect(output).toContain("synthetic stack");
});
it("preserves DEBUG=test for test-process logging", () => {
process.env.LOG_MODE = LogMode.Debug;
process.env.NODE_ENV = "test";
createDebug.enable("test");
createAppLogger("Unit").debug("test diagnostic");
expect(stdout).not.toHaveBeenCalled();
expect(stderr.mock.calls.flat().join("")).toContain("test diagnostic");
});
});
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more