Compare 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
ars9 14763103cf chore(release): cut minor release
CI / server (push) Successful in 1m7s
CI / changes (push) Skipped
CI / client (push) Successful in 1m23s
CI / image (push) Successful in 1m59s
- bump version to 1.25.0
- add browser notifications for scenario runs to the changelog
2026-10-07 19:23:01 +03:00
ars9 78f4c35d56 docs(claude): forbid co-author trailers and issue refs in commits
CI / changes (push) Successful in 6s
CI / server (push) Skipped
CI / client (push) Skipped
CI / image (push) Skipped
- keep issue references like Closes #12 for pull request descriptions
2026-10-07 19:22:02 +03:00
ars9 4b050fbdc4 Merge pull request 'Browser notifications' (#14) from feat/browser-notifications into master
CI / changes (push) Successful in 6s
CI / server (push) Successful in 3m4s
CI / client (push) Successful in 1m33s
CI / image (push) Skipped
Reviewed-on: #14
2026-10-07 19:20:59 +03:00
ars9 a93b3ef835 fix(client): keep run notifications connected in Firefox
CI / changes (pull_request) Successful in 6s
CI / server (pull_request) Successful in 1m16s
CI / client (pull_request) Successful in 1m28s
CI / image (pull_request) Skipped
- reopen the run events stream with backoff when the browser closes it for good (Firefox drops quiet connections after a network change)
- enable notifications when the permission is granted outside the bell, unless turned off explicitly
- follow permission changes made in the browser's site settings
- highlight the bell while notifications are on
2026-10-07 19:04:59 +03:00
ars9 d7eb018245 feat: browser notifications for scenario runs
- add RunEventsService and emit run.started / run.finished from the scheduler
- stream run events over SSE at GET /api/v1/scenarios/runs/events with a heartbeat
- add useRunNotifications hook and NotificationToggle (opt-in bell in the side panel footer)
- refresh runs lists when a run finishes
- document the events stream and notifications

Closes #12
2026-10-07 18:20:30 +03:00
ars9 968a8e470b chore(release): cut patch release
CI / server (push) Successful in 1m14s
CI / changes (push) Skipped
CI / client (push) Successful in 1m23s
CI / image (push) Successful in 1m52s
- bump version to 1.24.4
- add changelog entry for versioned export filenames and the
  install script terminal fix
2026-10-07 17:38:11 +03:00
ars9 3c8def3814 Merge pull request 'feat(client): include version in exported scenario and snippet filenames' (#13) from feat/export-version-filename into master
CI / changes (push) Successful in 6s
CI / server (push) Skipped
CI / client (push) Successful in 1m15s
CI / image (push) Skipped
Reviewed-on: #13
2026-10-07 17:36:55 +03:00
ars9 6e5da08719 feat(client): include version in exported scenario and snippet filenames
CI / changes (pull_request) Successful in 10s
CI / server (pull_request) Skipped
CI / client (pull_request) Successful in 1m21s
CI / image (pull_request) Skipped
- request the exact version being exported via ?version=N so file
  content always matches the filename
- name downloads <scenario>-v<N>.yaml and snippet-<alias>-v<N>.yaml
2026-10-07 17:34:21 +03:00
ars9 1abd95f9e1 Merge pull request 'fix(install): read prompts from the terminal and start liqa' (#11) from fix/install-tty into master
CI / changes (push) Successful in 6s
CI / server (push) Skipped
CI / client (push) Skipped
CI / image (push) Skipped
Reviewed-on: #11
2026-10-02 15:53:43 +03:00
111 changed files with 4623 additions and 91 deletions

No files matched your search

+13
View File
@@ -8,6 +8,19 @@
# NODE_ENV=development
# 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
## Vite dev server (http://localhost:5173) in development, the compose port
## (http://localhost:13000) in production
+37
View File
@@ -2,6 +2,43 @@
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
Changes since 1.24.4:
### Added
- Browser notifications for scenario runs: the UI shows "Run started / passed / failed: <scenario>" notifications for runs started from the UI, the REST API, MCP or the scheduler; clicking one opens the run. Turn them on with the bell button in the side panel footer (granting the permission from the browser's prompt or site settings works too). Notifications need a secure context (HTTPS or `localhost`).
- `GET /api/v1/scenarios/runs/events`: a server-sent events stream of run lifecycle events (`run.started`, `run.finished`) with a periodic `ping` heartbeat.
### Changed
- Runs lists refresh as soon as a run finishes while notifications are on.
## 1.24.4 - 2026-10-07
Changes since 1.24.3:
### Changed
- Exported scenario and snippet files include the exported version in their filename: `<scenario name>-v<N>.yaml` and `snippet-<alias>-v<N>.yaml`.
### Fixed
- `scripts/install.sh` reads prompts from the terminal, so `curl ... | bash` installs no longer consume the script's own lines as answers (it falls back to defaults when there is no terminal). It also checks that Docker, the compose plugin and the daemon work, and starts liqa with `docker compose up -d`, printing the manual start command if a check or the start fails.
## 1.24.3 - 2026-10-02
Changes since 1.24.2:
+2
View File
@@ -31,6 +31,8 @@ The live database is `data/liqa.db`. The container applies pending migrations be
Never commit directly to `master` when implementing a feature, chore or bug fix: create a separate branch for the work first, forked from `master`. These commits don't change the version or `CHANGELOG.md`; the branch is merged back to `master` through a pull request. Only release commits (see "Releasing a new version") are made on `master`.
Never add a `Co-Authored-By` trailer to commit messages. Don't put issue references like `Closes #12` in commit messages either; they belong only in the pull request description.
When committing on a work branch, also update the docs affected by the change (`docs/*.md`, `README.md`, `.env.example`, MCP tool descriptions) in the same branch.
## Code quality
+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.
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/`.
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,17 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { fn } from 'storybook/test';
import { NotificationToggle } from '../../src/ui/NotificationToggle/NotificationToggle';
const meta: Meta<typeof NotificationToggle> = {
title: 'UI/NotificationToggle',
component: NotificationToggle,
parameters: { layout: 'centered' },
tags: ['autodocs'],
args: { onToggle: fn() },
};
export default meta;
type Story = StoryObj<typeof NotificationToggle>;
export const Off: Story = { args: { state: 'off' } };
export const On: Story = { args: { state: 'on' } };
export const Blocked: Story = { args: { state: 'blocked' } };
@@ -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);
},
};
+70
View File
@@ -36,11 +36,19 @@
min-height: 100%;
}
.footerButtons {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1);
}
.sideFooter {
margin-top: auto;
padding: var(--space-3) var(--space-2) var(--space-2);
border-top: var(--border-width) solid var(--color-border);
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
@@ -62,6 +70,68 @@
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 {
display: flex;
align-items: center;
+86 -4
View File
@@ -1,12 +1,19 @@
import { lazy, Suspense } from 'react';
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import { LogOut } from 'lucide-react';
import { NavLink, Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import styles from './App.module.css';
import { SidePanel, ThemeSwitcher } from './ui';
import { NotificationToggle, SidePanel, ThemeSwitcher } from './ui';
import liqaLogo from './assets/liqa.svg';
import { useManifest } from './hooks/useManifest';
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(() =>
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
@@ -108,11 +115,59 @@ const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator:
export default function App() {
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 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 (
<div className={styles.shell}>
<SidePanel
collapsed={collapsed}
onCollapsedChange={setCollapsed}
header={
<div className={styles.header}>
<img src={liqaLogo} alt="Liqa" className={styles.brand} />
@@ -141,7 +196,19 @@ export default function App() {
</nav>
<div className={styles.sideFooter}>
<ThemeSwitcher />
<div className={styles.footerButtons}>
<ThemeSwitcher />
{notifications && (
<NotificationToggle state={notifications.state} onToggle={notifications.toggle} />
)}
{auth.enabled && auth.status === 'authenticated' && (
<SignOutControl
pending={loggingOut}
failed={logoutFailed}
onSignOut={() => void signOut()}
/>
)}
</div>
<div className={styles.version}>
<span
title={
@@ -166,6 +233,21 @@ export default function App() {
</div>
</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}>
<Suspense fallback={<p>Loading…</p>}>
<Routes>
+72 -9
View File
@@ -28,7 +28,28 @@ const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/
'',
);
async function request<T>(path: string, init?: RequestInit): Promise<T> {
/** URL of the server-sent events stream of run lifecycle events. */
export const RUN_EVENTS_URL = `${BASE_URL}/scenarios/runs/events`;
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;
try {
const headers = new Headers(init?.headers);
@@ -38,18 +59,26 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
res = await fetch(`${BASE_URL}${path}`, {
...init,
credentials: init?.credentials ?? 'include',
headers,
});
} catch (err) {
const message = (err as Error).message || 'Network request failed';
emitApiErrorToast(message);
if (!options.quietErrors) emitApiErrorToast(message);
throw new Error(message);
}
if (!res.ok) {
const text = await res.text().catch(() => res.statusText);
const message = `${res.status} ${text}`;
emitApiErrorToast(message);
throw new Error(message);
const error = new ApiError(res.status, 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');
if (res.status === 204 || contentLength === '0') return undefined as T;
@@ -62,6 +91,30 @@ async function request<T>(path: string, init?: RequestInit): Promise<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 ───────────────────────────────────────────────────────────────
export const credentials = {
@@ -123,8 +176,9 @@ export const snippets = {
versions(id: string): Promise<SnippetVersion[]> {
return request(`/snippets/${id}/versions`);
},
exportSnippet(id: string): Promise<unknown> {
return request(`/snippets/${id}/export`);
exportSnippet(id: string, version?: number): Promise<unknown> {
const query = version === undefined ? '' : `?version=${version}`;
return request(`/snippets/${id}/export${query}`);
},
};
@@ -247,7 +301,12 @@ export const scenarios = {
},
exportScenario(
id: string,
options: { includeEnvironment: boolean; credentialIds: string[]; snippetIds: string[] } = {
options: {
includeEnvironment: boolean;
credentialIds: string[];
snippetIds: string[];
version?: number;
} = {
includeEnvironment: false,
credentialIds: [],
snippetIds: [],
@@ -255,6 +314,9 @@ export const scenarios = {
): Promise<string> {
const params = new URLSearchParams();
params.set('includeEnvironment', String(options.includeEnvironment));
if (options.version !== undefined) {
params.set('version', String(options.version));
}
for (const cid of options.credentialIds) {
params.append('credentialIds', cid);
}
@@ -263,8 +325,9 @@ export const scenarios = {
}
return request(`/scenarios/${id}/export?${params.toString()}`);
},
exportE2eTestUrl(id: string): string {
return `${BASE_URL}/scenarios/${id}/export-e2e`;
exportE2eTestUrl(id: string, version?: number): string {
const query = version === undefined ? '' : `?version=${version}`;
return `${BASE_URL}/scenarios/${id}/export-e2e${query}`;
},
usedSnippets(id: string): Promise<UsedSnippet[]> {
return request(`/scenarios/${id}/used-snippets`);
+10
View File
@@ -234,3 +234,13 @@ export interface ImportedItem {
export interface ImportResult {
imported: ImportedItem[];
}
/** Run lifecycle event pushed by the server on `GET /scenarios/runs/events`. */
export interface RunEvent {
type: 'run.started' | 'run.finished';
runId: string;
scenarioId: string;
scenarioName: string;
status: ScenarioRunStatus;
at: string;
}
+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;
}
+184
View File
@@ -0,0 +1,184 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { RUN_EVENTS_URL } from '../api/client';
import type { RunEvent } from '../api/types';
import type { NotificationToggleState } from '../ui';
import { useAuth } from '../auth/useAuth';
const STORAGE_KEY = 'liqa-run-notifications';
const RETRY_MIN_MS = 1_000;
const RETRY_MAX_MS = 30_000;
export function createRunEventSource(): EventSource {
return new EventSource(RUN_EVENTS_URL, { withCredentials: true });
}
function supported(): boolean {
return typeof window !== 'undefined' && 'Notification' in window && 'EventSource' in window;
}
/** The stored choice: `null` until the user toggles notifications explicitly. */
function readEnabled(): boolean | null {
try {
const value = localStorage.getItem(STORAGE_KEY);
return value === null ? null : value === '1';
} catch {
return null;
}
}
function writeEnabled(enabled: boolean): void {
try {
localStorage.setItem(STORAGE_KEY, enabled ? '1' : '0');
} catch {
// storage unavailable: the choice just doesn't persist
}
}
/**
* Opt-in browser notifications for run start/finish, driven by the server's
* run events stream (so runs started from the API, MCP or the scheduler are
* covered too). Returns `null` when the browser lacks Notification/EventSource.
*/
export function useRunNotifications(): {
state: NotificationToggleState;
toggle: () => void;
} | null {
const auth = useAuth();
const isSupported = supported();
const { t } = useTranslation();
const navigate = useNavigate();
const queryClient = useQueryClient();
const [stored, setStored] = useState(readEnabled);
const [permission, setPermission] = useState<NotificationPermission>(() =>
isSupported ? Notification.permission : 'denied',
);
// Permission granted outside the toggle (browser prompt or site settings)
// enables notifications unless the user turned them off explicitly
const enabled = stored ?? permission === 'granted';
// Follow permission changes made in the browser's site settings
useEffect(() => {
if (!isSupported) return;
const sync = () => setPermission(Notification.permission);
let status: PermissionStatus | undefined;
let cancelled = false;
navigator.permissions
?.query({ name: 'notifications' })
.then((s) => {
if (cancelled) return;
status = s;
status.addEventListener('change', sync);
})
.catch(() => {});
window.addEventListener('focus', sync);
return () => {
cancelled = true;
status?.removeEventListener('change', sync);
window.removeEventListener('focus', sync);
};
}, [isSupported]);
// Latest callbacks without reopening the stream when they change
const handlers = useRef({ t, navigate });
useEffect(() => {
handlers.current = { t, navigate };
});
const active =
isSupported &&
enabled &&
permission === 'granted' &&
(!auth.enabled || auth.status === 'authenticated');
useEffect(() => {
if (!active) return;
let source: EventSource;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
let retryDelay = RETRY_MIN_MS;
const onEvent = (message: MessageEvent<string>) => {
let event: RunEvent;
try {
event = JSON.parse(message.data) as RunEvent;
} catch {
return;
}
if (event.type === 'run.finished') {
void queryClient.invalidateQueries({ queryKey: ['runs'] });
}
const { t: translate, navigate: go } = handlers.current;
const key =
event.type === 'run.started'
? 'run_started'
: event.status === 'pass'
? 'run_pass'
: 'run_fail';
const notification = new Notification(
translate(`notifications.${key}_title`, { scenario: event.scenarioName }),
{
body: translate(`notifications.${key}_body`),
// finished replaces started for the same run
tag: event.runId,
},
);
notification.onclick = () => {
window.focus();
go(`/scenarios/${event.scenarioId}/runs/${event.runId}`);
notification.close();
};
};
const connect = () => {
source = createRunEventSource();
source.addEventListener('open', () => {
retryDelay = RETRY_MIN_MS;
});
// The browser retries transient errors itself, but some failures close
// the stream for good (e.g. Firefox drops quiet connections after a
// network change), so reopen it with backoff
source.addEventListener('error', () => {
if (source.readyState !== EventSource.CLOSED) return;
retryTimer = setTimeout(connect, retryDelay);
retryDelay = Math.min(retryDelay * 2, RETRY_MAX_MS);
});
source.addEventListener('run.started', onEvent as EventListener);
source.addEventListener('run.finished', onEvent as EventListener);
};
connect();
return () => {
clearTimeout(retryTimer);
source.close();
};
}, [active, queryClient]);
const toggle = useCallback(() => {
if (!isSupported) return;
if (Notification.permission === 'default') {
void Notification.requestPermission().then((result) => {
setPermission(result);
if (result === 'granted') {
setStored(true);
writeEnabled(true);
}
});
return;
}
if (Notification.permission !== 'granted') {
setPermission(Notification.permission);
return;
}
const next = !enabled;
setStored(next);
writeEnabled(next);
}, [isSupported, enabled]);
if (!isSupported) return null;
return {
state: permission === 'denied' ? 'blocked' : active ? 'on' : 'off',
toggle,
};
}
+31
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": {
"button_cancel": "Cancel",
"button_confirm": "Confirm",
@@ -235,6 +255,17 @@
"light_mode": "Light mode",
"dark_mode": "Dark mode"
},
"notifications": {
"enable": "Enable browser notifications for runs",
"disable": "Disable browser notifications for runs",
"blocked": "Notifications are blocked in your browser settings",
"run_started_title": "Run started: {{scenario}}",
"run_started_body": "The scenario run is in progress.",
"run_pass_title": "Run passed: {{scenario}}",
"run_pass_body": "All steps passed.",
"run_fail_title": "Run failed: {{scenario}}",
"run_fail_body": "The scenario run failed."
},
"revealable": {
"hidden": "Hidden so secrets aren't exposed on screen.",
"reveal": "Reveal",
+9 -1
View File
@@ -8,12 +8,16 @@ export interface Manifest {
runLogs: {
dataLimits: LogDataLimits;
};
auth: {
enabled: boolean;
};
}
export const DEFAULT_MANIFEST: Manifest = {
name: 'liqa',
version: __APP_VERSION__,
runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS },
auth: { enabled: false },
};
const STORAGE_KEY = 'liqa-manifest';
@@ -39,6 +43,7 @@ function normalize(raw: unknown): Manifest | null {
return {
name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name,
version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version,
auth: { enabled: m.auth?.enabled === true },
runLogs: {
dataLimits: {
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.
*/
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((raw: unknown) => {
const next = normalize(raw);
+13 -2
View File
@@ -6,15 +6,26 @@ import './i18n';
import './ui/tokens.css';
import App from './App';
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(
<StrictMode>
<QueryClientProvider client={queryClient}>
<ToastProvider>
<BrowserRouter>
<App />
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
</ToastProvider>
</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>
);
}
@@ -229,12 +229,13 @@ export function ScenarioDetailPage() {
includeEnvironment,
credentialIds: credIds,
snippetIds: Array.from(includedSnippetIds),
version: scenario.version,
});
const blob = new Blob([yamlContent], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${scenario.name}.yaml`;
a.download = `${scenario.name}-v${scenario.version}.yaml`;
a.click();
URL.revokeObjectURL(url);
setExportModalOpen(false);
@@ -503,7 +504,10 @@ export function ScenarioDetailPage() {
variant="secondary"
size="sm"
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} />
@@ -51,12 +51,12 @@ export function SnippetDetailPage() {
const handleExport = async () => {
if (!snippet) return;
const data = await snippets.exportSnippet(snippet.id);
const data = await snippets.exportSnippet(snippet.id, snippet.version);
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `snippet-${snippet.alias}.yaml`;
a.download = `snippet-${snippet.alias}-v${snippet.version}.yaml`;
a.click();
URL.revokeObjectURL(url);
};
+6
View File
@@ -88,3 +88,9 @@
@keyframes spin {
to { transform: rotate(360deg); }
}
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
@@ -0,0 +1,48 @@
.btn {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
padding: 0;
background: none;
border: var(--border-width) solid var(--color-border);
border-radius: var(--radius-md);
color: var(--color-text-muted);
cursor: pointer;
flex-shrink: 0;
transition: background var(--transition), color var(--transition), border-color var(--transition);
}
.btn:hover {
background: var(--color-bg-subtle);
color: var(--color-text);
border-color: var(--color-text-muted);
}
.btn:active {
background: var(--color-secondary);
color: var(--color-secondary-fg);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn:disabled:hover {
background: none;
color: var(--color-text-muted);
border-color: var(--color-border);
}
.btn[aria-pressed='true'] {
background: var(--color-primary);
border-color: var(--color-primary);
color: var(--color-primary-fg);
}
.btn[aria-pressed='true']:hover {
background: var(--color-primary-hover);
border-color: var(--color-primary-hover);
}
@@ -0,0 +1,39 @@
import { Bell, BellOff } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import styles from './NotificationToggle.module.css';
/**
* - `on`: notifications are enabled
* - `off`: available, but not enabled (or permission not asked yet)
* - `blocked`: the browser denied the permission
*/
export type NotificationToggleState = 'on' | 'off' | 'blocked';
export interface NotificationToggleProps {
state: NotificationToggleState;
onToggle: () => void;
}
export function NotificationToggle({ state, onToggle }: NotificationToggleProps) {
const { t } = useTranslation();
const label =
state === 'on'
? t('notifications.disable')
: state === 'blocked'
? t('notifications.blocked')
: t('notifications.enable');
return (
<button
type="button"
className={styles.btn}
onClick={onToggle}
disabled={state === 'blocked'}
aria-label={label}
aria-pressed={state === 'on'}
title={label}
>
{state === 'on' ? <Bell size={16} /> : <BellOff size={16} />}
</button>
);
}
+1 -1
View File
@@ -38,7 +38,7 @@ export function SidePanel({
style={{ '--side-panel-width': `${width}px` } as React.CSSProperties}
aria-expanded={!collapsed}
>
<div className={styles.inner}>
<div className={styles.inner} aria-hidden={collapsed} inert={collapsed}>
{header && <div className={styles.header}>{header}</div>}
<div className={styles.content}>{children}</div>
</div>
+2
View File
@@ -26,6 +26,8 @@ export { Breadcrumbs } from './Breadcrumbs/Breadcrumbs';
export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs';
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
export { NotificationToggle } from './NotificationToggle/NotificationToggle';
export type { NotificationToggleState } from './NotificationToggle/NotificationToggle';
export { ToastProvider } from './Toast/ToastProvider';
export type { ToastProviderProps } from './Toast/ToastProvider';
+9 -1
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.
## 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/`)
- **McpService** (`mcp/`) registers the MCP tools and delegates to the services below. Each request gets a fresh MCP server over the Streamable HTTP transport.
@@ -75,8 +81,10 @@ A React 19 + TypeScript SPA. During development it's served by the Vite dev serv
The client calls the server REST endpoints directly — there is no separate BFF layer. Routing uses `BrowserRouter`; the server answers any GET outside `/api`, `/mcp`, `/docs`, `/health` and `/manifest.json` with the client's `index.html`, so client-side routes survive a page refresh.
Pages: scenarios (with steps, versions, credentials, used snippets and files), runs, snippets, credentials, environments, sessions, and the central import page. The sidebar footer contains the theme switcher and the app version.
Pages: scenarios (with steps, versions, credentials, used snippets and files), runs, snippets, credentials, environments, sessions, and the central import page. The sidebar footer contains the theme switcher, the browser notifications toggle and the app version.
`GET /manifest.json` is the server's public configuration for the client: the app `name` and `version`, and settings the UI needs (currently `runLogs.dataLimits`, from `RUN_LOG_DATA_COLLAPSE_BYTES` / `RUN_LOG_DATA_COLLAPSE_LINES`). The client reads it through `client/src/lib/manifest.ts` and the `useManifest()` hook, stale-while-revalidate: the copy cached in `localStorage` (or built-in defaults on first visit) is used right away, and the manifest is refetched once per page load and when the tab becomes visible again after 5 minutes. The server sends it with `Cache-Control: no-cache` and an ETag, so an unchanged manifest costs a 304. Add new client-facing settings to the manifest (`server/src/manifest/`) rather than as build-time Vite variables.
Run notifications: `RunEventsService` (`scenario/`) is an in-process rxjs subject. The scheduler emits `run.started` and `run.finished` (once per run, from the run's single exit points rather than each pass/fail transition), and `GET /api/v1/scenarios/runs/events` streams them as SSE. The `useRunNotifications` hook opens an `EventSource` to it, only while the user has enabled notifications and the browser permission is granted, and shows a `Notification` per event. See [scenario.md](scenario.md#run-events-and-browser-notifications).
See [development.md](development.md) for the full client tech stack and directory layout.
+56 -2
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 |
| `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 |
| `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 |
| `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 |
@@ -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 |
| `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`. |
| `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.
### 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):
1. Change the entity and build (`npm -w server run build`).
@@ -138,7 +192,7 @@ Watch mode:
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
npm -w server run test:debug
@@ -320,7 +374,7 @@ client/
src/
api/ API client (client.ts) and types (types.ts)
components/ modals/ - run, export, export logs and delete confirmation modals
hooks/ useTheme, usePageTitle, useRunDefaults, useImportFile
hooks/ useTheme, usePageTitle, useRunDefaults, useImportFile, useRunNotifications
i18n/ i18next bootstrap + locales/en.json
lib/ highlight.js setup, API error toast events
pages/ scenario/, run/, snippet/, credential/, environment/, session/, import/
+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.
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.
## 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) |
| `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)) |
| `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.
+18
View File
@@ -114,6 +114,10 @@ steps:
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
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.
@@ -128,6 +132,20 @@ Traces are off by default because they often reach ~10 MB per run.
Traces are run artifacts, so they expire after `FILE_RUN_EXPIRATION_DAYS` like other run files.
## Run events and browser notifications
The server publishes run lifecycle events on a server-sent events (SSE) stream, `GET /api/v1/scenarios/runs/events`, regardless of how the run was started (UI, REST API, MCP or the scheduler). Each message is named after its `type` and carries a JSON body:
```json
{ "type": "run.finished", "runId": "...", "scenarioId": "...", "scenarioName": "Login", "status": "pass", "at": "2026-01-01T12:00:00.000Z" }
```
- `run.started` is sent when a run becomes `in_progress` (`status` is `in_progress`).
- `run.finished` is sent exactly once per run, with the final `status` (`pass` or `fail`), including runs that fail during setup, time out, or are failed on server restart.
- A `ping` event is sent every 25 s to keep idle connections open through proxies.
The UI uses this stream for opt-in browser notifications: the bell button in the side panel footer asks for the notification permission (granting it from the browser's own prompt or site settings works too) and then shows "Run started / passed / failed: <scenario>" notifications while the UI is open in a tab; clicking one opens the run. The bell is highlighted while notifications are on; turning them off is stored in the browser's `localStorage`. Browsers only offer notifications in a secure context (HTTPS or `localhost`), so over plain HTTP on another host the bell has no effect. When the permission is blocked, the button is disabled; re-allow it in the browser's site settings. Finished runs also refresh the runs lists immediately.
## Statuses
Run status:
+3 -3
View File
@@ -1,12 +1,12 @@
{
"name": "liqa",
"version": "1.24.3",
"version": "1.26.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "liqa",
"version": "1.24.3",
"version": "1.26.0",
"license": "MIT",
"workspaces": [
"server",
@@ -17464,6 +17464,7 @@
"better-sqlite3": "^12.8.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.4",
"debug": "^4.4.3",
"effect": "^3.21.0",
"jsdom": "^29.0.2",
"playwright": "^1.59.1",
@@ -17487,7 +17488,6 @@
"@types/mozilla__readability": "^0.4.2",
"@types/node": "^25.5.2",
"@types/supertest": "^7.2.0",
"debug": "^4.4.3",
"eslint": "^10.2.0",
"eslint-config-prettier": "^10.1.8",
"jest": "^30.3.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "liqa",
"version": "1.24.3",
"version": "1.26.0",
"private": true,
"license": "MIT",
"author": "Andrii Arsenin",
+1
View File
@@ -6,6 +6,7 @@ module.exports = {
transform: {
'^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }],
},
setupFiles: ['<rootDir>/test/logging.setup.js'],
moduleNameMapper: {
'^jsdom$': '<rootDir>/test/__mocks__/jsdom.ts',
'^playwright$': '<rootDir>/test/__mocks__/playwright.ts',
+2 -1
View File
@@ -10,6 +10,7 @@
"migration:run": "node dist/database/migrate",
"migration:show": "typeorm migration:show -d dist/database/data-source.js",
"migration:generate": "typeorm migration:generate -d dist/database/data-source.js",
"cli": "node dist/cli.js",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
@@ -37,6 +38,7 @@
"better-sqlite3": "^12.8.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.4",
"debug": "^4.4.3",
"effect": "^3.21.0",
"jsdom": "^29.0.2",
"playwright": "^1.59.1",
@@ -60,7 +62,6 @@
"@types/mozilla__readability": "^0.4.2",
"@types/node": "^25.5.2",
"@types/supertest": "^7.2.0",
"debug": "^4.4.3",
"eslint": "^10.2.0",
"eslint-config-prettier": "^10.1.8",
"jest": "^30.3.0",
+2
View File
@@ -4,6 +4,7 @@ import { ScheduleModule } from "@nestjs/schedule";
import { ServeStaticModule } from "@nestjs/serve-static";
import { TypeOrmModule } from "@nestjs/typeorm";
import { BrowserModule } from "./browser/browser.module";
import { AuthModule } from "./auth/auth.module";
import { clientStaticOptions } from "./common/client-static";
import { dataSourceOptions } from "./database/data-source";
import { AppConfig, validateAppConfig } from "./config/app.config";
@@ -36,6 +37,7 @@ import { SnippetModule } from "./snippet/snippet.module";
dataSourceOptions(config.get("DB_PATH")),
}),
BrowserModule,
AuthModule,
EnvironmentModule,
CredentialModule,
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 { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import {
ApiBearerAuth,
ApiOperation,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { CodeExecutorService } from "../code-executor/code-executor.service";
import { CredentialService } from "../credential/credential.service";
import { EnvironmentService } from "../environment/environment.service";
@@ -8,6 +13,7 @@ import { ExecDto } from "./dto/exec.dto";
import { OpenDto } from "./dto/open.dto";
@ApiTags("browser")
@ApiBearerAuth()
@Controller()
export class BrowserController {
constructor(
+2 -2
View File
@@ -12,7 +12,7 @@ import type {
ScriptLogger,
} 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 { SessionContextService } from "../session/session-context.service";
import { SessionService } from "../session/session.service";
@@ -28,7 +28,7 @@ export interface OpenResult {
@Injectable()
export class BrowserService {
private readonly logger = new TraceLogger(BrowserService.name);
private readonly logger = createAppLogger(BrowserService.name);
constructor(
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 { URL } from "node:url";
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 { FileStorageService } from "../file/file-storage.service";
import type { DomNode } from "./dom-helpers";
@@ -115,7 +115,7 @@ export interface ExecContext {
@Injectable()
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
+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 { getTraceId } from "./trace-context";
/** Runtime console logger. Output is always written using Nest's console behavior. */
export class TraceLogger extends ConsoleLogger {
constructor(context?: string, options: ConsoleLoggerOptions = {}) {
super(context as string, options);
@@ -10,6 +11,11 @@ export class TraceLogger extends ConsoleLogger {
return new Date().toISOString();
}
protected override formatContext(context: string): string {
const traceId = getTraceId();
return super.formatContext(traceId ? `${context}:${traceId}` : context);
}
protected override formatMessage(
logLevel: LogLevel,
message: unknown,
@@ -22,10 +28,4 @@ export class TraceLogger extends ConsoleLogger {
const level = this.colorize(logLevel.toUpperCase(), logLevel);
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 {
IsBoolean,
IsEnum,
IsInt,
IsString,
@@ -10,12 +12,19 @@ import {
import { appPackage } from "../common/app-package";
import { durationSeconds } from "../common/interval";
export enum TraceMode {
On = "on",
RetainOnFailure = "retain-on-failure",
Off = "off",
}
export enum LogMode {
Console = "console",
Debug = "debug",
}
export class AppConfig {
/** `production` in the Docker image; also selects the default CORS origins. */
@IsString()
@@ -36,6 +45,10 @@ export class AppConfig {
@IsString()
APP_VERSION: string = appPackage().version;
/** Route application diagnostics through `debug` instead of the console. */
@IsEnum(LogMode)
LOG_MODE: LogMode = LogMode.Console;
@IsString()
DB_PATH: string = "data/liqa.db";
@@ -74,15 +87,66 @@ export class AppConfig {
@IsInt()
@Min(0)
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 {
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,
});
const errors = validateSync(validated, { skipMissingProperties: false });
if (errors.length > 0) {
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;
}
@@ -10,7 +10,12 @@ import {
Post,
Query,
} 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 { CredentialService } from "./credential.service";
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";
@ApiTags("credentials")
@ApiBearerAuth()
@Controller("credentials")
export class CredentialController {
constructor(private readonly credentialService: CredentialService) {}
+4
View File
@@ -1,4 +1,6 @@
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 { FileEntity } from "../file/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). */
export const ENTITIES = [
UserEntity,
RevokedTokenEntity,
SessionEntity,
EnvironmentEntity,
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 { AddRunLogContext1790848194828 } from "./1790848194828-AddRunLogContext";
import { AddRunLogData1790850734763 } from "./1790850734763-AddRunLogData";
import { AddAuthUsersAndRevokedTokens1793823870652 } from "./1793823870652-AddAuthUsersAndRevokedTokens";
/**
* All migrations, oldest first. Listed explicitly (instead of a glob) so the
@@ -10,4 +11,5 @@ export const MIGRATIONS = [
Initial1790793447827,
AddRunLogContext1790848194828,
AddRunLogData1790850734763,
AddAuthUsersAndRevokedTokens1793823870652,
];
@@ -10,7 +10,12 @@ import {
Post,
Query,
} 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 { CreateEnvironmentDto } from "./dto/create-environment.dto";
import { EnvironmentExportDto } from "./dto/environment-export.dto";
@@ -18,6 +23,7 @@ import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
import { EnvironmentService } from "./environment.service";
@ApiTags("environments")
@ApiBearerAuth()
@Controller("environments")
export class EnvironmentController {
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 { CronJob } from "cron";
import { Repository } from "typeorm";
import { TraceLogger } from "../common/trace-logger";
import { createAppLogger } from "../common/app-logger";
import { AppConfig } from "../config/app.config";
import { FileEntity } from "./file.entity";
import { ScenarioFileEntity } from "./scenario-file.entity";
@@ -27,7 +27,7 @@ export interface FileMetadata {
@Injectable()
export class FileStorageService implements OnModuleInit {
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 fileRunExpirationDays: number;
private readonly fileCleanupCron: string;
+2 -2
View File
@@ -7,11 +7,11 @@ import {
InternalServerErrorException,
} from "@nestjs/common";
import type { Request, Response } from "express";
import { TraceLogger } from "../common/trace-logger";
import { createAppLogger } from "../common/app-logger";
@Catch(BadRequestException, InternalServerErrorException)
export class HttpExceptionFilter implements ExceptionFilter {
private readonly logger = new TraceLogger(HttpExceptionFilter.name);
private readonly logger = createAppLogger(HttpExceptionFilter.name);
catch(exception: HttpException, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
+3
View File
@@ -1,10 +1,12 @@
import { Controller, Get } from "@nestjs/common";
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
import { Public } from "../auth/public.decorator";
@ApiTags("health")
@Controller()
export class HealthController {
@Get("health")
@Public()
@ApiOperation({ summary: "Health check" })
@ApiResponse({ status: 200, description: "Service is healthy" })
health(): { status: string } {
@@ -12,6 +14,7 @@ export class HealthController {
}
@Get("healthz")
@Public()
@ApiOperation({ summary: "Health check" })
@ApiResponse({ status: 200, description: "Service is healthy" })
healthz(): { status: string } {
+2
View File
@@ -1,5 +1,6 @@
import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
import {
ApiBearerAuth,
ApiBody,
ApiConsumes,
ApiOperation,
@@ -10,6 +11,7 @@ import { YAML_CONTENT_TYPES } from "../common/body-parsers";
import { ImportService } from "./import.service";
@ApiTags("import")
@ApiBearerAuth()
@Controller("import")
export class ImportController {
constructor(private readonly importService: ImportService) {}
+24 -3
View File
@@ -6,11 +6,29 @@ import {
} from "@nestjs/common";
import type { Request, Response } from "express";
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()
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> {
const http = context.switchToHttp();
@@ -18,8 +36,11 @@ export class LoggingInterceptor implements NestInterceptor {
const res = http.getResponse<Response>();
const { method, url, body } = req;
const start = Date.now();
const safeBody = redactAuthRequestBody(req.path, body);
const bodyStr =
body && Object.keys(body).length ? ` ${JSON.stringify(body)}` : "";
safeBody && Object.keys(safeBody).length
? ` ${JSON.stringify(safeBody)}`
: "";
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 { configureBodyParsers } from "./common/body-parsers";
import { corsOrigins } from "./common/cors";
import { TraceLogger } from "./common/trace-logger";
import { createAppLogger } from "./common/app-logger";
import { AppConfig } from "./config/app.config";
import { HttpExceptionFilter } from "./filters/http-exception.filter";
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
// callbacks (e.g. a bad waitForURL predicate). Without this, Node.js v15+
// crashes the process on any unhandled rejection or uncaught exception.
const processLogger = new TraceLogger("Process");
const processLogger = createAppLogger("Process");
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) => {
processLogger.error(
@@ -32,9 +35,9 @@ process.on("unhandledRejection", (reason) => {
async function bootstrap() {
const { name: pkgName, version: pkgVersion } = appPackage();
const API_PREFIX = "api/v1";
const logger = new TraceLogger("Bootstrap");
const logger = createAppLogger("Bootstrap");
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.
@@ -74,6 +77,7 @@ async function bootstrap() {
.setTitle(pkgName)
.setDescription(`${pkgName} API`)
.setVersion(pkgVersion)
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, swaggerConfig);
@@ -2,6 +2,7 @@ import { Controller, Get, Header } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";
import { AppConfig } from "../config/app.config";
import { Public } from "../auth/public.decorator";
import { ManifestDto } from "./manifest.dto";
@ApiTags("manifest")
@@ -10,6 +11,7 @@ export class ManifestController {
constructor(private readonly config: ConfigService<AppConfig, true>) {}
@Get("manifest.json")
@Public()
// Clients cache the manifest themselves; the browser just revalidates it (ETag)
@Header("Cache-Control", "no-cache")
@ApiOperation({ summary: "Public client configuration and app version" })
@@ -18,6 +20,7 @@ export class ManifestController {
return {
name: this.config.get("APP_NAME"),
version: this.config.get("APP_VERSION"),
auth: { enabled: this.config.get("AUTH_ENABLED") },
runLogs: {
dataLimits: {
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 {
@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,
})
bytes!: number;
@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,
})
lines!: number;
@@ -26,6 +28,13 @@ export class ManifestDto {
@ApiProperty({ example: "1.4.0" })
version!: string;
@ApiProperty({
description: "Whether account authentication is enabled.",
type: "object",
properties: { enabled: { type: "boolean", example: false } },
})
auth!: { enabled: boolean };
@ApiProperty({ type: RunLogsManifestDto })
runLogs!: RunLogsManifestDto;
}
+7 -1
View File
@@ -1,9 +1,15 @@
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 { McpService } from "./mcp.service";
@ApiTags("mcp")
@ApiBearerAuth()
@Controller("mcp")
export class McpController {
constructor(private readonly mcpService: McpService) {}
+9 -3
View File
@@ -1343,15 +1343,21 @@ export class McpService {
"export_e2e_test",
{
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: {
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 {
const { filename, buffer } =
await this.e2eExportService.buildE2eTestPackage(id);
await this.e2eExportService.buildE2eTestPackage(id, version);
return {
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,
) {}
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 content = await this.scenarioService.findVersion(
scenarioId,
version ?? scenario.version,
);
const [credentialMap, snippetMap, attachedFiles] = await Promise.all([
this.scenarioService.buildCredentialMap(scenarioId),
this.snippetService.buildSnippetMap(),
@@ -51,10 +59,10 @@ export class E2eExportService {
]);
const envData = scenario.environment?.data ?? {};
const slug = slugify(scenario.name);
const slug = `${slugify(content.name)}-v${content.version}`;
const files: Record<string, string | Buffer> = {
"package.json": this.buildPackageJson(slug),
"playwright.config.ts": this.buildPlaywrightConfig(scenario.timeoutSeconds),
"playwright.config.ts": this.buildPlaywrightConfig(content.timeoutSeconds),
".env": this.buildEnvFile(envData),
"credentials.json": JSON.stringify(credentialMap, null, 2) + "\n",
".gitignore": [
@@ -65,7 +73,7 @@ export class E2eExportService {
".env",
"credentials.json",
].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.
@@ -97,7 +105,7 @@ export class E2eExportService {
// Bundle only the snippets actually referenced (directly or transitively via
// other snippets) by this scenario's steps, as individual .js files under snippets/.
const usedAliases = resolveUsedSnippetAliases(
scenario.steps.map((s) => s.execCode ?? ""),
content.steps.map((s) => s.execCode ?? ""),
snippetMap,
);
const snippetManifest: { alias: string; filename: string }[] = [];
@@ -116,7 +124,7 @@ export class E2eExportService {
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);
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` : "";
return `# ${scenarioName} - standalone e2e test
return `# ${scenarioName} (v${version}) - standalone e2e test
${descriptionSection}## Setup
+31
View File
@@ -0,0 +1,31 @@
import { Injectable } from "@nestjs/common";
import { Observable, Subject } from "rxjs";
export type RunEventStatus = "pending" | "in_progress" | "pass" | "fail";
export interface RunEvent {
type: "run.started" | "run.finished";
runId: string;
scenarioId: string;
scenarioName: string;
status: RunEventStatus;
/** ISO timestamp of the transition. */
at: string;
}
/**
* In-process event bus for scenario run lifecycle transitions. The scheduler
* emits; the SSE endpoint (and tests) subscribe.
*/
@Injectable()
export class RunEventsService {
private readonly subject = new Subject<RunEvent>();
emit(event: RunEvent): void {
this.subject.next(event);
}
stream(): Observable<RunEvent> {
return this.subject.asObservable();
}
}
@@ -19,7 +19,7 @@ import {
} from "../code-executor/code-executor.service";
import { ExecContextBuilder } from "../code-executor/exec-context.builder";
import { traceStorage } from "../common/trace-context";
import { TraceLogger } from "../common/trace-logger";
import { createAppLogger } from "../common/app-logger";
import {
EnvironmentData,
EnvironmentEntity,
@@ -30,6 +30,7 @@ import { SnippetService } from "../snippet/snippet.service";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { RunEventsService } from "./run-events.service";
import { ScenarioService } from "./scenario.service";
interface BrowserHandle {
@@ -41,7 +42,7 @@ interface BrowserHandle {
@Injectable()
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 runBrowsers = new Map<string, BrowserHandle>();
// Cache credential maps per run (built once when a run starts)
@@ -80,6 +81,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
private readonly sessionService: SessionService,
private readonly sessionContextService: SessionContextService,
private readonly fileStorageService: FileStorageService,
private readonly runEvents: RunEventsService,
configService: ConfigService<AppConfig, true>,
) {
this.defaultTraceMode = configService.get("PLAYWRIGHT_TRACE_MODE");
@@ -109,7 +111,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
this.failRun(
run.id,
"Run aborted: server restarted and playwright session could not be recovered",
),
).then(() => this.emitFinished(run.id)),
).pipe(
Effect.catchAll((err) =>
Effect.sync(() =>
@@ -149,6 +151,48 @@ export class ScenarioSchedulerService implements OnModuleInit {
this.persistLog(runId, null, "error", reason, "run");
}
/**
* Publishes a run lifecycle event. Never throws: a notification problem
* must not affect the run itself.
*/
private async emitRunEvent(
type: "run.started" | "run.finished",
runId: string,
): Promise<void> {
try {
const run = await this.runRepo.findOneBy({ id: runId });
if (!run) return;
if (type === "run.finished" && run.status !== "pass" && run.status !== "fail") {
return;
}
const scenario = await this.scenarioService
.findOne(run.scenarioId)
.catch(() => null);
this.runEvents.emit({
type,
runId,
scenarioId: run.scenarioId,
scenarioName: scenario?.name ?? run.scenarioId,
status: run.status,
at: new Date().toISOString(),
});
} catch (err) {
this.logger.warn(
`Run #${runId}: failed to emit ${type} event — ${String(err)}`,
);
}
}
/**
* Emits `run.finished` with the run's final status. Called exactly once per
* run, from the single exit point of each run's lifecycle (the `finally` of
* processRunToCompletion, setup failure, stale-run cleanup), never from the
* individual pass/fail transitions.
*/
private emitFinished(runId: string): Promise<void> {
return this.emitRunEvent("run.finished", runId);
}
private persistLog(
runId: string,
stepRunId: string | null,
@@ -214,6 +258,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
run.status = "in_progress";
await this.runRepo.save(run);
this.logger.log(`Run #${run.id} → in_progress`);
await this.emitRunEvent("run.started", run.id);
const credMap = await this.scenarioService
.buildCredentialMap(run.scenarioId)
.catch(() => ({}) as Record<string, unknown>);
@@ -267,6 +312,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
run.id,
`Run setup failed: ${String(err)}`,
).catch(() => {});
await this.emitFinished(run.id);
}),
),
);
@@ -315,6 +361,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
);
await this.failRun(runId, `Unexpected error: ${(err as Error).message}`);
} finally {
await this.emitFinished(runId);
// Before runLogSeq is cleared, so the trace log entry keeps its order
await this.saveTrace(runId);
this.activeRuns.delete(runId);
+51 -7
View File
@@ -11,12 +11,19 @@ import {
Post,
Query,
Res,
Sse,
UseInterceptors,
UploadedFile,
} from "@nestjs/common";
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 { interval, map, merge, type Observable } from "rxjs";
import type { File as MulterFile } from "multer";
import { stringify as yamlStringify } from "yaml";
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
@@ -28,15 +35,25 @@ import { RunsQueryDto } from "./dto/runs-query.dto";
import { ExportEntity, ScenarioExportDto } from "./dto/scenario-export.dto";
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
import { RunEventsService } from "./run-events.service";
import { ScenarioService } from "./scenario.service";
import { E2eExportService } from "./e2e-export.service";
interface SseMessage {
type: string;
data: object;
}
@ApiTags("scenarios")
@ApiBearerAuth()
@Controller("scenarios")
export class ScenarioController {
private static readonly HEARTBEAT_MS = 25_000;
constructor(
private readonly scenarioService: ScenarioService,
private readonly e2eExportService: E2eExportService,
private readonly runEvents: RunEventsService,
) {}
// ── Scenarios ─────────────────────────────────────────────────────────────
@@ -49,7 +66,10 @@ export class ScenarioController {
}
@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" })
importScenario(@Body() payload: unknown) {
return this.scenarioService.importScenario(
@@ -73,6 +93,23 @@ export class ScenarioController {
return this.scenarioService.findAllRuns(query);
}
@Sse("runs/events")
@ApiOperation({
summary:
"Server-sent events stream of run lifecycle events (run.started, run.finished) for all scenarios",
})
@ApiResponse({ status: 200, description: "text/event-stream" })
streamRunEvents(): Observable<SseMessage> {
const events = this.runEvents
.stream()
.pipe(map((event): SseMessage => ({ type: event.type, data: event })));
// Periodic named event so proxies don't drop an idle connection
const heartbeat = interval(ScenarioController.HEARTBEAT_MS).pipe(
map((): SseMessage => ({ type: "ping", data: {} })),
);
return merge(events, heartbeat);
}
@Get("run-defaults")
@ApiOperation({ summary: "Get server-configured defaults for new runs" })
@ApiResponse({ status: 200 })
@@ -172,15 +209,19 @@ export class ScenarioController {
@Get(":id/export-e2e")
@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: 404, description: "Scenario not found" })
@ApiResponse({ status: 404, description: "Scenario or version not found" })
async exportE2eTest(
@Param("id", ParseUUIDPipe) id: string,
@Query("version", new ParseIntPipe({ optional: true }))
version: number | undefined,
@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-Disposition", `attachment; filename="${filename}"`);
res.setHeader("Content-Length", buffer.length);
@@ -237,7 +278,8 @@ export class ScenarioController {
@Get(":id/used-snippets")
@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: 404, description: "Scenario not found" })
@@ -342,7 +384,9 @@ export class ScenarioController {
const fmt = format === "csv" ? "csv" : "md";
const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
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";
res.setHeader("Content-Type", contentType);
res.setHeader(
+7 -1
View File
@@ -13,6 +13,7 @@ import { ScenarioCredentialEntity } from "./scenario-credential.entity";
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
import { ScenarioRunEntity } from "./scenario-run.entity";
import { RunEventsService } from "./run-events.service";
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
import { ScenarioVersionEntity } from "./scenario-version.entity";
import { ScenarioStepEntity } from "./scenario-step.entity";
@@ -43,7 +44,12 @@ import { E2eExportService } from "./e2e-export.service";
FileModule,
],
controllers: [ScenarioController],
providers: [ScenarioService, ScenarioSchedulerService, E2eExportService],
providers: [
ScenarioService,
ScenarioSchedulerService,
E2eExportService,
RunEventsService,
],
exports: [ScenarioService, E2eExportService],
})
export class ScenarioModule {}
@@ -5,7 +5,7 @@ import {
OnModuleDestroy,
} from "@nestjs/common";
import type { Browser, BrowserContext, Page } from "playwright";
import { TraceLogger } from "../common/trace-logger";
import { createAppLogger } from "../common/app-logger";
import { SessionService } from "./session.service";
export interface SessionHandle {
@@ -21,7 +21,7 @@ export interface SessionHandle {
*/
@Injectable()
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>();
constructor(private readonly sessionService: SessionService) {}
@@ -1,7 +1,7 @@
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { Interval } from "@nestjs/schedule";
import { TraceLogger } from "../common/trace-logger";
import { createAppLogger } from "../common/app-logger";
import { AppConfig } from "../config/app.config";
import { SessionContextService } from "./session-context.service";
import { SessionService } from "./session.service";
@@ -13,7 +13,7 @@ import { SessionService } from "./session.service";
*/
@Injectable()
export class SessionSchedulerService {
private readonly logger = new TraceLogger(SessionSchedulerService.name);
private readonly logger = createAppLogger(SessionSchedulerService.name);
constructor(
private readonly sessionService: SessionService,
+7 -1
View File
@@ -8,7 +8,12 @@ import {
ParseUUIDPipe,
Query,
} 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 { SessionContextService } from "./session-context.service";
import { SessionService } from "./session.service";
@@ -19,6 +24,7 @@ function maskToken(token: string, head = 6, tail = 4): string {
}
@ApiTags("sessions")
@ApiBearerAuth()
@Controller("sessions")
export class SessionController {
constructor(
+2 -2
View File
@@ -6,7 +6,7 @@ import {
PaginatedResult,
PaginationQueryDto,
} from "../common/dto/pagination.dto";
import { TraceLogger } from "../common/trace-logger";
import { createAppLogger } from "../common/app-logger";
import { SessionEntity } from "./session.entity";
export type SessionOrderBy =
@@ -19,7 +19,7 @@ export type SessionOrderBy =
@Injectable()
export class SessionService implements OnApplicationBootstrap {
private readonly logger = new TraceLogger(SessionService.name);
private readonly logger = createAppLogger(SessionService.name);
constructor(
@InjectRepository(SessionEntity)
+7 -1
View File
@@ -11,7 +11,12 @@ import {
Post,
Query,
} 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 { CreateSnippetDto } from "./dto/create-snippet.dto";
import { SnippetExportDto } from "./dto/snippet-export.dto";
@@ -19,6 +24,7 @@ import { UpdateSnippetDto } from "./dto/update-snippet.dto";
import { SnippetService } from "./snippet.service";
@ApiTags("snippets")
@ApiBearerAuth()
@Controller("snippets")
export class SnippetController {
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 { LoggingInterceptor } from "../src/interceptors/logging.interceptor";
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
// some clean up their files dir, which must not affect other suites.
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
TypeOrmModule.forRoot({
...dataSourceOptions(":memory:"),
...dataSourceOptions(databasePath),
migrationsRun: true,
}),
ScheduleModule.forRoot(),
BrowserModule,
AuthModule,
SessionModule,
EnvironmentModule,
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);
});
});
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff. Show more