Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c0fe15dc01 | ||
|
|
8b48d4812d | ||
|
|
ff9a700c86 | ||
|
|
ea4f72c236 | ||
|
|
9ff9579a7b | ||
|
|
9bdba32a34 | ||
|
|
d4d9bceb98 | ||
|
|
768a799db0 | ||
|
|
fe19fb9d56 | ||
|
|
f2bcbe07b6 | ||
|
|
8676d6281c | ||
|
|
92141a25fb | ||
|
|
9e4b692444 | ||
|
|
2976a08aef | ||
|
|
c3e8670515 | ||
|
|
1830feb71b | ||
|
|
72e127888c | ||
|
|
de41571b5c | ||
|
|
d4bb274982 | ||
|
|
969f24ea73 | ||
|
|
81164f8494 | ||
|
|
14763103cf | ||
|
|
78f4c35d56 | ||
|
|
4b050fbdc4 | ||
|
|
a93b3ef835 | ||
|
|
d7eb018245 | ||
|
|
968a8e470b | ||
|
|
3c8def3814 | ||
|
|
6e5da08719 | ||
|
|
1abd95f9e1 | ||
|
|
d7476f0fe8 | ||
|
|
75bb0af9fd | ||
|
|
0c11e11c27 | ||
|
|
c1924060eb | ||
|
|
28dfce246a | ||
|
|
a0624789ce |
No files matched your search
@@ -8,6 +8,19 @@
|
|||||||
# NODE_ENV=development
|
# NODE_ENV=development
|
||||||
# PORT=3000
|
# PORT=3000
|
||||||
|
|
||||||
|
## Application log output: console (default) or debug (controlled by DEBUG namespaces)
|
||||||
|
# LOG_MODE=console
|
||||||
|
|
||||||
|
## Optional account authentication (disabled unless explicitly enabled)
|
||||||
|
# AUTH_ENABLED=true
|
||||||
|
## Required when AUTH_ENABLED=true. Set a private, high-entropy value outside source control.
|
||||||
|
# AUTH_JWT_SECRET=replace-with-a-private-random-secret
|
||||||
|
## Browser cookie name and default JWT lifetime
|
||||||
|
# AUTH_COOKIE_NAME=liqa_auth
|
||||||
|
# AUTH_JWT_EXPIRES_IN=24h
|
||||||
|
## Expired logout revocations are cleaned at startup and on this cron schedule.
|
||||||
|
# AUTH_REVOKED_TOKEN_CLEANUP_CRON=0 3 * * *
|
||||||
|
|
||||||
## Origins allowed to call the API cross-origin (comma separated). Default: the
|
## Origins allowed to call the API cross-origin (comma separated). Default: the
|
||||||
## Vite dev server (http://localhost:5173) in development, the compose port
|
## Vite dev server (http://localhost:5173) in development, the compose port
|
||||||
## (http://localhost:13000) in production
|
## (http://localhost:13000) in production
|
||||||
|
|||||||
+23
-41
@@ -1,9 +1,8 @@
|
|||||||
# Code quality checks on master and pull requests. The server and client jobs
|
# Code quality checks on master and pull requests. The server and client jobs
|
||||||
# only run when their directory (or shared root files) changed. On a push to
|
# only run when their directory (or shared root files) changed. On a release
|
||||||
# master, also builds the Docker image and pushes it to this Gitea instance's
|
# tag push (vX.Y.Z), runs both jobs unconditionally and then builds the Docker
|
||||||
# container registry, tagged with the root package.json version and `latest`
|
# image and pushes it to this Gitea instance's container registry, tagged with
|
||||||
# - unless that version's image already exists in the registry, in which case
|
# the version and `latest`. The tag must match the root package.json version.
|
||||||
# the push is skipped.
|
|
||||||
#
|
#
|
||||||
# Needs a repository (or owner) secret REGISTRY_TOKEN: a Gitea access token
|
# Needs a repository (or owner) secret REGISTRY_TOKEN: a Gitea access token
|
||||||
# with package write access for the repository owner. The registry host is
|
# with package write access for the repository owner. The registry host is
|
||||||
@@ -15,13 +14,16 @@ name: CI
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [master]
|
branches: [master]
|
||||||
|
tags: ['v[0-9]+.[0-9]+.[0-9]+']
|
||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
REGISTRY: git.hq.ars9.space
|
REGISTRY: git.hq.ars9.space
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
# Not needed on tag pushes: server and client always run there
|
||||||
changes:
|
changes:
|
||||||
|
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
outputs:
|
outputs:
|
||||||
server: ${{ steps.filter.outputs.server }}
|
server: ${{ steps.filter.outputs.server }}
|
||||||
@@ -45,7 +47,10 @@ jobs:
|
|||||||
|
|
||||||
server:
|
server:
|
||||||
needs: changes
|
needs: changes
|
||||||
if: needs.changes.outputs.server == 'true'
|
# changes is skipped on tag pushes, hence !cancelled()
|
||||||
|
if: |
|
||||||
|
!cancelled() &&
|
||||||
|
(startsWith(github.ref, 'refs/tags/') || needs.changes.outputs.server == 'true')
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
@@ -65,7 +70,10 @@ jobs:
|
|||||||
|
|
||||||
client:
|
client:
|
||||||
needs: changes
|
needs: changes
|
||||||
if: needs.changes.outputs.client == 'true'
|
# changes is skipped on tag pushes, hence !cancelled()
|
||||||
|
if: |
|
||||||
|
!cancelled() &&
|
||||||
|
(startsWith(github.ref, 'refs/tags/') || needs.changes.outputs.client == 'true')
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
@@ -83,46 +91,20 @@ jobs:
|
|||||||
- name: Storybook tests
|
- name: Storybook tests
|
||||||
run: npm run -w client test:storybook
|
run: npm run -w client test:storybook
|
||||||
|
|
||||||
# Skips the image job if the registry already has this version's image
|
image:
|
||||||
version:
|
needs: [server, client]
|
||||||
if: github.event_name == 'push'
|
if: ${{ !failure() && !cancelled() && startsWith(github.ref, 'refs/tags/') }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
outputs:
|
|
||||||
version: ${{ steps.check.outputs.version }}
|
|
||||||
changed: ${{ steps.check.outputs.changed }}
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- id: check
|
- name: Check the tag matches package.json
|
||||||
env:
|
|
||||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
OWNER: ${{ github.repository_owner }}
|
|
||||||
run: |
|
run: |
|
||||||
version=$(node -p "require('./package.json').version")
|
version=$(node -p "require('./package.json').version")
|
||||||
image="${REGISTRY}/$(echo "${GITHUB_REPOSITORY}" | tr '[:upper:]' '[:lower:]')"
|
if [ "${GITHUB_REF_NAME}" != "v${version}" ]; then
|
||||||
echo "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$OWNER" --password-stdin
|
echo "tag ${GITHUB_REF_NAME} does not match package.json version ${version}"
|
||||||
if docker manifest inspect "${image}:${version}" >/dev/null 2>&1; then
|
exit 1
|
||||||
echo "version ${version}: image already in registry, skipping"
|
|
||||||
echo "changed=false" >> "$GITHUB_OUTPUT"
|
|
||||||
else
|
|
||||||
echo "version ${version}: not in registry, building"
|
|
||||||
echo "changed=true" >> "$GITHUB_OUTPUT"
|
|
||||||
fi
|
fi
|
||||||
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
echo "VERSION=${version}" >> "$GITHUB_ENV"
|
||||||
|
|
||||||
image:
|
|
||||||
needs: [server, client, version]
|
|
||||||
# server/client may be skipped when their paths didn't change
|
|
||||||
if: |
|
|
||||||
!failure() && !cancelled() &&
|
|
||||||
github.event_name == 'push' &&
|
|
||||||
needs.version.outputs.changed == 'true' &&
|
|
||||||
(needs.server.result == 'success' || needs.server.result == 'skipped') &&
|
|
||||||
(needs.client.result == 'success' || needs.client.result == 'skipped')
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
env:
|
|
||||||
VERSION: ${{ needs.version.outputs.version }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
- name: Log in to the registry
|
- name: Log in to the registry
|
||||||
env:
|
env:
|
||||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|||||||
@@ -2,6 +2,55 @@
|
|||||||
|
|
||||||
All notable changes to this project will be documented in this file.
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
## 1.26.0 - 2026-10-08
|
||||||
|
|
||||||
|
Changes since 1.25.0:
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- e2e test export for a chosen scenario version: `GET /api/v1/scenarios/:id/export-e2e` and the `export_e2e_test` MCP tool take an optional `version` (defaults to the latest), and the test project is built from that version's steps, name and timeout. The Export e2e test button in the UI exports the version being viewed.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Exported e2e test archives include the version in their filename (`<scenario name>-v<N>-e2e-test.zip`), and the version also appears in the generated package name and README heading.
|
||||||
|
|
||||||
|
## 1.25.0 - 2026-10-07
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `examples/` directory with ready-to-import example resources. The first one, `examples/self-test`, is a scenario that tests the liqa instance it runs on: it creates a temporary scenario through the REST API, runs it, checks the run and its page in the UI, and cleans up. It uses an environment, a credential, snippets and assertions.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- CI builds and pushes the Docker image only when a `vX.Y.Z` release tag is pushed, not on every merge to `master`.
|
||||||
|
|
||||||
## 1.24.2 - 2026-10-02
|
## 1.24.2 - 2026-10-02
|
||||||
|
|
||||||
Changes since 1.24.1:
|
Changes since 1.24.1:
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ It is an npm workspace with two packages:
|
|||||||
- [docs/development.md](docs/development.md) - local setup, running, testing, Docker
|
- [docs/development.md](docs/development.md) - local setup, running, testing, Docker
|
||||||
- [docs/scenario.md](docs/scenario.md) - scenario execution, script `context` API, versioning, export/import, Playwright traces
|
- [docs/scenario.md](docs/scenario.md) - scenario execution, script `context` API, versioning, export/import, Playwright traces
|
||||||
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
||||||
|
- [examples/](examples/README.md) - ready-to-import example resources (YAML); `server/test/examples.spec.ts` imports each file, so keep them in sync with the import format
|
||||||
- [CHANGELOG.md](CHANGELOG.md) - release notes per version
|
- [CHANGELOG.md](CHANGELOG.md) - release notes per version
|
||||||
- [Dockerfile](Dockerfile) - single image: builds client and server, runtime serves both
|
- [Dockerfile](Dockerfile) - single image: builds client and server, runtime serves both
|
||||||
- [.env.example](.env.example) - all configuration variables (validated in `server/src/config/app.config.ts`)
|
- [.env.example](.env.example) - all configuration variables (validated in `server/src/config/app.config.ts`)
|
||||||
@@ -28,7 +29,11 @@ The live database is `data/liqa.db`. The container applies pending migrations be
|
|||||||
|
|
||||||
## Branching
|
## Branching
|
||||||
|
|
||||||
Never commit directly to `master` when implementing a feature, chore or bug fix: create a separate branch for the work first. Only version-bump release commits (see "Committing a new version") are made on `master`.
|
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
|
## Code quality
|
||||||
|
|
||||||
@@ -47,17 +52,18 @@ cd client && npm run lint && npm run build && npm run test:storybook
|
|||||||
- Server tests use an in-memory DB, a Playwright mock (`server/test/__mocks__/playwright.ts`), and a temporary files directory per test app (see `server/test/app.harness.ts`).
|
- Server tests use an in-memory DB, a Playwright mock (`server/test/__mocks__/playwright.ts`), and a temporary files directory per test app (see `server/test/app.harness.ts`).
|
||||||
- Import Node.js built-in modules with the `node:` prefix (`node:fs`, `node:path`, `node:crypto`, ...).
|
- Import Node.js built-in modules with the `node:` prefix (`node:fs`, `node:path`, `node:crypto`, ...).
|
||||||
|
|
||||||
## Committing a new version
|
## Releasing a new version
|
||||||
|
|
||||||
When asked to commit:
|
A release is cut on `master` after one or more work branches have been merged (their pull request checks are already green). CI builds and pushes the Docker image only when a `vX.Y.Z` tag is pushed, not on merges.
|
||||||
|
|
||||||
1. **Ask which version to bump** - major, minor or patch - and propose a sensible default based on the changes: patch for fixes and small behavior/default tweaks, minor for new features, major for breaking changes (e.g. changed API or export/import formats that old clients or files can't use).
|
When asked to release:
|
||||||
2. Run the code quality checks above.
|
|
||||||
|
1. Make sure you're on an up-to-date, clean `master` (`git switch master && git pull`), and collect the changes since the last release: `git log --oneline "$(git describe --tags --abbrev=0)"..HEAD`.
|
||||||
|
2. **Ask which version to bump** - major, minor or patch - and propose a sensible default based on those changes: patch for fixes and small behavior/default tweaks, minor for new features, major for breaking changes (e.g. changed API or export/import formats that old clients or files can't use).
|
||||||
3. Bump `version` in the root `package.json` and in both places at the top of `package-lock.json` (the root entry and `packages[""]`). `server/package.json` and `client/package.json` keep their own versions; don't bump them.
|
3. Bump `version` in the root `package.json` and in both places at the top of `package-lock.json` (the root entry and `packages[""]`). `server/package.json` and `client/package.json` keep their own versions; don't bump them.
|
||||||
4. Add a `## <version> - <YYYY-MM-DD>` entry at the top of `CHANGELOG.md` ("Changes since <previous version>:", then `### Added` / `### Changed` / `### Fixed`). Mark breaking changes with **Breaking:**.
|
4. Add a `## <version> - <YYYY-MM-DD>` entry at the top of `CHANGELOG.md` ("Changes since <previous version>:", then `### Added` / `### Changed` / `### Fixed`). Mark breaking changes with **Breaking:**.
|
||||||
5. Update the docs affected by the change (`docs/*.md`, `README.md`, `.env.example`, MCP tool descriptions).
|
5. Commit only these release changes on `master`. Build the commit message with the `/git-commit` skill if it is available, following its format and rules. Otherwise use a conventional commit message (`type(scope): subject`, then a bullet list body). Either way, put the version bump in the body as a bullet (e.g. `- bump version to <version>`), not in the subject line. This overrides the skill's rule of putting versions in the subject.
|
||||||
6. Build the commit message with the `/git-commit` skill if it is available, following its format and rules. Otherwise use a conventional commit message (`type(scope): subject`, then a bullet list body). Either way, put the version bump in the body as a bullet (e.g. `- bump version to <version>`), not in the subject line. This overrides the skill's rule of putting versions in the subject. Then make the commit with that message.
|
6. **Tag the release commit** with an annotated tag `v<version>` whose message is that version's `CHANGELOG.md` entry, verbatim (from its `## <version>` heading up to the next version's heading). `--cleanup=whitespace` is required: the default cleanup strips lines starting with `#`, which would drop the entry's headings:
|
||||||
7. **Tag the version commit** with an annotated tag `v<version>` whose message is that version's `CHANGELOG.md` entry, verbatim (from its `## <version>` heading up to the next version's heading). Commits without a version bump get no tag. `--cleanup=whitespace` is required: the default cleanup strips lines starting with `#`, which would drop the entry's headings:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
v=<version>
|
v=<version>
|
||||||
@@ -65,5 +71,5 @@ When asked to commit:
|
|||||||
| git tag -a "v$v" --cleanup=whitespace -F -
|
| git tag -a "v$v" --cleanup=whitespace -F -
|
||||||
```
|
```
|
||||||
|
|
||||||
Don't push the tag; tell the user to push with `git push --follow-tags`, which also pushes annotated tags.
|
7. **Ask the user before pushing**, then push the commit and the tag together with `git push --follow-tags` (it also pushes annotated tags). The tag push triggers the image build; it fails if the tag doesn't match the `package.json` version.
|
||||||
8. **After committing, ask the user whether to rebuild and restart the docker compose containers** (`docker compose up -d --build`); don't do it without confirmation.
|
8. **Ask the user whether to rebuild and restart the docker compose containers** (`docker compose up -d --build`); don't do it without confirmation.
|
||||||
@@ -12,8 +12,12 @@ docker compose up -d --build
|
|||||||
|
|
||||||
No configuration is needed: every setting has a default. To override one, copy `.env.example` to `.env` and uncomment it.
|
No configuration is needed: every setting has a default. To override one, copy `.env.example` to `.env` and uncomment it.
|
||||||
|
|
||||||
|
Authentication is **disabled by default**. To enable operator-managed accounts, set `AUTH_ENABLED=true` and provide a private `AUTH_JWT_SECRET`; then rebuild/restart the service and provision an account with the CLI. See [operator authentication](docs/development.md#operator-account-commands) for setup and browser/API usage. Existing deployments remain unauthenticated until explicitly enabled.
|
||||||
|
|
||||||
Everything is served from one container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. Data is kept in `./data/`.
|
Everything is served from one container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. Data is kept in `./data/`.
|
||||||
|
|
||||||
|
To see it work, import and run the [self-test example](examples/self-test/): a scenario that tests liqa itself using an environment, a credential and snippets.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
@@ -49,6 +53,7 @@ Scenarios, snippets, environments and credentials can be exported as YAML and im
|
|||||||
- [docs/scenario.md](docs/scenario.md) - runs, the script `context` API, versioning, import/export, Playwright traces
|
- [docs/scenario.md](docs/scenario.md) - runs, the script `context` API, versioning, import/export, Playwright traces
|
||||||
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
- [docs/mcp.md](docs/mcp.md) - MCP tool reference
|
||||||
- [docs/development.md](docs/development.md) - setup, configuration, running, testing, linting, Docker
|
- [docs/development.md](docs/development.md) - setup, configuration, running, testing, linting, Docker
|
||||||
|
- [examples/](examples/) - ready-to-import example scenarios
|
||||||
- [CHANGELOG.md](CHANGELOG.md) - release notes
|
- [CHANGELOG.md](CHANGELOG.md) - release notes
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -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);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -36,11 +36,19 @@
|
|||||||
min-height: 100%;
|
min-height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.footerButtons {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-1);
|
||||||
|
}
|
||||||
|
|
||||||
.sideFooter {
|
.sideFooter {
|
||||||
margin-top: auto;
|
margin-top: auto;
|
||||||
padding: var(--space-3) var(--space-2) var(--space-2);
|
padding: var(--space-3) var(--space-2) var(--space-2);
|
||||||
border-top: var(--border-width) solid var(--color-border);
|
border-top: var(--border-width) solid var(--color-border);
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: var(--space-2);
|
gap: var(--space-2);
|
||||||
@@ -62,6 +70,68 @@
|
|||||||
text-decoration: underline;
|
text-decoration: underline;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.signOut,
|
||||||
|
.expandForSignOut {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 44px;
|
||||||
|
height: 44px;
|
||||||
|
padding: 0;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
background: transparent;
|
||||||
|
border: var(--border-width) solid var(--color-border);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signOut:hover,
|
||||||
|
.expandForSignOut:hover {
|
||||||
|
color: var(--color-text);
|
||||||
|
background: var(--color-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.signOut:focus-visible,
|
||||||
|
.expandForSignOut:focus-visible,
|
||||||
|
.logoutFailure button:focus-visible {
|
||||||
|
outline: 2px solid var(--color-primary-text);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.signOut:disabled {
|
||||||
|
opacity: 0.55;
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logoutFailure {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
padding: var(--space-2);
|
||||||
|
color: var(--color-error-fg);
|
||||||
|
background: var(--color-error-bg);
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
font-size: var(--font-size-xs);
|
||||||
|
}
|
||||||
|
|
||||||
|
.logoutFailure button {
|
||||||
|
min-height: 32px;
|
||||||
|
color: inherit;
|
||||||
|
background: transparent;
|
||||||
|
border: var(--border-width) solid currentColor;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.expandForSignOut {
|
||||||
|
position: fixed;
|
||||||
|
left: 8px;
|
||||||
|
bottom: 12px;
|
||||||
|
z-index: 20;
|
||||||
|
background: var(--color-bg-subtle);
|
||||||
|
box-shadow: var(--shadow-sm);
|
||||||
|
}
|
||||||
|
|
||||||
.navItem {
|
.navItem {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|||||||
+86
-4
@@ -1,12 +1,19 @@
|
|||||||
import { lazy, Suspense } from 'react';
|
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
|
||||||
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
|
import { LogOut } from 'lucide-react';
|
||||||
|
import { NavLink, Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react';
|
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react';
|
||||||
import type { LucideIcon } from 'lucide-react';
|
import type { LucideIcon } from 'lucide-react';
|
||||||
import styles from './App.module.css';
|
import styles from './App.module.css';
|
||||||
import { SidePanel, ThemeSwitcher } from './ui';
|
import { NotificationToggle, SidePanel, ThemeSwitcher } from './ui';
|
||||||
import liqaLogo from './assets/liqa.svg';
|
import liqaLogo from './assets/liqa.svg';
|
||||||
import { useManifest } from './hooks/useManifest';
|
import { useManifest } from './hooks/useManifest';
|
||||||
|
import { useRunNotifications } from './hooks/useRunNotifications';
|
||||||
|
import { useAuth } from './auth/useAuth';
|
||||||
|
import { safeReturnTo } from './auth/returnTo';
|
||||||
|
import { AuthStatusPage } from './pages/auth/AuthStatusPage';
|
||||||
|
import { LoginPage } from './pages/auth/LoginPage';
|
||||||
|
import { SignOutControl } from './pages/auth/SignOutControl';
|
||||||
|
|
||||||
const EnvironmentsPage = lazy(() =>
|
const EnvironmentsPage = lazy(() =>
|
||||||
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
|
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
|
||||||
@@ -108,11 +115,59 @@ const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator:
|
|||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const auth = useAuth();
|
||||||
|
const location = useLocation();
|
||||||
|
const [search] = useSearchParams();
|
||||||
|
const [collapsed, setCollapsed] = useState(false);
|
||||||
|
const [loggingOut, setLoggingOut] = useState(false);
|
||||||
|
const [logoutFailed, setLogoutFailed] = useState(false);
|
||||||
|
const focusSignOut = useRef(false);
|
||||||
const { version } = useManifest();
|
const { version } = useManifest();
|
||||||
|
const notifications = useRunNotifications();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!collapsed && focusSignOut.current) {
|
||||||
|
focusSignOut.current = false;
|
||||||
|
document.querySelector<HTMLButtonElement>('[data-sign-out="true"]')?.focus();
|
||||||
|
}
|
||||||
|
}, [collapsed]);
|
||||||
|
|
||||||
|
async function signOut() {
|
||||||
|
if (loggingOut) return;
|
||||||
|
setLoggingOut(true);
|
||||||
|
setLogoutFailed(false);
|
||||||
|
try {
|
||||||
|
await auth.logout();
|
||||||
|
} catch {
|
||||||
|
setLogoutFailed(true);
|
||||||
|
} finally {
|
||||||
|
setLoggingOut(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onLogin = location.pathname === '/login';
|
||||||
|
if (auth.enabled && (auth.status === 'checking' || auth.status === 'disabled')) {
|
||||||
|
return <AuthStatusPage />;
|
||||||
|
}
|
||||||
|
if (auth.enabled && auth.status === 'error') {
|
||||||
|
return <AuthStatusPage failed onRetry={() => void auth.checkSession()} />;
|
||||||
|
}
|
||||||
|
if (!auth.enabled && onLogin) return <Navigate to="/scenarios" replace />;
|
||||||
|
if (auth.enabled && auth.status === 'authenticated' && onLogin) {
|
||||||
|
return <Navigate to={safeReturnTo(search.get('returnTo')) ?? '/scenarios'} replace />;
|
||||||
|
}
|
||||||
|
if (auth.enabled && auth.status === 'unauthenticated' && !onLogin) {
|
||||||
|
const returnTo =
|
||||||
|
safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios';
|
||||||
|
return <Navigate to={`/login?returnTo=${encodeURIComponent(returnTo)}`} replace />;
|
||||||
|
}
|
||||||
|
if (onLogin) return <LoginPage />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.shell}>
|
<div className={styles.shell}>
|
||||||
<SidePanel
|
<SidePanel
|
||||||
|
collapsed={collapsed}
|
||||||
|
onCollapsedChange={setCollapsed}
|
||||||
header={
|
header={
|
||||||
<div className={styles.header}>
|
<div className={styles.header}>
|
||||||
<img src={liqaLogo} alt="Liqa" className={styles.brand} />
|
<img src={liqaLogo} alt="Liqa" className={styles.brand} />
|
||||||
@@ -141,7 +196,19 @@ export default function App() {
|
|||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<div className={styles.sideFooter}>
|
<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}>
|
<div className={styles.version}>
|
||||||
<span
|
<span
|
||||||
title={
|
title={
|
||||||
@@ -166,6 +233,21 @@ export default function App() {
|
|||||||
</div>
|
</div>
|
||||||
</SidePanel>
|
</SidePanel>
|
||||||
|
|
||||||
|
{collapsed && auth.enabled && auth.status === 'authenticated' && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={styles.expandForSignOut}
|
||||||
|
aria-label={t('auth.show_sign_out')}
|
||||||
|
title={t('auth.show_sign_out')}
|
||||||
|
onClick={() => {
|
||||||
|
focusSignOut.current = true;
|
||||||
|
setCollapsed(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LogOut size={18} aria-hidden="true" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
<main className={styles.main}>
|
<main className={styles.main}>
|
||||||
<Suspense fallback={<p>Loading…</p>}>
|
<Suspense fallback={<p>Loading…</p>}>
|
||||||
<Routes>
|
<Routes>
|
||||||
|
|||||||
@@ -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;
|
let res: Response;
|
||||||
try {
|
try {
|
||||||
const headers = new Headers(init?.headers);
|
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}`, {
|
res = await fetch(`${BASE_URL}${path}`, {
|
||||||
...init,
|
...init,
|
||||||
|
credentials: init?.credentials ?? 'include',
|
||||||
headers,
|
headers,
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = (err as Error).message || 'Network request failed';
|
const message = (err as Error).message || 'Network request failed';
|
||||||
emitApiErrorToast(message);
|
if (!options.quietErrors) emitApiErrorToast(message);
|
||||||
throw new Error(message);
|
throw new Error(message);
|
||||||
}
|
}
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const text = await res.text().catch(() => res.statusText);
|
const text = await res.text().catch(() => res.statusText);
|
||||||
const message = `${res.status} ${text}`;
|
const message = `${res.status} ${text}`;
|
||||||
emitApiErrorToast(message);
|
const error = new ApiError(res.status, message);
|
||||||
throw new Error(message);
|
if (res.status === 401 && !path.startsWith('/auth/')) {
|
||||||
|
const event = new CustomEvent('liqa:unauthorized', { cancelable: true });
|
||||||
|
const handled = !window.dispatchEvent(event);
|
||||||
|
if (!handled && !options.quietErrors) emitApiErrorToast(message);
|
||||||
|
} else if (!options.quietErrors && !path.startsWith('/auth/')) {
|
||||||
|
emitApiErrorToast(message);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
const contentLength = res.headers.get('content-length');
|
const contentLength = res.headers.get('content-length');
|
||||||
if (res.status === 204 || contentLength === '0') return undefined as T;
|
if (res.status === 204 || contentLength === '0') return undefined as T;
|
||||||
@@ -62,6 +91,30 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|||||||
return text as T;
|
return text as T;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AuthUser {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const auth = {
|
||||||
|
async login(username: string, password: string): Promise<AuthUser> {
|
||||||
|
const response = await request<{ user: AuthUser }>(
|
||||||
|
'/auth/login',
|
||||||
|
{ method: 'POST', body: JSON.stringify({ username, password }) },
|
||||||
|
{ quietErrors: true },
|
||||||
|
);
|
||||||
|
return response.user;
|
||||||
|
},
|
||||||
|
me(): Promise<AuthUser> {
|
||||||
|
return request('/auth/me', undefined, { quietErrors: true });
|
||||||
|
},
|
||||||
|
logout(): Promise<void> {
|
||||||
|
return request('/auth/logout', { method: 'POST' }, { quietErrors: true });
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
// ── Credentials ───────────────────────────────────────────────────────────────
|
// ── Credentials ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export const credentials = {
|
export const credentials = {
|
||||||
@@ -123,8 +176,9 @@ export const snippets = {
|
|||||||
versions(id: string): Promise<SnippetVersion[]> {
|
versions(id: string): Promise<SnippetVersion[]> {
|
||||||
return request(`/snippets/${id}/versions`);
|
return request(`/snippets/${id}/versions`);
|
||||||
},
|
},
|
||||||
exportSnippet(id: string): Promise<unknown> {
|
exportSnippet(id: string, version?: number): Promise<unknown> {
|
||||||
return request(`/snippets/${id}/export`);
|
const query = version === undefined ? '' : `?version=${version}`;
|
||||||
|
return request(`/snippets/${id}/export${query}`);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -247,7 +301,12 @@ export const scenarios = {
|
|||||||
},
|
},
|
||||||
exportScenario(
|
exportScenario(
|
||||||
id: string,
|
id: string,
|
||||||
options: { includeEnvironment: boolean; credentialIds: string[]; snippetIds: string[] } = {
|
options: {
|
||||||
|
includeEnvironment: boolean;
|
||||||
|
credentialIds: string[];
|
||||||
|
snippetIds: string[];
|
||||||
|
version?: number;
|
||||||
|
} = {
|
||||||
includeEnvironment: false,
|
includeEnvironment: false,
|
||||||
credentialIds: [],
|
credentialIds: [],
|
||||||
snippetIds: [],
|
snippetIds: [],
|
||||||
@@ -255,6 +314,9 @@ export const scenarios = {
|
|||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
params.set('includeEnvironment', String(options.includeEnvironment));
|
params.set('includeEnvironment', String(options.includeEnvironment));
|
||||||
|
if (options.version !== undefined) {
|
||||||
|
params.set('version', String(options.version));
|
||||||
|
}
|
||||||
for (const cid of options.credentialIds) {
|
for (const cid of options.credentialIds) {
|
||||||
params.append('credentialIds', cid);
|
params.append('credentialIds', cid);
|
||||||
}
|
}
|
||||||
@@ -263,8 +325,9 @@ export const scenarios = {
|
|||||||
}
|
}
|
||||||
return request(`/scenarios/${id}/export?${params.toString()}`);
|
return request(`/scenarios/${id}/export?${params.toString()}`);
|
||||||
},
|
},
|
||||||
exportE2eTestUrl(id: string): string {
|
exportE2eTestUrl(id: string, version?: number): string {
|
||||||
return `${BASE_URL}/scenarios/${id}/export-e2e`;
|
const query = version === undefined ? '' : `?version=${version}`;
|
||||||
|
return `${BASE_URL}/scenarios/${id}/export-e2e${query}`;
|
||||||
},
|
},
|
||||||
usedSnippets(id: string): Promise<UsedSnippet[]> {
|
usedSnippets(id: string): Promise<UsedSnippet[]> {
|
||||||
return request(`/scenarios/${id}/used-snippets`);
|
return request(`/scenarios/${id}/used-snippets`);
|
||||||
|
|||||||
@@ -234,3 +234,13 @@ export interface ImportedItem {
|
|||||||
export interface ImportResult {
|
export interface ImportResult {
|
||||||
imported: ImportedItem[];
|
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;
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
@@ -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()}`;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,4 +1,24 @@
|
|||||||
{
|
{
|
||||||
|
"auth": {
|
||||||
|
"page_title": "Sign in",
|
||||||
|
"sign_in": "Sign in",
|
||||||
|
"signing_in": "Signing in…",
|
||||||
|
"username": "Username",
|
||||||
|
"password": "Password",
|
||||||
|
"username_required": "Enter your username.",
|
||||||
|
"password_required": "Enter your password.",
|
||||||
|
"invalid_credentials": "Username or password is incorrect.",
|
||||||
|
"sign_in_failed": "Couldn't sign in. Check your connection and try again.",
|
||||||
|
"checking_session": "Checking your session…",
|
||||||
|
"session_check_failed": "Couldn't check your session. Try again.",
|
||||||
|
"retry": "Retry",
|
||||||
|
"session_expired": "Your session has expired. Sign in again to continue.",
|
||||||
|
"sign_out": "Sign out",
|
||||||
|
"signing_out": "Signing out…",
|
||||||
|
"signed_out": "You have signed out.",
|
||||||
|
"sign_out_failed": "Couldn't sign out. Try again.",
|
||||||
|
"show_sign_out": "Expand the menu to sign out"
|
||||||
|
},
|
||||||
"common": {
|
"common": {
|
||||||
"button_cancel": "Cancel",
|
"button_cancel": "Cancel",
|
||||||
"button_confirm": "Confirm",
|
"button_confirm": "Confirm",
|
||||||
@@ -235,6 +255,17 @@
|
|||||||
"light_mode": "Light mode",
|
"light_mode": "Light mode",
|
||||||
"dark_mode": "Dark 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": {
|
"revealable": {
|
||||||
"hidden": "Hidden so secrets aren't exposed on screen.",
|
"hidden": "Hidden so secrets aren't exposed on screen.",
|
||||||
"reveal": "Reveal",
|
"reveal": "Reveal",
|
||||||
|
|||||||
@@ -8,12 +8,16 @@ export interface Manifest {
|
|||||||
runLogs: {
|
runLogs: {
|
||||||
dataLimits: LogDataLimits;
|
dataLimits: LogDataLimits;
|
||||||
};
|
};
|
||||||
|
auth: {
|
||||||
|
enabled: boolean;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const DEFAULT_MANIFEST: Manifest = {
|
export const DEFAULT_MANIFEST: Manifest = {
|
||||||
name: 'liqa',
|
name: 'liqa',
|
||||||
version: __APP_VERSION__,
|
version: __APP_VERSION__,
|
||||||
runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS },
|
runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS },
|
||||||
|
auth: { enabled: false },
|
||||||
};
|
};
|
||||||
|
|
||||||
const STORAGE_KEY = 'liqa-manifest';
|
const STORAGE_KEY = 'liqa-manifest';
|
||||||
@@ -39,6 +43,7 @@ function normalize(raw: unknown): Manifest | null {
|
|||||||
return {
|
return {
|
||||||
name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name,
|
name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name,
|
||||||
version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version,
|
version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version,
|
||||||
|
auth: { enabled: m.auth?.enabled === true },
|
||||||
runLogs: {
|
runLogs: {
|
||||||
dataLimits: {
|
dataLimits: {
|
||||||
bytes: num(limits.bytes, DEFAULT_LOG_DATA_LIMITS.bytes),
|
bytes: num(limits.bytes, DEFAULT_LOG_DATA_LIMITS.bytes),
|
||||||
@@ -77,7 +82,10 @@ const listeners = new Set<() => void>();
|
|||||||
* silent: the cached (or default) manifest stays in use.
|
* silent: the cached (or default) manifest stays in use.
|
||||||
*/
|
*/
|
||||||
export function refreshManifest(): Promise<void> {
|
export function refreshManifest(): Promise<void> {
|
||||||
inFlight ??= fetch(MANIFEST_URL, { headers: { Accept: 'application/json' } })
|
inFlight ??= fetch(MANIFEST_URL, {
|
||||||
|
headers: { Accept: 'application/json' },
|
||||||
|
credentials: 'include',
|
||||||
|
})
|
||||||
.then((res) => (res.ok ? res.json() : null))
|
.then((res) => (res.ok ? res.json() : null))
|
||||||
.then((raw: unknown) => {
|
.then((raw: unknown) => {
|
||||||
const next = normalize(raw);
|
const next = normalize(raw);
|
||||||
|
|||||||
+13
-2
@@ -6,15 +6,26 @@ import './i18n';
|
|||||||
import './ui/tokens.css';
|
import './ui/tokens.css';
|
||||||
import App from './App';
|
import App from './App';
|
||||||
import { ToastProvider } from './ui';
|
import { ToastProvider } from './ui';
|
||||||
|
import { AuthProvider } from './auth/AuthContext';
|
||||||
|
import { ApiError } from './api/client';
|
||||||
|
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient({
|
||||||
|
defaultOptions: {
|
||||||
|
queries: {
|
||||||
|
retry: (failureCount, error) =>
|
||||||
|
error instanceof ApiError && error.status === 401 ? false : failureCount < 3,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
createRoot(document.getElementById('root')!).render(
|
createRoot(document.getElementById('root')!).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
<ToastProvider>
|
<ToastProvider>
|
||||||
<BrowserRouter>
|
<BrowserRouter>
|
||||||
<App />
|
<AuthProvider>
|
||||||
|
<App />
|
||||||
|
</AuthProvider>
|
||||||
</BrowserRouter>
|
</BrowserRouter>
|
||||||
</ToastProvider>
|
</ToastProvider>
|
||||||
</QueryClientProvider>
|
</QueryClientProvider>
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
.page {
|
||||||
|
min-height: 100vh;
|
||||||
|
padding: 24px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
color: var(--color-text);
|
||||||
|
background: var(--color-bg);
|
||||||
|
font-family: var(--font-family);
|
||||||
|
}
|
||||||
|
|
||||||
|
.header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
display: block;
|
||||||
|
width: auto;
|
||||||
|
height: 32px;
|
||||||
|
padding: 3px 6px;
|
||||||
|
background: #e6edea;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.main {
|
||||||
|
flex: 1;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
padding: var(--space-6) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message {
|
||||||
|
width: min(100%, 440px);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: var(--space-4);
|
||||||
|
margin: 0;
|
||||||
|
padding: var(--space-6);
|
||||||
|
text-align: center;
|
||||||
|
background: var(--color-bg);
|
||||||
|
border: var(--border-width) solid var(--color-border);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
box-shadow: var(--shadow-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.message p {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--color-error-fg);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.page {
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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,
|
includeEnvironment,
|
||||||
credentialIds: credIds,
|
credentialIds: credIds,
|
||||||
snippetIds: Array.from(includedSnippetIds),
|
snippetIds: Array.from(includedSnippetIds),
|
||||||
|
version: scenario.version,
|
||||||
});
|
});
|
||||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = url;
|
a.href = url;
|
||||||
a.download = `${scenario.name}.yaml`;
|
a.download = `${scenario.name}-v${scenario.version}.yaml`;
|
||||||
a.click();
|
a.click();
|
||||||
URL.revokeObjectURL(url);
|
URL.revokeObjectURL(url);
|
||||||
setExportModalOpen(false);
|
setExportModalOpen(false);
|
||||||
@@ -503,7 +504,10 @@ export function ScenarioDetailPage() {
|
|||||||
variant="secondary"
|
variant="secondary"
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() =>
|
onClick={() =>
|
||||||
handleFileDownload(scenarios.exportE2eTestUrl(id!), `${scenario.name}-e2e-test.zip`)
|
handleFileDownload(
|
||||||
|
scenarios.exportE2eTestUrl(id!, scenario.version),
|
||||||
|
`${scenario.name}-v${scenario.version}-e2e-test.zip`,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<FileArchive size={14} />
|
<FileArchive size={14} />
|
||||||
|
|||||||
@@ -51,12 +51,12 @@ export function SnippetDetailPage() {
|
|||||||
|
|
||||||
const handleExport = async () => {
|
const handleExport = async () => {
|
||||||
if (!snippet) return;
|
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 blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
|
||||||
const url = URL.createObjectURL(blob);
|
const url = URL.createObjectURL(blob);
|
||||||
const a = document.createElement('a');
|
const a = document.createElement('a');
|
||||||
a.href = url;
|
a.href = url;
|
||||||
a.download = `snippet-${snippet.alias}.yaml`;
|
a.download = `snippet-${snippet.alias}-v${snippet.version}.yaml`;
|
||||||
a.click();
|
a.click();
|
||||||
URL.revokeObjectURL(url);
|
URL.revokeObjectURL(url);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -88,3 +88,9 @@
|
|||||||
@keyframes spin {
|
@keyframes spin {
|
||||||
to { transform: rotate(360deg); }
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -38,7 +38,7 @@ export function SidePanel({
|
|||||||
style={{ '--side-panel-width': `${width}px` } as React.CSSProperties}
|
style={{ '--side-panel-width': `${width}px` } as React.CSSProperties}
|
||||||
aria-expanded={!collapsed}
|
aria-expanded={!collapsed}
|
||||||
>
|
>
|
||||||
<div className={styles.inner}>
|
<div className={styles.inner} aria-hidden={collapsed} inert={collapsed}>
|
||||||
{header && <div className={styles.header}>{header}</div>}
|
{header && <div className={styles.header}>{header}</div>}
|
||||||
<div className={styles.content}>{children}</div>
|
<div className={styles.content}>{children}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ export { Breadcrumbs } from './Breadcrumbs/Breadcrumbs';
|
|||||||
export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs';
|
export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs';
|
||||||
|
|
||||||
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
|
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
|
||||||
|
export { NotificationToggle } from './NotificationToggle/NotificationToggle';
|
||||||
|
export type { NotificationToggleState } from './NotificationToggle/NotificationToggle';
|
||||||
|
|
||||||
export { ToastProvider } from './Toast/ToastProvider';
|
export { ToastProvider } from './Toast/ToastProvider';
|
||||||
export type { ToastProviderProps } from './Toast/ToastProvider';
|
export type { ToastProviderProps } from './Toast/ToastProvider';
|
||||||
|
|||||||
@@ -35,6 +35,12 @@
|
|||||||
|
|
||||||
Everything runs in one container built from the root `Dockerfile`: the server serves the API, MCP and Swagger, and also the built client. See [development.md](development.md) for running it.
|
Everything runs in one container built from the root `Dockerfile`: the server serves the API, MCP and Swagger, and also the built client. See [development.md](development.md) for running it.
|
||||||
|
|
||||||
|
## Optional authentication boundary
|
||||||
|
|
||||||
|
Account authentication is off unless `AUTH_ENABLED=true`. When enabled, the global guard protects REST and MCP controller routes and the run-events stream. The public routes are `GET /health`, `GET /healthz`, `GET /manifest.json` and `POST /api/v1/auth/login`; the manifest reports the auth-enabled flag so the client can choose its login flow. UI assets and the Swagger UI remain reachable, but API operations require authentication. Protected requests accept a bearer token or the `AUTH_COOKIE_NAME` cookie (`liqa_auth` by default). Browser login sets an HttpOnly, SameSite=Strict cookie and logout revokes the presented token and expires the cookie; HTTPS requests also get the Secure attribute. See [development.md](development.md#enabling-authentication) for operator setup and lifecycle details.
|
||||||
|
|
||||||
|
The authentication service stores users and hashed revoked-token identifiers in SQLite. Revocation records are retained through token expiry, then removed at startup and by the `AUTH_REVOKED_TOKEN_CLEANUP_CRON` job (`0 3 * * *` by default); no cleanup job is registered while auth is disabled. Authentication checks that the token is not revoked and that its account still exists, so deleting an account invalidates its outstanding tokens at the next request.
|
||||||
|
|
||||||
## Server components (`server/src/`)
|
## Server components (`server/src/`)
|
||||||
|
|
||||||
- **McpService** (`mcp/`) registers the MCP tools and delegates to the services below. Each request gets a fresh MCP server over the Streamable HTTP transport.
|
- **McpService** (`mcp/`) registers the MCP tools and delegates to the services below. Each request gets a fresh MCP server over the Streamable HTTP transport.
|
||||||
@@ -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.
|
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.
|
`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.
|
See [development.md](development.md) for the full client tech stack and directory layout.
|
||||||
+61
-8
@@ -30,6 +30,7 @@ All settings are validated at startup by `server/src/config/app.config.ts`.
|
|||||||
| `NODE_ENV` | `development` | `production` in the Docker image. Shown in the startup log, and selects the default CORS origins |
|
| `NODE_ENV` | `development` | `production` in the Docker image. Shown in the startup log, and selects the default CORS origins |
|
||||||
| `CORS_ORIGINS` | *(empty)* | Comma-separated origins allowed to call the API cross-origin. When empty: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) unless `NODE_ENV=production`, then the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) |
|
| `CORS_ORIGINS` | *(empty)* | Comma-separated origins allowed to call the API cross-origin. When empty: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) unless `NODE_ENV=production`, then the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) |
|
||||||
| `PORT` | `3000` | HTTP port |
|
| `PORT` | `3000` | HTTP port |
|
||||||
|
| `LOG_MODE` | `console` | `console` preserves the default server output; `debug` routes application diagnostics through the `debug` package and only emits namespaces enabled by `DEBUG` (for example, `DEBUG=liqa:*`). |
|
||||||
| `DB_PATH` | `data/liqa.db` | SQLite database file |
|
| `DB_PATH` | `data/liqa.db` | SQLite database file |
|
||||||
| `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored |
|
| `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored |
|
||||||
| `FILE_RUN_EXPIRATION_DAYS` | `7` | How long run artifacts (downloads, failure dumps, traces) are kept |
|
| `FILE_RUN_EXPIRATION_DAYS` | `7` | How long run artifacts (downloads, failure dumps, traces) are kept |
|
||||||
@@ -41,6 +42,11 @@ All settings are validated at startup by `server/src/config/app.config.ts`.
|
|||||||
| `RUN_LOG_DATA_COLLAPSE_LINES` | `5` | Same, for the number of lines |
|
| `RUN_LOG_DATA_COLLAPSE_LINES` | `5` | Same, for the number of lines |
|
||||||
| `CLIENT_DIR` | *(empty)* | Directory with the built client to serve at `/` (the Docker image sets it to `client`); empty means the server doesn't serve the UI |
|
| `CLIENT_DIR` | *(empty)* | Directory with the built client to serve at `/` (the Docker image sets it to `client`); empty means the server doesn't serve the UI |
|
||||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to a Chromium binary to use instead of Playwright's own. Not set in Docker: the image ships Playwright's `chromium-headless-shell` (matching the Playwright version) under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`. |
|
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to a Chromium binary to use instead of Playwright's own. Not set in Docker: the image ships Playwright's `chromium-headless-shell` (matching the Playwright version) under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`. |
|
||||||
|
| `AUTH_ENABLED` | `false` | Opt-in account authentication. With the default `false`, the existing UI, REST API and MCP remain available without accounts. |
|
||||||
|
| `AUTH_JWT_SECRET` | *(empty)* | Required and non-empty when `AUTH_ENABLED=true`. Keep it private and stable across restarts; changing it invalidates existing tokens. |
|
||||||
|
| `AUTH_COOKIE_NAME` | `liqa_auth` | Name of the browser's HttpOnly session cookie. |
|
||||||
|
| `AUTH_JWT_EXPIRES_IN` | `24h` | Default lifetime for browser sessions and CLI-issued tokens. Positive durations use `s`, `m`, `h` or `d`. |
|
||||||
|
| `AUTH_REVOKED_TOKEN_CLEANUP_CRON` | `0 3 * * *` | When expired logout revocations are cleaned. Cleanup also runs once at startup and is disabled when auth is off. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -103,6 +109,54 @@ The SQLite schema is managed by TypeORM migrations in `server/src/database/migra
|
|||||||
|
|
||||||
The scripts run from `server/`, so `DB_PATH` (default `data/liqa.db`) is relative to it, and they read `server/.env` if present, like the server does.
|
The scripts run from `server/`, so `DB_PATH` (default `data/liqa.db`) is relative to it, and they read `server/.env` if present, like the server does.
|
||||||
|
|
||||||
|
### Enabling authentication
|
||||||
|
|
||||||
|
Authentication is disabled by default, so a fresh install needs no auth settings. For Docker Compose, set these in the project `.env` (keep it out of version control):
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
AUTH_ENABLED=true
|
||||||
|
AUTH_JWT_SECRET=<private-random-secret>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use a long, randomly generated secret from your secret manager; do not use the placeholder literally or commit a real value. `AUTH_ENABLED` accepts only `true` or `false`. When enabled, startup fails if the signing secret is blank or the configured token lifetime/cleanup schedule is invalid. Rebuild/restart the container after changing its configuration. Compose applies pending migrations before starting the server. For local development, export the same variables in the server process environment (or put them in `server/.env`); run `npm -w server run build` and `npm -w server run migration:run` before account commands or server startup. Migrations add the user and revoked-token tables and are required even when authentication is disabled.
|
||||||
|
|
||||||
|
When auth is enabled, REST and MCP controller routes require a valid bearer token or browser cookie except `GET /health`, `GET /healthz`, `GET /manifest.json`, and `POST /api/v1/auth/login`. Login is public so a browser can establish its session. The manifest exposes whether auth is enabled; health endpoints return service status. The UI assets and Swagger UI at `/docs` remain reachable, while API operations invoked from Swagger require authentication. MCP at `/mcp` and the run-events stream are protected. When auth is disabled, the guard allows existing requests through.
|
||||||
|
|
||||||
|
## Operator account commands
|
||||||
|
|
||||||
|
Authentication is opt-in. To manage accounts or issue tokens, set `AUTH_ENABLED=true` and `AUTH_JWT_SECRET` in the same environment used by the server. Apply database migrations before using the commands. Passwords are entered interactively without terminal echo; they are never accepted as command-line arguments. The CLI uses the same `DB_PATH` as the server; locally it resolves the default `data/liqa.db` relative to `server/`, while inside the container it uses the configured path (normally `/app/data/liqa.db`, persisted by the `./data:/app/data` volume).
|
||||||
|
|
||||||
|
Build the server and apply migrations locally, then run commands from the server workspace:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm -w server run build
|
||||||
|
npm -w server run migration:run
|
||||||
|
npm -w server run cli -- user:create
|
||||||
|
npm -w server run cli -- user:get alice
|
||||||
|
npm -w server run cli -- user:token alice # uses AUTH_JWT_EXPIRES_IN (default 24h)
|
||||||
|
npm -w server run cli -- user:token alice 30m # optional lifetime
|
||||||
|
npm -w server run cli -- user:delete alice
|
||||||
|
```
|
||||||
|
|
||||||
|
The container image does not include npm or npx. Run the built CLI with Node inside the running service; it uses that container's configured `DB_PATH` and exits without starting the web server or schedulers:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec liqa node dist/cli.js user:create
|
||||||
|
docker compose exec liqa node dist/cli.js user:get alice
|
||||||
|
docker compose exec liqa node dist/cli.js user:token alice 30m
|
||||||
|
docker compose exec liqa node dist/cli.js user:delete alice
|
||||||
|
```
|
||||||
|
|
||||||
|
`user:create` asks for a username and two matching passwords; password entry is hidden and requires an interactive terminal. A duplicate username, blank username/password, mismatch or invalid input fails with a nonzero exit. The other commands require an existing username; lookup output contains only the account id, username and timestamps. Unknown usernames fail with `No account found for that username.` and a nonzero exit. A token duration must be a positive number followed by `s`, `m`, `h` or `d` (for example `30m`, `1h`, `7d`); omitted duration uses `AUTH_JWT_EXPIRES_IN` (`24h` by default). Token output is a bearer credential: handle it as a secret and do not paste it into logs or shared history. User deletion removes the account, so the server rejects that user's previously issued tokens on their next authentication. General CLI failures print a concise hint to check auth settings, `DB_PATH` and migrations.
|
||||||
|
|
||||||
|
### Browser sessions, logout and development origins
|
||||||
|
|
||||||
|
With auth enabled, the UI asks for credentials at `/login`. `POST /api/v1/auth/login` sets a signed session in an HttpOnly, `SameSite=Strict` cookie (default name `liqa_auth`) whose expiry matches the JWT lifetime. The cookie gets the `Secure` attribute when the request is HTTPS, including when the server sees `X-Forwarded-Proto: https`; serve production traffic over HTTPS and configure trusted proxy headers accordingly. JavaScript cannot read the token. `POST /api/v1/auth/logout` revokes the presented token and clears the cookie. Revoked tokens remain rejected until their expiration; deleted accounts also cause their tokens to be rejected on the next authentication.
|
||||||
|
|
||||||
|
Expired revocation rows are removed at startup and by `AUTH_REVOKED_TOKEN_CLEANUP_CRON` (default `0 3 * * *`, daily at 03:00 server time). The cleanup is not scheduled when authentication is disabled. Browser run notifications use the authenticated `GET /api/v1/scenarios/runs/events` event stream.
|
||||||
|
|
||||||
|
For local Vite development, the server's default CORS origins are `http://localhost:5173` and `http://127.0.0.1:5173` outside production. Vite has no API proxy: set `VITE_API_URL=http://localhost:3000/api/v1` when using a local server, or use `npm -w client run dev:compose-api` to target `http://localhost:13000`. The API's default CORS list also permits the compose origins `http://localhost:13000` and `http://127.0.0.1:13000` in production. Keep the UI and API on the same host name (`localhost` with `localhost`, or `127.0.0.1` with `127.0.0.1`) so the strict cookie remains same-site. For a different origin, set `CORS_ORIGINS` to the exact comma-separated UI origins; use HTTPS in deployed environments.
|
||||||
|
|
||||||
**Changing the schema** (adding or changing an entity):
|
**Changing the schema** (adding or changing an entity):
|
||||||
|
|
||||||
1. Change the entity and build (`npm -w server run build`).
|
1. Change the entity and build (`npm -w server run build`).
|
||||||
@@ -138,7 +192,7 @@ Watch mode:
|
|||||||
npm -w server run test:watch
|
npm -w server run test:watch
|
||||||
```
|
```
|
||||||
|
|
||||||
Print the NestJS logs of the test app (they're silenced by default; `DEBUG=test`):
|
Server application logs use debug output during tests. They remain quiet unless the `test` namespace is enabled. To see NestJS and application logs:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm -w server run test:debug
|
npm -w server run test:debug
|
||||||
@@ -245,13 +299,12 @@ Before adding a dependency, check its license is compatible with MIT distributio
|
|||||||
|
|
||||||
## CI (Gitea Actions)
|
## CI (Gitea Actions)
|
||||||
|
|
||||||
`.gitea/workflows/ci.yml` runs on pushes to `master` and on pull requests:
|
`.gitea/workflows/ci.yml` runs on pushes to `master`, on pull requests and on release tags (`vX.Y.Z`):
|
||||||
|
|
||||||
- **changes**: detects which of `server/` and `client/` changed (via `dorny/paths-filter`), also treating root `package.json`/`package-lock.json` and the workflow file itself as affecting both.
|
- **changes** (not on tags): detects which of `server/` and `client/` changed (via `dorny/paths-filter`), also treating root `package.json`/`package-lock.json` and the workflow file itself as affecting both.
|
||||||
- **server** (skipped if nothing under `server/` changed): lint (no warnings allowed), type-check, tests, build.
|
- **server** (skipped if nothing under `server/` changed; always runs on tags): lint (no warnings allowed), type-check, tests, build.
|
||||||
- **client** (skipped if nothing under `client/` changed): lint (no warnings allowed), build, Storybook tests in headless Chromium.
|
- **client** (skipped if nothing under `client/` changed; always runs on tags): lint (no warnings allowed), build, Storybook tests in headless Chromium.
|
||||||
- **version** (pushes to `master` only): reads `version` from the root `package.json` and checks the registry for an existing `<registry>/<owner>/<repo>:<version>` image; skips the image job if that tag is already present.
|
- **image** (release tags only): after the server and client jobs pass, checks that the tag matches the root `package.json` version (`v<version>`), builds the Docker image and pushes it to the Gitea container registry set by `REGISTRY` at the top of the workflow (`git.hq.ars9.space`) as `<registry>/<owner>/<repo>:<version>` and `:latest`. Merges to `master` don't build images.
|
||||||
- **image** (pushes to `master` only): when the version job found no existing image for the current version, and the server/client jobs passed or were skipped, builds the Docker image and pushes it to the Gitea container registry set by `REGISTRY` at the top of the workflow (`git.hq.ars9.space`) as `<registry>/<owner>/<repo>:<version>` and `:latest`.
|
|
||||||
|
|
||||||
The image job logs in as the repository owner with the `REGISTRY_TOKEN` secret: a Gitea access token with package write access (Settings → Applications → token with `write:package`), added under the repository's Settings → Actions → Secrets. It runs `docker` on the runner, so the runner must give jobs access to a Docker daemon (act_runner mounts the host's Docker socket into job containers by default).
|
The image job logs in as the repository owner with the `REGISTRY_TOKEN` secret: a Gitea access token with package write access (Settings → Applications → token with `write:package`), added under the repository's Settings → Actions → Secrets. It runs `docker` on the runner, so the runner must give jobs access to a Docker daemon (act_runner mounts the host's Docker socket into job containers by default).
|
||||||
|
|
||||||
@@ -321,7 +374,7 @@ client/
|
|||||||
src/
|
src/
|
||||||
api/ API client (client.ts) and types (types.ts)
|
api/ API client (client.ts) and types (types.ts)
|
||||||
components/ modals/ - run, export, export logs and delete confirmation modals
|
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
|
i18n/ i18next bootstrap + locales/en.json
|
||||||
lib/ highlight.js setup, API error toast events
|
lib/ highlight.js setup, API error toast events
|
||||||
pages/ scenario/, run/, snippet/, credential/, environment/, session/, import/
|
pages/ scenario/, run/, snippet/, credential/, environment/, session/, import/
|
||||||
|
|||||||
+14
-1
@@ -2,6 +2,19 @@
|
|||||||
|
|
||||||
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport), e.g. `http://localhost:13000/mcp` with the compose setup. Each request is served by a fresh MCP server, so there is no MCP session state between calls.
|
The MCP endpoint is exposed at `/mcp` (Streamable HTTP transport), e.g. `http://localhost:13000/mcp` with the compose setup. Each request is served by a fresh MCP server, so there is no MCP session state between calls.
|
||||||
|
|
||||||
|
Authentication is disabled by default. When `AUTH_ENABLED=true`, MCP requests must include a valid bearer token from the operator CLI (`user:token`); browser cookies are accepted by the HTTP API, but MCP clients should use the bearer header. For an MCP client that supports custom HTTP headers, configure the endpoint and header like this (replace the synthetic token with a privately issued token):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"url": "https://liqa.example/mcp",
|
||||||
|
"headers": {
|
||||||
|
"Authorization": "Bearer <synthetic-token>"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep the token secret and renew it when it expires. See [development.md](development.md#operator-account-commands) for provisioning and token issuance. With auth disabled, omit the authorization header.
|
||||||
|
|
||||||
The server registers the following tools. All entity IDs are UUIDs; list tools are paginated (`page`, `limit`, and where noted `orderBy` / `orderDir`). Errors are returned as MCP tool errors (`isError: true`) with the message as text.
|
The server registers the following tools. All entity IDs are UUIDs; list tools are paginated (`page`, `limit`, and where noted `orderBy` / `orderDir`). Errors are returned as MCP tool errors (`isError: true`) with the message as text.
|
||||||
|
|
||||||
## Sessions
|
## Sessions
|
||||||
@@ -61,7 +74,7 @@ The server registers the following tools. All entity IDs are UUIDs; list tools a
|
|||||||
| `export_scenario` | Export one scenario version (optional `version`, defaults to the latest) |
|
| `export_scenario` | Export one scenario version (optional `version`, defaults to the latest) |
|
||||||
| `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in [scenario.md](scenario.md)) |
|
| `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in [scenario.md](scenario.md)) |
|
||||||
| `import_yaml` | Import any mix of environments, credentials, snippets and scenarios from YAML (see "Import" in [scenario.md](scenario.md)) |
|
| `import_yaml` | Import any mix of environments, credentials, snippets and scenarios from YAML (see "Import" in [scenario.md](scenario.md)) |
|
||||||
| `export_e2e_test` | Export a scenario as a standalone Playwright test project (zip, base64) |
|
| `export_e2e_test` | Export one scenario version as a standalone Playwright test project (zip, base64; optional `version`, defaults to the latest) |
|
||||||
|
|
||||||
Changes to scenario content (fields and steps) create a new scenario version; credential assignments and files are not versioned.
|
Changes to scenario content (fields and steps) create a new scenario version; credential assignments and files are not versioned.
|
||||||
|
|
||||||
|
|||||||
@@ -114,6 +114,10 @@ steps:
|
|||||||
execCode: await context.page.goto(context.getEnv("base_url"));
|
execCode: await context.page.goto(context.getEnv("base_url"));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### E2e test export
|
||||||
|
|
||||||
|
`GET /scenarios/:id/export-e2e` (the "Export e2e test" button, the `export_e2e_test` MCP tool) exports one scenario version as a standalone Playwright test project, zipped as `<scenario>-v<N>-e2e-test.zip`. It takes an optional `version` (default: the latest). Snippets are bundled the same way as in the scenario export: the latest version for plain `runSnippet("alias")` calls, plus each version pinned with `alias@N`. The environment, credentials and files are the scenario's current ones; they are not versioned.
|
||||||
|
|
||||||
## Playwright traces
|
## Playwright traces
|
||||||
|
|
||||||
A run can record a [Playwright trace](https://playwright.dev/docs/trace-viewer) of its browser context (screenshots and DOM snapshots). When the run finishes, the trace is uploaded to the run's files as `trace.zip`. Download it from the run detail page, then open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
|
A run can record a [Playwright trace](https://playwright.dev/docs/trace-viewer) of its browser context (screenshots and DOM snapshots). When the run finishes, the trace is uploaded to the run's files as `trace.zip`. Download it from the run detail page, then open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
|
||||||
@@ -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.
|
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
|
## Statuses
|
||||||
|
|
||||||
Run status:
|
Run status:
|
||||||
@@ -155,3 +173,5 @@ Run-step status:
|
|||||||
5. Assign credentials to scenario aliases when needed
|
5. Assign credentials to scenario aliases when needed
|
||||||
6. Run scenario
|
6. Run scenario
|
||||||
7. Wait for run completion and inspect run logs/outputs
|
7. Wait for run completion and inspect run logs/outputs
|
||||||
|
|
||||||
|
The [self-test example](../examples/self-test/) follows these steps through the REST API, and can be imported as a complete, working scenario.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Examples
|
||||||
|
|
||||||
|
Ready-to-import liqa resources. Each example is a directory with a YAML file to import (the Import page in the UI, `POST /api/v1/import`, or the `import_yaml` MCP tool; see [Import](../docs/scenario.md#import)) and a README on how to run it.
|
||||||
|
|
||||||
|
| Example | What it shows |
|
||||||
|
|---|---|
|
||||||
|
| [self-test](self-test/) | A scenario that tests the liqa instance it runs on: creates a scenario through the REST API, runs it, checks the run and its page in the UI, and cleans up. Uses an environment, a credential, snippets and assertions |
|
||||||
|
|
||||||
|
`server/test/examples.spec.ts` imports every YAML file in this directory and checks that its code parses, so the examples keep up with the import format.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Self-test
|
||||||
|
|
||||||
|
A scenario that tests the liqa instance it runs on. It drives liqa through its own REST API and web UI: it creates a small scenario, runs it, checks the result and deletes it again. It shows the main liqa features in one place:
|
||||||
|
|
||||||
|
- an **environment** with the URLs and test values the steps read with `context.getEnv()`
|
||||||
|
- a **credential**, assigned to the scenario as `fixture` and read with `context.getCredential()`
|
||||||
|
- three **snippets**, called with `context.runSnippet()`, one of them from the other two
|
||||||
|
- **assertions** (`context.assert()` and Playwright's `expect`), step outputs (`context.getStepOutput()`) and run logs
|
||||||
|
|
||||||
|
Everything is in [self-test.yaml](self-test.yaml).
|
||||||
|
|
||||||
|
## Run it
|
||||||
|
|
||||||
|
1. Start liqa with the default docker compose deployment (`docker compose up -d --build` at the repo root). It's served at http://localhost:13000.
|
||||||
|
2. Import [self-test.yaml](self-test.yaml): open **Import** in the UI and pick the file, or run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:13000/api/v1/import \
|
||||||
|
-H 'Content-Type: application/yaml' \
|
||||||
|
--data-binary @examples/self-test/self-test.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
Every item has a fixed id, so importing the file again updates the same resources instead of adding copies.
|
||||||
|
3. Open the **liqa self-test** scenario and click **Run**. Its default environment, `liqa-self-test`, is preselected.
|
||||||
|
|
||||||
|
The run takes a few seconds. The run page shows every assertion as a log entry, and the target scenario's run while it exists.
|
||||||
|
|
||||||
|
## What's in the file
|
||||||
|
|
||||||
|
| Kind | Name | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| Environment | `liqa-self-test` | `liqa_url` (REST API base), `ui_url` (web UI base), `temp_prefix` (name prefix of the temporary resources), `greeting` (test value) |
|
||||||
|
| Credential | `liqa-self-test-fixture` | Test data (`username`, `token`) that the self-test passes on to the scenario it creates. It's not a real secret |
|
||||||
|
| Snippet | `liqa-api` | `runSnippet("liqa-api", method, path, body?)`: calls `liqa_url` + `/api/v1` + `path`, returns the parsed JSON and throws on an error status |
|
||||||
|
| Snippet | `liqa-run-and-wait` | `runSnippet("liqa-run-and-wait", scenarioId, environmentId)`: starts a run and returns it once it has finished. Uses `liqa-api` |
|
||||||
|
| Snippet | `self-test-cleanup` | Deletes every scenario, credential and environment whose name starts with `temp_prefix` and returns how many it deleted. Uses `liqa-api` |
|
||||||
|
| Scenario | `liqa self-test` | The self-test itself (below) |
|
||||||
|
|
||||||
|
The scenario's steps:
|
||||||
|
|
||||||
|
1. **Check the instance is up**: checks `GET /health`, then runs `self-test-cleanup` to remove anything a failed earlier run left behind (and logs a warning if it found some).
|
||||||
|
2. **Create the target scenario**: creates a temporary environment, a temporary credential (holding the `fixture` credential's data) and the target scenario `[self-test] target scenario`, and assigns the credential to it as `secret`. The target has two steps: one reads `greeting` and the `secret` token, the other renders the greeting on a page and checks it with `expect`.
|
||||||
|
3. **Run the target scenario**: runs it with `liqa-run-and-wait` and checks the result: the run and both steps passed, the step outputs hold the greeting and the token's length, and the target logged its passing assertion.
|
||||||
|
4. **Check the run in the UI**: opens the target's run page at `ui_url` and checks that it shows the scenario name and the assertion.
|
||||||
|
5. **Clean up**: runs `self-test-cleanup` again, and checks that it deleted the three temporary resources and that the target scenario is gone.
|
||||||
|
|
||||||
|
## Addresses
|
||||||
|
|
||||||
|
Steps run inside the liqa server, so `liqa_url` and `ui_url` are addresses as seen from the server, not from your machine. In the docker compose deployment the server listens on port 3000 inside the container, published as 13000 on the host, so both are `http://localhost:3000`.
|
||||||
|
|
||||||
|
When running the server locally (`npm run start:dev`, see [docs/development.md](../../docs/development.md)), `liqa_url` stays `http://localhost:3000`. The UI is then served by the Vite dev server: set `ui_url` to `http://localhost:5173`.
|
||||||
|
|
||||||
|
## When it fails
|
||||||
|
|
||||||
|
A failed step stops the run, so the temporary resources (named `[self-test] ...`) are left in place to inspect. The next self-test run deletes them in its first step.
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
# liqa self-test example: a scenario that tests the liqa instance it runs on.
|
||||||
|
#
|
||||||
|
# Import this file (Import page in the UI, POST /api/v1/import with
|
||||||
|
# Content-Type: application/yaml, or the import_yaml MCP tool), then run the
|
||||||
|
# "liqa self-test" scenario. See README.md next to this file.
|
||||||
|
#
|
||||||
|
# Every item has a fixed id, so importing the file again updates the same
|
||||||
|
# resources instead of creating duplicates.
|
||||||
|
---
|
||||||
|
# Environment: where the liqa under test is reachable from the liqa server
|
||||||
|
kind: environment
|
||||||
|
id: 418eacb0-ab16-4ad6-ab50-c0274fdc49f1
|
||||||
|
name: liqa-self-test
|
||||||
|
description: >-
|
||||||
|
The liqa instance the self-test scenario runs against. Steps run inside the
|
||||||
|
liqa server (the Docker container), so the compose deployment published at
|
||||||
|
http://localhost:13000 is reached at its in-container port 3000.
|
||||||
|
data:
|
||||||
|
# REST API base (without /api/v1)
|
||||||
|
liqa_url: http://localhost:3000
|
||||||
|
# Web UI base; use http://localhost:5173 with the Vite dev server
|
||||||
|
ui_url: http://localhost:3000
|
||||||
|
# Name prefix of the temporary resources the self-test creates and deletes
|
||||||
|
temp_prefix: "[self-test] "
|
||||||
|
# Value the target scenario reads from its own (temporary) environment
|
||||||
|
greeting: Hello from the liqa self-test
|
||||||
|
---
|
||||||
|
# Credential: test data handed over to the temporary target scenario
|
||||||
|
kind: credential
|
||||||
|
id: b0c9ccab-6743-4ac1-9017-d99e0f5d7474
|
||||||
|
name: liqa-self-test-fixture
|
||||||
|
data: '{"username":"self-test-user","token":"not-a-real-secret-0123456789"}'
|
||||||
|
---
|
||||||
|
# Snippet: liqa-api
|
||||||
|
kind: snippet
|
||||||
|
id: f9d2612c-266c-411a-9483-5d860599f208
|
||||||
|
version: 1
|
||||||
|
alias: liqa-api
|
||||||
|
title: Call the liqa REST API
|
||||||
|
description: >-
|
||||||
|
`context.runSnippet("liqa-api", method, path, body?)` sends a request to
|
||||||
|
`liqa_url` + `/api/v1` + path and returns the parsed JSON response (`null`
|
||||||
|
for an empty body). Throws on a non-2xx status.
|
||||||
|
code: |
|
||||||
|
const [method, path, body] = args;
|
||||||
|
const url = context.getEnv("liqa_url") + "/api/v1" + path;
|
||||||
|
const response = await context.page.request.fetch(url, {
|
||||||
|
method,
|
||||||
|
data: body,
|
||||||
|
// POST /scenarios/:id/run/:runId/wait blocks until the run finishes
|
||||||
|
timeout: 120_000,
|
||||||
|
failOnStatusCode: false,
|
||||||
|
});
|
||||||
|
const text = await response.text();
|
||||||
|
if (!response.ok()) {
|
||||||
|
throw new Error(`${method} ${path} returned ${response.status()}: ${text}`);
|
||||||
|
}
|
||||||
|
return text ? JSON.parse(text) : null;
|
||||||
|
---
|
||||||
|
# Snippet: liqa-run-and-wait
|
||||||
|
kind: snippet
|
||||||
|
id: b36c1075-2700-421f-a2e7-ab1a80adb7e7
|
||||||
|
version: 1
|
||||||
|
alias: liqa-run-and-wait
|
||||||
|
title: Run a scenario and wait for it
|
||||||
|
description: >-
|
||||||
|
`context.runSnippet("liqa-run-and-wait", scenarioId, environmentId)` starts
|
||||||
|
a run of the scenario's latest version and returns the finished run (with
|
||||||
|
its step runs and logs). Uses the liqa-api snippet.
|
||||||
|
code: |
|
||||||
|
const [scenarioId, environmentId] = args;
|
||||||
|
const run = await context.runSnippet(
|
||||||
|
"liqa-api",
|
||||||
|
"POST",
|
||||||
|
`/scenarios/${scenarioId}/run`,
|
||||||
|
{ environmentId },
|
||||||
|
);
|
||||||
|
context.log(`Started run ${run.id}, waiting for it to finish`);
|
||||||
|
return context.runSnippet(
|
||||||
|
"liqa-api",
|
||||||
|
"POST",
|
||||||
|
`/scenarios/${scenarioId}/run/${run.id}/wait`,
|
||||||
|
);
|
||||||
|
---
|
||||||
|
# Snippet: self-test-cleanup
|
||||||
|
kind: snippet
|
||||||
|
id: f99e3b17-d28d-4a80-8ae4-f7e8252e0be5
|
||||||
|
version: 1
|
||||||
|
alias: self-test-cleanup
|
||||||
|
title: Delete temporary self-test resources
|
||||||
|
description: >-
|
||||||
|
Deletes every scenario, credential and environment whose name starts with
|
||||||
|
the `temp_prefix` environment value, and returns how many were deleted.
|
||||||
|
Uses the liqa-api snippet.
|
||||||
|
code: |
|
||||||
|
const prefix = context.getEnv("temp_prefix");
|
||||||
|
let deleted = 0;
|
||||||
|
// Scenarios first: they reference the credentials and environments
|
||||||
|
for (const path of ["/scenarios", "/credentials", "/environments"]) {
|
||||||
|
const page = await context.runSnippet("liqa-api", "GET", `${path}?limit=1000`);
|
||||||
|
for (const item of page.data.filter((i) => i.name.startsWith(prefix))) {
|
||||||
|
await context.runSnippet("liqa-api", "DELETE", `${path}/${item.id}`);
|
||||||
|
context.log(`Deleted ${path.slice(1, -1)} "${item.name}"`);
|
||||||
|
deleted += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return deleted;
|
||||||
|
---
|
||||||
|
# Scenario: liqa self-test
|
||||||
|
kind: scenario
|
||||||
|
id: 571b2894-dacc-4428-b459-4e3fefac5908
|
||||||
|
version: 1
|
||||||
|
name: liqa self-test
|
||||||
|
description: |
|
||||||
|
Tests the liqa instance it runs on, through its REST API and web UI:
|
||||||
|
|
||||||
|
1. checks that the instance is up and removes leftovers of earlier runs
|
||||||
|
2. creates a temporary environment, credential and two-step target scenario
|
||||||
|
3. runs the target scenario, waits for it and checks its step outputs and logs
|
||||||
|
4. opens the finished run in the web UI
|
||||||
|
5. deletes the temporary resources
|
||||||
|
|
||||||
|
Uses the `liqa-api`, `liqa-run-and-wait` and `self-test-cleanup` snippets and
|
||||||
|
the `fixture` credential. See `examples/self-test/README.md`.
|
||||||
|
environmentId: 418eacb0-ab16-4ad6-ab50-c0274fdc49f1
|
||||||
|
timeoutSeconds: 300
|
||||||
|
credentials:
|
||||||
|
- credentialId: b0c9ccab-6743-4ac1-9017-d99e0f5d7474
|
||||||
|
alias: fixture
|
||||||
|
steps:
|
||||||
|
- title: Check the instance is up
|
||||||
|
execCode: |
|
||||||
|
const response = await context.page.request.get(
|
||||||
|
context.getEnv("liqa_url") + "/health",
|
||||||
|
);
|
||||||
|
const health = await response.json();
|
||||||
|
context.assert(() => response.ok(), "Health endpoint responds", {
|
||||||
|
status: response.status(),
|
||||||
|
});
|
||||||
|
context.assert(() => health.status === "ok", "Health status is ok", health);
|
||||||
|
|
||||||
|
// A failed earlier run may have left its temporary resources behind
|
||||||
|
const deleted = await context.runSnippet("self-test-cleanup");
|
||||||
|
if (deleted > 0) {
|
||||||
|
context.warn(`Deleted ${deleted} leftover resource(s) of an earlier run`);
|
||||||
|
}
|
||||||
|
return health;
|
||||||
|
- title: Create the target scenario
|
||||||
|
execCode: |
|
||||||
|
const prefix = context.getEnv("temp_prefix");
|
||||||
|
const api = (method, path, body) =>
|
||||||
|
context.runSnippet("liqa-api", method, path, body);
|
||||||
|
|
||||||
|
const environment = await api("POST", "/environments", {
|
||||||
|
name: `${prefix}environment`,
|
||||||
|
data: { greeting: context.getEnv("greeting") },
|
||||||
|
});
|
||||||
|
// Hand the fixture credential over to the target scenario
|
||||||
|
const fixture = context.getCredential("fixture");
|
||||||
|
const credential = await api("POST", "/credentials", {
|
||||||
|
name: `${prefix}credential`,
|
||||||
|
data: JSON.stringify(fixture),
|
||||||
|
});
|
||||||
|
const scenario = await api("POST", "/scenarios", {
|
||||||
|
name: `${prefix}target scenario`,
|
||||||
|
description: "Temporary scenario created by the liqa self-test",
|
||||||
|
environmentId: environment.id,
|
||||||
|
timeoutSeconds: 60,
|
||||||
|
});
|
||||||
|
await api("POST", `/scenarios/${scenario.id}/credentials`, {
|
||||||
|
credentialId: credential.id,
|
||||||
|
alias: "secret",
|
||||||
|
});
|
||||||
|
|
||||||
|
await api("POST", `/scenarios/${scenario.id}/steps`, {
|
||||||
|
title: "Read the environment and credential",
|
||||||
|
execCode: `
|
||||||
|
const secret = context.getCredential("secret");
|
||||||
|
context.assert(() => typeof secret.token === "string", "Credential has a token");
|
||||||
|
// Return the token length, not the token: step outputs are not secret
|
||||||
|
return { greeting: context.getEnv("greeting"), tokenLength: secret.token.length };
|
||||||
|
`,
|
||||||
|
});
|
||||||
|
await api("POST", `/scenarios/${scenario.id}/steps`, {
|
||||||
|
title: "Render the greeting",
|
||||||
|
execCode: `
|
||||||
|
const { greeting } = await context.getStepOutput(-1);
|
||||||
|
await context.page.setContent("<h1>" + greeting + "</h1>");
|
||||||
|
await expect(context.page.locator("h1")).toHaveText(greeting);
|
||||||
|
return { heading: await context.page.locator("h1").textContent() };
|
||||||
|
`,
|
||||||
|
});
|
||||||
|
|
||||||
|
const created = await api("GET", `/scenarios/${scenario.id}`);
|
||||||
|
context.assert(
|
||||||
|
() => created.steps.length === 2,
|
||||||
|
"Target scenario has 2 steps",
|
||||||
|
{ steps: created.steps.length },
|
||||||
|
);
|
||||||
|
context.log(`Created target scenario ${scenario.id}`);
|
||||||
|
return {
|
||||||
|
scenarioId: scenario.id,
|
||||||
|
scenarioName: scenario.name,
|
||||||
|
environmentId: environment.id,
|
||||||
|
credentialId: credential.id,
|
||||||
|
};
|
||||||
|
- title: Run the target scenario
|
||||||
|
timeoutSeconds: 150
|
||||||
|
execCode: |
|
||||||
|
const { scenarioId, environmentId } = await context.getStepOutput(-1);
|
||||||
|
const run = await context.runSnippet(
|
||||||
|
"liqa-run-and-wait",
|
||||||
|
scenarioId,
|
||||||
|
environmentId,
|
||||||
|
);
|
||||||
|
context.assert(() => run.status === "pass", "Target run passed", {
|
||||||
|
status: run.status,
|
||||||
|
errors: run.logs.filter((l) => l.level === "error").map((l) => l.message),
|
||||||
|
});
|
||||||
|
context.assert(
|
||||||
|
() => run.stepRuns.every((s) => s.status === "pass"),
|
||||||
|
"All target steps passed",
|
||||||
|
run.stepRuns.map((s) => ({ order: s.order, status: s.status })),
|
||||||
|
);
|
||||||
|
|
||||||
|
const [read, render] = run.stepRuns.map((s) => JSON.parse(s.output));
|
||||||
|
const greeting = context.getEnv("greeting");
|
||||||
|
context.assert(
|
||||||
|
() => read.greeting === greeting,
|
||||||
|
"Target read the greeting from its environment",
|
||||||
|
read,
|
||||||
|
);
|
||||||
|
context.assert(
|
||||||
|
() => read.tokenLength === context.getCredential("fixture").token.length,
|
||||||
|
"Target read the token from its credential",
|
||||||
|
);
|
||||||
|
context.assert(
|
||||||
|
() => render.heading === greeting,
|
||||||
|
"Target rendered the greeting",
|
||||||
|
render,
|
||||||
|
);
|
||||||
|
context.assert(
|
||||||
|
() =>
|
||||||
|
run.logs.some(
|
||||||
|
(l) =>
|
||||||
|
l.context === "assertion:pass" &&
|
||||||
|
l.message === "Credential has a token",
|
||||||
|
),
|
||||||
|
"Target logged its passed assertion",
|
||||||
|
);
|
||||||
|
return { runId: run.id };
|
||||||
|
- title: Check the run in the UI
|
||||||
|
execCode: |
|
||||||
|
const { scenarioId, scenarioName } = await context.getStepOutput(2);
|
||||||
|
const { runId } = await context.getStepOutput(3);
|
||||||
|
const page = context.page;
|
||||||
|
await page.goto(
|
||||||
|
`${context.getEnv("ui_url")}/scenarios/${scenarioId}/runs/${runId}`,
|
||||||
|
);
|
||||||
|
await expect(page.getByText(scenarioName).first()).toBeVisible();
|
||||||
|
await expect(page.getByText("Credential has a token").first()).toBeVisible();
|
||||||
|
context.log(`Run page checked: ${page.url()}`);
|
||||||
|
return { url: page.url() };
|
||||||
|
- title: Clean up
|
||||||
|
execCode: |
|
||||||
|
const { scenarioId } = await context.getStepOutput(2);
|
||||||
|
const deleted = await context.runSnippet("self-test-cleanup");
|
||||||
|
context.assert(() => deleted === 3, "Deleted the 3 temporary resources", {
|
||||||
|
deleted,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await context.page.request.get(
|
||||||
|
`${context.getEnv("liqa_url")}/api/v1/scenarios/${scenarioId}`,
|
||||||
|
);
|
||||||
|
context.assert(
|
||||||
|
() => response.status() === 404,
|
||||||
|
"Target scenario is gone",
|
||||||
|
{ status: response.status() },
|
||||||
|
);
|
||||||
|
return { deleted };
|
||||||
Generated
+3
-3
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "liqa",
|
"name": "liqa",
|
||||||
"version": "1.24.2",
|
"version": "1.26.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "liqa",
|
"name": "liqa",
|
||||||
"version": "1.24.2",
|
"version": "1.26.0",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"workspaces": [
|
"workspaces": [
|
||||||
"server",
|
"server",
|
||||||
@@ -17464,6 +17464,7 @@
|
|||||||
"better-sqlite3": "^12.8.0",
|
"better-sqlite3": "^12.8.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.4",
|
"class-validator": "^0.14.4",
|
||||||
|
"debug": "^4.4.3",
|
||||||
"effect": "^3.21.0",
|
"effect": "^3.21.0",
|
||||||
"jsdom": "^29.0.2",
|
"jsdom": "^29.0.2",
|
||||||
"playwright": "^1.59.1",
|
"playwright": "^1.59.1",
|
||||||
@@ -17487,7 +17488,6 @@
|
|||||||
"@types/mozilla__readability": "^0.4.2",
|
"@types/mozilla__readability": "^0.4.2",
|
||||||
"@types/node": "^25.5.2",
|
"@types/node": "^25.5.2",
|
||||||
"@types/supertest": "^7.2.0",
|
"@types/supertest": "^7.2.0",
|
||||||
"debug": "^4.4.3",
|
|
||||||
"eslint": "^10.2.0",
|
"eslint": "^10.2.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"jest": "^30.3.0",
|
"jest": "^30.3.0",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "liqa",
|
"name": "liqa",
|
||||||
"version": "1.24.2",
|
"version": "1.26.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"author": "Andrii Arsenin",
|
"author": "Andrii Arsenin",
|
||||||
|
|||||||
+48
-9
@@ -6,14 +6,20 @@ set -euo pipefail
|
|||||||
|
|
||||||
REGISTRY_IMAGE="git.hq.ars9.space/ars9/liqa"
|
REGISTRY_IMAGE="git.hq.ars9.space/ars9/liqa"
|
||||||
|
|
||||||
read -rp "Install directory [./liqa]: " install_dir
|
# Prompt on the terminal, not stdin: under `curl ... | bash` stdin is the
|
||||||
install_dir="${install_dir:-./liqa}"
|
# script itself, so a plain `read` would consume the script's own lines.
|
||||||
|
# Without a terminal, the default is used.
|
||||||
|
ask() {
|
||||||
|
local prompt="$1" default="$2" answer=""
|
||||||
|
if { : </dev/tty; } 2>/dev/null; then
|
||||||
|
read -rp "$prompt [$default]: " answer </dev/tty
|
||||||
|
fi
|
||||||
|
echo "${answer:-$default}"
|
||||||
|
}
|
||||||
|
|
||||||
read -rp "Port to expose [13000]: " port
|
install_dir="$(ask "Install directory" "./liqa")"
|
||||||
port="${port:-13000}"
|
port="$(ask "Port to expose" "13000")"
|
||||||
|
version="$(ask "Version to install" "latest")"
|
||||||
read -rp "Version to install [latest]: " version
|
|
||||||
version="${version:-latest}"
|
|
||||||
|
|
||||||
mkdir -p "$install_dir/data"
|
mkdir -p "$install_dir/data"
|
||||||
|
|
||||||
@@ -35,5 +41,38 @@ EOF
|
|||||||
echo "Wrote $compose_file"
|
echo "Wrote $compose_file"
|
||||||
echo "Created $install_dir/data"
|
echo "Created $install_dir/data"
|
||||||
echo
|
echo
|
||||||
echo "To start liqa:"
|
|
||||||
echo " cd $install_dir && docker compose up -d"
|
start_hint() {
|
||||||
|
echo "Once that is fixed, start liqa with:" >&2
|
||||||
|
echo " cd $install_dir && docker compose up -d" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if ! command -v docker >/dev/null 2>&1; then
|
||||||
|
echo "Error: docker is not installed. Install Docker Engine with the Compose plugin:" >&2
|
||||||
|
echo " https://docs.docker.com/engine/install/" >&2
|
||||||
|
start_hint
|
||||||
|
elif ! docker compose version >/dev/null 2>&1; then
|
||||||
|
echo "Error: the Docker Compose plugin (docker compose) is not available. Install it:" >&2
|
||||||
|
echo " https://docs.docker.com/compose/install/linux/" >&2
|
||||||
|
start_hint
|
||||||
|
elif ! docker compose -f "$compose_file" config --quiet >/dev/null 2>&1; then
|
||||||
|
echo "Error: docker compose rejected $compose_file:" >&2
|
||||||
|
docker compose -f "$compose_file" config --quiet >&2 || true
|
||||||
|
start_hint
|
||||||
|
elif ! docker info >/dev/null 2>&1; then
|
||||||
|
echo "Error: can't reach the Docker daemon. Make sure it is running and that" >&2
|
||||||
|
echo "your user may use it (e.g. is in the docker group), or use sudo." >&2
|
||||||
|
start_hint
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd "$install_dir"
|
||||||
|
if ! docker compose up -d; then
|
||||||
|
echo >&2
|
||||||
|
echo "Error: docker compose up failed." >&2
|
||||||
|
start_hint
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "liqa is running at http://localhost:$port"
|
||||||
|
echo "Manage it from $install_dir with docker compose (ps, logs, down, pull)."
|
||||||
@@ -6,6 +6,7 @@ module.exports = {
|
|||||||
transform: {
|
transform: {
|
||||||
'^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }],
|
'^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }],
|
||||||
},
|
},
|
||||||
|
setupFiles: ['<rootDir>/test/logging.setup.js'],
|
||||||
moduleNameMapper: {
|
moduleNameMapper: {
|
||||||
'^jsdom$': '<rootDir>/test/__mocks__/jsdom.ts',
|
'^jsdom$': '<rootDir>/test/__mocks__/jsdom.ts',
|
||||||
'^playwright$': '<rootDir>/test/__mocks__/playwright.ts',
|
'^playwright$': '<rootDir>/test/__mocks__/playwright.ts',
|
||||||
|
|||||||
+2
-1
@@ -10,6 +10,7 @@
|
|||||||
"migration:run": "node dist/database/migrate",
|
"migration:run": "node dist/database/migrate",
|
||||||
"migration:show": "typeorm migration:show -d dist/database/data-source.js",
|
"migration:show": "typeorm migration:show -d dist/database/data-source.js",
|
||||||
"migration:generate": "typeorm migration:generate -d dist/database/data-source.js",
|
"migration:generate": "typeorm migration:generate -d dist/database/data-source.js",
|
||||||
|
"cli": "node dist/cli.js",
|
||||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
|
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
|
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
@@ -37,6 +38,7 @@
|
|||||||
"better-sqlite3": "^12.8.0",
|
"better-sqlite3": "^12.8.0",
|
||||||
"class-transformer": "^0.5.1",
|
"class-transformer": "^0.5.1",
|
||||||
"class-validator": "^0.14.4",
|
"class-validator": "^0.14.4",
|
||||||
|
"debug": "^4.4.3",
|
||||||
"effect": "^3.21.0",
|
"effect": "^3.21.0",
|
||||||
"jsdom": "^29.0.2",
|
"jsdom": "^29.0.2",
|
||||||
"playwright": "^1.59.1",
|
"playwright": "^1.59.1",
|
||||||
@@ -60,7 +62,6 @@
|
|||||||
"@types/mozilla__readability": "^0.4.2",
|
"@types/mozilla__readability": "^0.4.2",
|
||||||
"@types/node": "^25.5.2",
|
"@types/node": "^25.5.2",
|
||||||
"@types/supertest": "^7.2.0",
|
"@types/supertest": "^7.2.0",
|
||||||
"debug": "^4.4.3",
|
|
||||||
"eslint": "^10.2.0",
|
"eslint": "^10.2.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"jest": "^30.3.0",
|
"jest": "^30.3.0",
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { ScheduleModule } from "@nestjs/schedule";
|
|||||||
import { ServeStaticModule } from "@nestjs/serve-static";
|
import { ServeStaticModule } from "@nestjs/serve-static";
|
||||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||||
import { BrowserModule } from "./browser/browser.module";
|
import { BrowserModule } from "./browser/browser.module";
|
||||||
|
import { AuthModule } from "./auth/auth.module";
|
||||||
import { clientStaticOptions } from "./common/client-static";
|
import { clientStaticOptions } from "./common/client-static";
|
||||||
import { dataSourceOptions } from "./database/data-source";
|
import { dataSourceOptions } from "./database/data-source";
|
||||||
import { AppConfig, validateAppConfig } from "./config/app.config";
|
import { AppConfig, validateAppConfig } from "./config/app.config";
|
||||||
@@ -36,6 +37,7 @@ import { SnippetModule } from "./snippet/snippet.module";
|
|||||||
dataSourceOptions(config.get("DB_PATH")),
|
dataSourceOptions(config.get("DB_PATH")),
|
||||||
}),
|
}),
|
||||||
BrowserModule,
|
BrowserModule,
|
||||||
|
AuthModule,
|
||||||
EnvironmentModule,
|
EnvironmentModule,
|
||||||
CredentialModule,
|
CredentialModule,
|
||||||
ScenarioModule,
|
ScenarioModule,
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export const AUTH_COOKIE_NAME = "liqa_auth";
|
||||||
@@ -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),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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 {}
|
||||||
@@ -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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,5 +1,10 @@
|
|||||||
import { Body, Controller, Post } from "@nestjs/common";
|
import { Body, Controller, Post } from "@nestjs/common";
|
||||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||||
import { CredentialService } from "../credential/credential.service";
|
import { CredentialService } from "../credential/credential.service";
|
||||||
import { EnvironmentService } from "../environment/environment.service";
|
import { EnvironmentService } from "../environment/environment.service";
|
||||||
@@ -8,6 +13,7 @@ import { ExecDto } from "./dto/exec.dto";
|
|||||||
import { OpenDto } from "./dto/open.dto";
|
import { OpenDto } from "./dto/open.dto";
|
||||||
|
|
||||||
@ApiTags("browser")
|
@ApiTags("browser")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller()
|
@Controller()
|
||||||
export class BrowserController {
|
export class BrowserController {
|
||||||
constructor(
|
constructor(
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import type {
|
|||||||
ScriptLogger,
|
ScriptLogger,
|
||||||
} from "../code-executor/code-executor.service";
|
} from "../code-executor/code-executor.service";
|
||||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
import { createAppLogger } from "../common/app-logger";
|
||||||
import type { EnvironmentData } from "../environment/environment.entity";
|
import type { EnvironmentData } from "../environment/environment.entity";
|
||||||
import { SessionContextService } from "../session/session-context.service";
|
import { SessionContextService } from "../session/session-context.service";
|
||||||
import { SessionService } from "../session/session.service";
|
import { SessionService } from "../session/session.service";
|
||||||
@@ -28,7 +28,7 @@ export interface OpenResult {
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class BrowserService {
|
export class BrowserService {
|
||||||
private readonly logger = new TraceLogger(BrowserService.name);
|
private readonly logger = createAppLogger(BrowserService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly sessionContextService: SessionContextService,
|
private readonly sessionContextService: SessionContextService,
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import "reflect-metadata";
|
||||||
|
import dataSource from "./database/data-source";
|
||||||
|
import { validateAppConfig } from "./config/app.config";
|
||||||
|
import { PasswordService } from "./auth/password.service";
|
||||||
|
import {
|
||||||
|
OperatorCliError,
|
||||||
|
createTerminalInput,
|
||||||
|
runOperatorCommand,
|
||||||
|
} from "./operator-cli/operator-cli";
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
const config = validateAppConfig(process.env);
|
||||||
|
if (!config.AUTH_ENABLED) {
|
||||||
|
throw new OperatorCliError(
|
||||||
|
"Operator account commands require AUTH_ENABLED=true.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await dataSource.initialize();
|
||||||
|
try {
|
||||||
|
await runOperatorCommand(process.argv.slice(2), {
|
||||||
|
dataSource,
|
||||||
|
config,
|
||||||
|
passwords: new PasswordService(),
|
||||||
|
input: createTerminalInput(),
|
||||||
|
output: { write: (message) => process.stdout.write(message) },
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
await dataSource.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error: unknown) => {
|
||||||
|
if (error instanceof OperatorCliError) {
|
||||||
|
console.error(error.message);
|
||||||
|
} else if (
|
||||||
|
error instanceof Error &&
|
||||||
|
error.message === "This command requires an interactive terminal."
|
||||||
|
) {
|
||||||
|
console.error(error.message);
|
||||||
|
} else {
|
||||||
|
console.error(
|
||||||
|
"Operator command failed. Check AUTH_ENABLED, DB_PATH, and that database migrations are up to date.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
@@ -8,7 +8,7 @@ import { parse } from "acorn";
|
|||||||
import type { BrowserContext, Page } from "playwright";
|
import type { BrowserContext, Page } from "playwright";
|
||||||
import { URL } from "node:url";
|
import { URL } from "node:url";
|
||||||
import { downloadFile as downloadFileImpl } from "../common/file-downloader";
|
import { downloadFile as downloadFileImpl } from "../common/file-downloader";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
import { createAppLogger } from "../common/app-logger";
|
||||||
import type { EnvironmentData } from "../environment/environment.entity";
|
import type { EnvironmentData } from "../environment/environment.entity";
|
||||||
import type { FileStorageService } from "../file/file-storage.service";
|
import type { FileStorageService } from "../file/file-storage.service";
|
||||||
import type { DomNode } from "./dom-helpers";
|
import type { DomNode } from "./dom-helpers";
|
||||||
@@ -115,7 +115,7 @@ export interface ExecContext {
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class CodeExecutorService {
|
export class CodeExecutorService {
|
||||||
private readonly logger = new TraceLogger(CodeExecutorService.name);
|
private readonly logger = createAppLogger(CodeExecutorService.name);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates `code` by wrapping it in an async function body and attempting
|
* Validates `code` by wrapping it in an async function body and attempting
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { ConsoleLogger, ConsoleLoggerOptions, LogLevel } from "@nestjs/common";
|
import { ConsoleLogger, ConsoleLoggerOptions, LogLevel } from "@nestjs/common";
|
||||||
import { getTraceId } from "./trace-context";
|
import { getTraceId } from "./trace-context";
|
||||||
|
|
||||||
|
/** Runtime console logger. Output is always written using Nest's console behavior. */
|
||||||
export class TraceLogger extends ConsoleLogger {
|
export class TraceLogger extends ConsoleLogger {
|
||||||
constructor(context?: string, options: ConsoleLoggerOptions = {}) {
|
constructor(context?: string, options: ConsoleLoggerOptions = {}) {
|
||||||
super(context as string, options);
|
super(context as string, options);
|
||||||
@@ -10,6 +11,11 @@ export class TraceLogger extends ConsoleLogger {
|
|||||||
return new Date().toISOString();
|
return new Date().toISOString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected override formatContext(context: string): string {
|
||||||
|
const traceId = getTraceId();
|
||||||
|
return super.formatContext(traceId ? `${context}:${traceId}` : context);
|
||||||
|
}
|
||||||
|
|
||||||
protected override formatMessage(
|
protected override formatMessage(
|
||||||
logLevel: LogLevel,
|
logLevel: LogLevel,
|
||||||
message: unknown,
|
message: unknown,
|
||||||
@@ -22,10 +28,4 @@ export class TraceLogger extends ConsoleLogger {
|
|||||||
const level = this.colorize(logLevel.toUpperCase(), logLevel);
|
const level = this.colorize(logLevel.toUpperCase(), logLevel);
|
||||||
return `${this.getTimestamp()} ${level} ${contextMessage}${output}${timestampDiff}\n`;
|
return `${this.getTimestamp()} ${level} ${contextMessage}${output}${timestampDiff}\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override formatContext(context: string): string {
|
|
||||||
const traceId = getTraceId();
|
|
||||||
const traced = traceId ? `${context}:${traceId}` : context;
|
|
||||||
return super.formatContext(traced);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
|
import "reflect-metadata";
|
||||||
import { plainToInstance } from "class-transformer";
|
import { plainToInstance } from "class-transformer";
|
||||||
import {
|
import {
|
||||||
|
IsBoolean,
|
||||||
IsEnum,
|
IsEnum,
|
||||||
IsInt,
|
IsInt,
|
||||||
IsString,
|
IsString,
|
||||||
@@ -10,12 +12,19 @@ import {
|
|||||||
|
|
||||||
import { appPackage } from "../common/app-package";
|
import { appPackage } from "../common/app-package";
|
||||||
|
|
||||||
|
import { durationSeconds } from "../common/interval";
|
||||||
|
|
||||||
export enum TraceMode {
|
export enum TraceMode {
|
||||||
On = "on",
|
On = "on",
|
||||||
RetainOnFailure = "retain-on-failure",
|
RetainOnFailure = "retain-on-failure",
|
||||||
Off = "off",
|
Off = "off",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum LogMode {
|
||||||
|
Console = "console",
|
||||||
|
Debug = "debug",
|
||||||
|
}
|
||||||
|
|
||||||
export class AppConfig {
|
export class AppConfig {
|
||||||
/** `production` in the Docker image; also selects the default CORS origins. */
|
/** `production` in the Docker image; also selects the default CORS origins. */
|
||||||
@IsString()
|
@IsString()
|
||||||
@@ -36,6 +45,10 @@ export class AppConfig {
|
|||||||
@IsString()
|
@IsString()
|
||||||
APP_VERSION: string = appPackage().version;
|
APP_VERSION: string = appPackage().version;
|
||||||
|
|
||||||
|
/** Route application diagnostics through `debug` instead of the console. */
|
||||||
|
@IsEnum(LogMode)
|
||||||
|
LOG_MODE: LogMode = LogMode.Console;
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
DB_PATH: string = "data/liqa.db";
|
DB_PATH: string = "data/liqa.db";
|
||||||
|
|
||||||
@@ -74,15 +87,66 @@ export class AppConfig {
|
|||||||
@IsInt()
|
@IsInt()
|
||||||
@Min(0)
|
@Min(0)
|
||||||
RUN_LOG_DATA_COLLAPSE_LINES: number = 5;
|
RUN_LOG_DATA_COLLAPSE_LINES: number = 5;
|
||||||
|
|
||||||
|
/** Authentication is opt-in so existing deployments remain unchanged. */
|
||||||
|
@IsBoolean()
|
||||||
|
AUTH_ENABLED: boolean = false;
|
||||||
|
|
||||||
|
/** Required only when AUTH_ENABLED is true. */
|
||||||
|
@IsString()
|
||||||
|
AUTH_JWT_SECRET: string = "";
|
||||||
|
|
||||||
|
/** Cookie name used for browser sessions. */
|
||||||
|
@IsString()
|
||||||
|
AUTH_COOKIE_NAME: string = "liqa_auth";
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
AUTH_JWT_EXPIRES_IN: string = "24h";
|
||||||
|
|
||||||
|
@IsString()
|
||||||
|
AUTH_REVOKED_TOKEN_CLEANUP_CRON: string = "0 3 * * *";
|
||||||
}
|
}
|
||||||
|
|
||||||
export function validateAppConfig(config: Record<string, unknown>): AppConfig {
|
export function validateAppConfig(config: Record<string, unknown>): AppConfig {
|
||||||
const validated = plainToInstance(AppConfig, config, {
|
const authEnabled = config.AUTH_ENABLED;
|
||||||
|
if (
|
||||||
|
authEnabled !== undefined &&
|
||||||
|
authEnabled !== true &&
|
||||||
|
authEnabled !== false &&
|
||||||
|
authEnabled !== "true" &&
|
||||||
|
authEnabled !== "false"
|
||||||
|
) {
|
||||||
|
throw new Error("AUTH_ENABLED must be either true or false.");
|
||||||
|
}
|
||||||
|
const normalized = {
|
||||||
|
...config,
|
||||||
|
AUTH_ENABLED: authEnabled === true || authEnabled === "true",
|
||||||
|
};
|
||||||
|
const validated = plainToInstance(AppConfig, normalized, {
|
||||||
enableImplicitConversion: true,
|
enableImplicitConversion: true,
|
||||||
});
|
});
|
||||||
const errors = validateSync(validated, { skipMissingProperties: false });
|
const errors = validateSync(validated, { skipMissingProperties: false });
|
||||||
if (errors.length > 0) {
|
if (errors.length > 0) {
|
||||||
throw new Error(errors.toString());
|
throw new Error(errors.toString());
|
||||||
}
|
}
|
||||||
|
if (validated.AUTH_ENABLED && !validated.AUTH_JWT_SECRET.trim()) {
|
||||||
|
throw new Error("AUTH_JWT_SECRET must be set when AUTH_ENABLED=true.");
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
validated.AUTH_ENABLED &&
|
||||||
|
durationSeconds(validated.AUTH_JWT_EXPIRES_IN) === null
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"AUTH_JWT_EXPIRES_IN must be a positive duration such as 30m, 1h, or 24h.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
validated.AUTH_ENABLED &&
|
||||||
|
!validated.AUTH_REVOKED_TOKEN_CLEANUP_CRON.trim()
|
||||||
|
) {
|
||||||
|
throw new Error(
|
||||||
|
"AUTH_REVOKED_TOKEN_CLEANUP_CRON must be set when AUTH_ENABLED=true.",
|
||||||
|
);
|
||||||
|
}
|
||||||
return validated;
|
return validated;
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,12 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
import { CredentialQueryDto } from "./dto/credential-query.dto";
|
import { CredentialQueryDto } from "./dto/credential-query.dto";
|
||||||
import { CredentialService } from "./credential.service";
|
import { CredentialService } from "./credential.service";
|
||||||
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
import { CreateCredentialDto } from "./dto/create-credential.dto";
|
||||||
@@ -18,6 +23,7 @@ import { CredentialExportDto } from "./dto/credential-export.dto";
|
|||||||
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
import { UpdateCredentialDto } from "./dto/update-credential.dto";
|
||||||
|
|
||||||
@ApiTags("credentials")
|
@ApiTags("credentials")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("credentials")
|
@Controller("credentials")
|
||||||
export class CredentialController {
|
export class CredentialController {
|
||||||
constructor(private readonly credentialService: CredentialService) {}
|
constructor(private readonly credentialService: CredentialService) {}
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
import { CredentialEntity } from "../credential/credential.entity";
|
import { CredentialEntity } from "../credential/credential.entity";
|
||||||
|
import { RevokedTokenEntity } from "../auth/revoked-token.entity";
|
||||||
|
import { UserEntity } from "../auth/user.entity";
|
||||||
import { EnvironmentEntity } from "../environment/environment.entity";
|
import { EnvironmentEntity } from "../environment/environment.entity";
|
||||||
import { FileEntity } from "../file/file.entity";
|
import { FileEntity } from "../file/file.entity";
|
||||||
import { ScenarioFileEntity } from "../file/scenario-file.entity";
|
import { ScenarioFileEntity } from "../file/scenario-file.entity";
|
||||||
@@ -16,6 +18,8 @@ import { SnippetEntity } from "../snippet/snippet.entity";
|
|||||||
|
|
||||||
/** Every TypeORM entity of the app (used by the app, the migrations CLI and tests). */
|
/** Every TypeORM entity of the app (used by the app, the migrations CLI and tests). */
|
||||||
export const ENTITIES = [
|
export const ENTITIES = [
|
||||||
|
UserEntity,
|
||||||
|
RevokedTokenEntity,
|
||||||
SessionEntity,
|
SessionEntity,
|
||||||
EnvironmentEntity,
|
EnvironmentEntity,
|
||||||
CredentialEntity,
|
CredentialEntity,
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { MigrationInterface, QueryRunner } from "typeorm";
|
||||||
|
|
||||||
|
export class AddAuthUsersAndRevokedTokens1793823870652 implements MigrationInterface {
|
||||||
|
name = "AddAuthUsersAndRevokedTokens1793823870652";
|
||||||
|
|
||||||
|
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
if (!(await queryRunner.hasTable("users"))) {
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "users" ("id" varchar PRIMARY KEY NOT NULL, "username" varchar NOT NULL, "passwordHash" text NOT NULL, "createdAt" datetime NOT NULL DEFAULT (datetime('now')), "updatedAt" datetime NOT NULL DEFAULT (datetime('now')), CONSTRAINT "UQ_fe0bb3f6520ee0469504521e710" UNIQUE ("username"))`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!(await queryRunner.hasTable("revoked_tokens"))) {
|
||||||
|
await queryRunner.query(
|
||||||
|
`CREATE TABLE "revoked_tokens" ("tokenHash" varchar(64) PRIMARY KEY NOT NULL, "expiresAt" datetime NOT NULL)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||||
|
await queryRunner.query(`DROP TABLE "revoked_tokens"`);
|
||||||
|
await queryRunner.query(`DROP TABLE "users"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { Initial1790793447827 } from "./1790793447827-Initial";
|
import { Initial1790793447827 } from "./1790793447827-Initial";
|
||||||
import { AddRunLogContext1790848194828 } from "./1790848194828-AddRunLogContext";
|
import { AddRunLogContext1790848194828 } from "./1790848194828-AddRunLogContext";
|
||||||
import { AddRunLogData1790850734763 } from "./1790850734763-AddRunLogData";
|
import { AddRunLogData1790850734763 } from "./1790850734763-AddRunLogData";
|
||||||
|
import { AddAuthUsersAndRevokedTokens1793823870652 } from "./1793823870652-AddAuthUsersAndRevokedTokens";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* All migrations, oldest first. Listed explicitly (instead of a glob) so the
|
* All migrations, oldest first. Listed explicitly (instead of a glob) so the
|
||||||
@@ -10,4 +11,5 @@ export const MIGRATIONS = [
|
|||||||
Initial1790793447827,
|
Initial1790793447827,
|
||||||
AddRunLogContext1790848194828,
|
AddRunLogContext1790848194828,
|
||||||
AddRunLogData1790850734763,
|
AddRunLogData1790850734763,
|
||||||
|
AddAuthUsersAndRevokedTokens1793823870652,
|
||||||
];
|
];
|
||||||
@@ -10,7 +10,12 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
import { EnvironmentQueryDto } from "./dto/environment-query.dto";
|
import { EnvironmentQueryDto } from "./dto/environment-query.dto";
|
||||||
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
|
import { CreateEnvironmentDto } from "./dto/create-environment.dto";
|
||||||
import { EnvironmentExportDto } from "./dto/environment-export.dto";
|
import { EnvironmentExportDto } from "./dto/environment-export.dto";
|
||||||
@@ -18,6 +23,7 @@ import { UpdateEnvironmentDto } from "./dto/update-environment.dto";
|
|||||||
import { EnvironmentService } from "./environment.service";
|
import { EnvironmentService } from "./environment.service";
|
||||||
|
|
||||||
@ApiTags("environments")
|
@ApiTags("environments")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("environments")
|
@Controller("environments")
|
||||||
export class EnvironmentController {
|
export class EnvironmentController {
|
||||||
constructor(private readonly environmentService: EnvironmentService) {}
|
constructor(private readonly environmentService: EnvironmentService) {}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import * as fs from "node:fs/promises";
|
|||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import { CronJob } from "cron";
|
import { CronJob } from "cron";
|
||||||
import { Repository } from "typeorm";
|
import { Repository } from "typeorm";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
import { createAppLogger } from "../common/app-logger";
|
||||||
import { AppConfig } from "../config/app.config";
|
import { AppConfig } from "../config/app.config";
|
||||||
import { FileEntity } from "./file.entity";
|
import { FileEntity } from "./file.entity";
|
||||||
import { ScenarioFileEntity } from "./scenario-file.entity";
|
import { ScenarioFileEntity } from "./scenario-file.entity";
|
||||||
@@ -27,7 +27,7 @@ export interface FileMetadata {
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class FileStorageService implements OnModuleInit {
|
export class FileStorageService implements OnModuleInit {
|
||||||
private static readonly DEFAULT_PAGE_SIZE = 20;
|
private static readonly DEFAULT_PAGE_SIZE = 20;
|
||||||
private readonly logger = new TraceLogger(FileStorageService.name);
|
private readonly logger = createAppLogger(FileStorageService.name);
|
||||||
private readonly filesDir: string;
|
private readonly filesDir: string;
|
||||||
private readonly fileRunExpirationDays: number;
|
private readonly fileRunExpirationDays: number;
|
||||||
private readonly fileCleanupCron: string;
|
private readonly fileCleanupCron: string;
|
||||||
|
|||||||
@@ -7,11 +7,11 @@ import {
|
|||||||
InternalServerErrorException,
|
InternalServerErrorException,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import type { Request, Response } from "express";
|
import type { Request, Response } from "express";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
import { createAppLogger } from "../common/app-logger";
|
||||||
|
|
||||||
@Catch(BadRequestException, InternalServerErrorException)
|
@Catch(BadRequestException, InternalServerErrorException)
|
||||||
export class HttpExceptionFilter implements ExceptionFilter {
|
export class HttpExceptionFilter implements ExceptionFilter {
|
||||||
private readonly logger = new TraceLogger(HttpExceptionFilter.name);
|
private readonly logger = createAppLogger(HttpExceptionFilter.name);
|
||||||
|
|
||||||
catch(exception: HttpException, host: ArgumentsHost): void {
|
catch(exception: HttpException, host: ArgumentsHost): void {
|
||||||
const ctx = host.switchToHttp();
|
const ctx = host.switchToHttp();
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { Controller, Get } from "@nestjs/common";
|
import { Controller, Get } from "@nestjs/common";
|
||||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||||
|
import { Public } from "../auth/public.decorator";
|
||||||
|
|
||||||
@ApiTags("health")
|
@ApiTags("health")
|
||||||
@Controller()
|
@Controller()
|
||||||
export class HealthController {
|
export class HealthController {
|
||||||
@Get("health")
|
@Get("health")
|
||||||
|
@Public()
|
||||||
@ApiOperation({ summary: "Health check" })
|
@ApiOperation({ summary: "Health check" })
|
||||||
@ApiResponse({ status: 200, description: "Service is healthy" })
|
@ApiResponse({ status: 200, description: "Service is healthy" })
|
||||||
health(): { status: string } {
|
health(): { status: string } {
|
||||||
@@ -12,6 +14,7 @@ export class HealthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get("healthz")
|
@Get("healthz")
|
||||||
|
@Public()
|
||||||
@ApiOperation({ summary: "Health check" })
|
@ApiOperation({ summary: "Health check" })
|
||||||
@ApiResponse({ status: 200, description: "Service is healthy" })
|
@ApiResponse({ status: 200, description: "Service is healthy" })
|
||||||
healthz(): { status: string } {
|
healthz(): { status: string } {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
|
import { BadRequestException, Body, Controller, Post } from "@nestjs/common";
|
||||||
import {
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
ApiBody,
|
ApiBody,
|
||||||
ApiConsumes,
|
ApiConsumes,
|
||||||
ApiOperation,
|
ApiOperation,
|
||||||
@@ -10,6 +11,7 @@ import { YAML_CONTENT_TYPES } from "../common/body-parsers";
|
|||||||
import { ImportService } from "./import.service";
|
import { ImportService } from "./import.service";
|
||||||
|
|
||||||
@ApiTags("import")
|
@ApiTags("import")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("import")
|
@Controller("import")
|
||||||
export class ImportController {
|
export class ImportController {
|
||||||
constructor(private readonly importService: ImportService) {}
|
constructor(private readonly importService: ImportService) {}
|
||||||
|
|||||||
@@ -6,11 +6,29 @@ import {
|
|||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import type { Request, Response } from "express";
|
import type { Request, Response } from "express";
|
||||||
import { Observable, tap } from "rxjs";
|
import { Observable, tap } from "rxjs";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
import { createAppLogger } from "../common/app-logger";
|
||||||
|
|
||||||
|
export function redactAuthRequestBody(path: string, body: unknown): unknown {
|
||||||
|
const normalizedPath = path.toLowerCase().replace(/\/+$/, "");
|
||||||
|
if (
|
||||||
|
(normalizedPath !== "/auth/login" &&
|
||||||
|
normalizedPath !== "/api/v1/auth/login") ||
|
||||||
|
!body ||
|
||||||
|
typeof body !== "object" ||
|
||||||
|
Array.isArray(body)
|
||||||
|
) {
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
const requestBody = body as Record<string, unknown>;
|
||||||
|
return {
|
||||||
|
...requestBody,
|
||||||
|
password: requestBody.password ? "[REDACTED]" : requestBody.password,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class LoggingInterceptor implements NestInterceptor {
|
export class LoggingInterceptor implements NestInterceptor {
|
||||||
private readonly logger = new TraceLogger(LoggingInterceptor.name);
|
private readonly logger = createAppLogger(LoggingInterceptor.name);
|
||||||
|
|
||||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||||
const http = context.switchToHttp();
|
const http = context.switchToHttp();
|
||||||
@@ -18,8 +36,11 @@ export class LoggingInterceptor implements NestInterceptor {
|
|||||||
const res = http.getResponse<Response>();
|
const res = http.getResponse<Response>();
|
||||||
const { method, url, body } = req;
|
const { method, url, body } = req;
|
||||||
const start = Date.now();
|
const start = Date.now();
|
||||||
|
const safeBody = redactAuthRequestBody(req.path, body);
|
||||||
const bodyStr =
|
const bodyStr =
|
||||||
body && Object.keys(body).length ? ` ${JSON.stringify(body)}` : "";
|
safeBody && Object.keys(safeBody).length
|
||||||
|
? ` ${JSON.stringify(safeBody)}`
|
||||||
|
: "";
|
||||||
|
|
||||||
this.logger.debug(`→ ${method} ${url}${bodyStr}`);
|
this.logger.debug(`→ ${method} ${url}${bodyStr}`);
|
||||||
|
|
||||||
|
|||||||
+9
-5
@@ -8,7 +8,7 @@ import { AppModule } from "./app.module";
|
|||||||
import { appPackage } from "./common/app-package";
|
import { appPackage } from "./common/app-package";
|
||||||
import { configureBodyParsers } from "./common/body-parsers";
|
import { configureBodyParsers } from "./common/body-parsers";
|
||||||
import { corsOrigins } from "./common/cors";
|
import { corsOrigins } from "./common/cors";
|
||||||
import { TraceLogger } from "./common/trace-logger";
|
import { createAppLogger } from "./common/app-logger";
|
||||||
import { AppConfig } from "./config/app.config";
|
import { AppConfig } from "./config/app.config";
|
||||||
import { HttpExceptionFilter } from "./filters/http-exception.filter";
|
import { HttpExceptionFilter } from "./filters/http-exception.filter";
|
||||||
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
|
import { LoggingInterceptor } from "./interceptors/logging.interceptor";
|
||||||
@@ -17,9 +17,12 @@ import { TraceInterceptor } from "./interceptors/trace.interceptor";
|
|||||||
// Guard against uncaught exceptions thrown inside Playwright event listener
|
// Guard against uncaught exceptions thrown inside Playwright event listener
|
||||||
// callbacks (e.g. a bad waitForURL predicate). Without this, Node.js v15+
|
// callbacks (e.g. a bad waitForURL predicate). Without this, Node.js v15+
|
||||||
// crashes the process on any unhandled rejection or uncaught exception.
|
// crashes the process on any unhandled rejection or uncaught exception.
|
||||||
const processLogger = new TraceLogger("Process");
|
const processLogger = createAppLogger("Process");
|
||||||
process.on("uncaughtException", (err) => {
|
process.on("uncaughtException", (err) => {
|
||||||
processLogger.error(`Uncaught exception (process kept alive): ${err.message}`, err.stack);
|
processLogger.error(
|
||||||
|
`Uncaught exception (process kept alive): ${err.message}`,
|
||||||
|
err.stack,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
process.on("unhandledRejection", (reason) => {
|
process.on("unhandledRejection", (reason) => {
|
||||||
processLogger.error(
|
processLogger.error(
|
||||||
@@ -32,9 +35,9 @@ process.on("unhandledRejection", (reason) => {
|
|||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const { name: pkgName, version: pkgVersion } = appPackage();
|
const { name: pkgName, version: pkgVersion } = appPackage();
|
||||||
const API_PREFIX = "api/v1";
|
const API_PREFIX = "api/v1";
|
||||||
const logger = new TraceLogger("Bootstrap");
|
const logger = createAppLogger("Bootstrap");
|
||||||
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
|
||||||
logger: new TraceLogger("Bootstrap", { timestamp: true }),
|
logger: createAppLogger("Bootstrap", { timestamp: true }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// The schema is managed by migrations; refuse to run against an outdated one.
|
// The schema is managed by migrations; refuse to run against an outdated one.
|
||||||
@@ -74,6 +77,7 @@ async function bootstrap() {
|
|||||||
.setTitle(pkgName)
|
.setTitle(pkgName)
|
||||||
.setDescription(`${pkgName} API`)
|
.setDescription(`${pkgName} API`)
|
||||||
.setVersion(pkgVersion)
|
.setVersion(pkgVersion)
|
||||||
|
.addBearerAuth()
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
const document = SwaggerModule.createDocument(app, swaggerConfig);
|
const document = SwaggerModule.createDocument(app, swaggerConfig);
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { Controller, Get, Header } from "@nestjs/common";
|
|||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";
|
import { ApiOkResponse, ApiOperation, ApiTags } from "@nestjs/swagger";
|
||||||
import { AppConfig } from "../config/app.config";
|
import { AppConfig } from "../config/app.config";
|
||||||
|
import { Public } from "../auth/public.decorator";
|
||||||
import { ManifestDto } from "./manifest.dto";
|
import { ManifestDto } from "./manifest.dto";
|
||||||
|
|
||||||
@ApiTags("manifest")
|
@ApiTags("manifest")
|
||||||
@@ -10,6 +11,7 @@ export class ManifestController {
|
|||||||
constructor(private readonly config: ConfigService<AppConfig, true>) {}
|
constructor(private readonly config: ConfigService<AppConfig, true>) {}
|
||||||
|
|
||||||
@Get("manifest.json")
|
@Get("manifest.json")
|
||||||
|
@Public()
|
||||||
// Clients cache the manifest themselves; the browser just revalidates it (ETag)
|
// Clients cache the manifest themselves; the browser just revalidates it (ETag)
|
||||||
@Header("Cache-Control", "no-cache")
|
@Header("Cache-Control", "no-cache")
|
||||||
@ApiOperation({ summary: "Public client configuration and app version" })
|
@ApiOperation({ summary: "Public client configuration and app version" })
|
||||||
@@ -18,6 +20,7 @@ export class ManifestController {
|
|||||||
return {
|
return {
|
||||||
name: this.config.get("APP_NAME"),
|
name: this.config.get("APP_NAME"),
|
||||||
version: this.config.get("APP_VERSION"),
|
version: this.config.get("APP_VERSION"),
|
||||||
|
auth: { enabled: this.config.get("AUTH_ENABLED") },
|
||||||
runLogs: {
|
runLogs: {
|
||||||
dataLimits: {
|
dataLimits: {
|
||||||
bytes: this.config.get("RUN_LOG_DATA_COLLAPSE_BYTES"),
|
bytes: this.config.get("RUN_LOG_DATA_COLLAPSE_BYTES"),
|
||||||
|
|||||||
@@ -2,13 +2,15 @@ import { ApiProperty } from "@nestjs/swagger";
|
|||||||
|
|
||||||
export class RunLogDataLimitsDto {
|
export class RunLogDataLimitsDto {
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: "Data blocks over this many bytes (pretty-printed) start collapsed",
|
description:
|
||||||
|
"Data blocks over this many bytes (pretty-printed) start collapsed",
|
||||||
example: 256,
|
example: 256,
|
||||||
})
|
})
|
||||||
bytes!: number;
|
bytes!: number;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: "Data blocks over this many lines (pretty-printed) start collapsed",
|
description:
|
||||||
|
"Data blocks over this many lines (pretty-printed) start collapsed",
|
||||||
example: 5,
|
example: 5,
|
||||||
})
|
})
|
||||||
lines!: number;
|
lines!: number;
|
||||||
@@ -26,6 +28,13 @@ export class ManifestDto {
|
|||||||
@ApiProperty({ example: "1.4.0" })
|
@ApiProperty({ example: "1.4.0" })
|
||||||
version!: string;
|
version!: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description: "Whether account authentication is enabled.",
|
||||||
|
type: "object",
|
||||||
|
properties: { enabled: { type: "boolean", example: false } },
|
||||||
|
})
|
||||||
|
auth!: { enabled: boolean };
|
||||||
|
|
||||||
@ApiProperty({ type: RunLogsManifestDto })
|
@ApiProperty({ type: RunLogsManifestDto })
|
||||||
runLogs!: RunLogsManifestDto;
|
runLogs!: RunLogsManifestDto;
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,15 @@
|
|||||||
import { Controller, Delete, Get, Post, Req, Res } from "@nestjs/common";
|
import { Controller, Delete, Get, Post, Req, Res } from "@nestjs/common";
|
||||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
import type { Request, Response } from "express";
|
import type { Request, Response } from "express";
|
||||||
import { McpService } from "./mcp.service";
|
import { McpService } from "./mcp.service";
|
||||||
|
|
||||||
@ApiTags("mcp")
|
@ApiTags("mcp")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("mcp")
|
@Controller("mcp")
|
||||||
export class McpController {
|
export class McpController {
|
||||||
constructor(private readonly mcpService: McpService) {}
|
constructor(private readonly mcpService: McpService) {}
|
||||||
|
|||||||
@@ -1343,15 +1343,21 @@ export class McpService {
|
|||||||
"export_e2e_test",
|
"export_e2e_test",
|
||||||
{
|
{
|
||||||
description:
|
description:
|
||||||
"Export a scenario as a standalone, plug-and-play Playwright e2e test project (package.json, playwright.config.ts, test.spec.ts, .env), zipped and returned as base64",
|
"Export one version of a scenario as a standalone, plug-and-play Playwright e2e test project (package.json, playwright.config.ts, test.spec.ts, .env), zipped and returned as base64",
|
||||||
inputSchema: {
|
inputSchema: {
|
||||||
id: z.uuid().describe("Scenario ID to export"),
|
id: z.uuid().describe("Scenario ID to export"),
|
||||||
|
version: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(1)
|
||||||
|
.optional()
|
||||||
|
.describe("Scenario version to export. Defaults to the latest"),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
async ({ id }) => {
|
async ({ id, version }) => {
|
||||||
try {
|
try {
|
||||||
const { filename, buffer } =
|
const { filename, buffer } =
|
||||||
await this.e2eExportService.buildE2eTestPackage(id);
|
await this.e2eExportService.buildE2eTestPackage(id, version);
|
||||||
return {
|
return {
|
||||||
content: [
|
content: [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { EventEmitter } from "node:events";
|
||||||
|
import type { Writable } from "node:stream";
|
||||||
|
|
||||||
|
export interface RawInput extends EventEmitter {
|
||||||
|
isTTY?: boolean;
|
||||||
|
isRaw?: boolean;
|
||||||
|
pause(): this;
|
||||||
|
resume(): this;
|
||||||
|
setRawMode?(mode: boolean): this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read a secret without echoing typed characters to the terminal. */
|
||||||
|
export function readHiddenInput(
|
||||||
|
input: RawInput,
|
||||||
|
output: Pick<Writable, "write">,
|
||||||
|
prompt: string,
|
||||||
|
): Promise<string> {
|
||||||
|
if (!input.isTTY || !input.setRawMode) {
|
||||||
|
return Promise.reject(
|
||||||
|
new Error("This command requires an interactive terminal."),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let value = "";
|
||||||
|
const previousRawMode = input.isRaw ?? false;
|
||||||
|
const finish = (error?: Error) => {
|
||||||
|
input.off("data", onData);
|
||||||
|
input.setRawMode?.(previousRawMode);
|
||||||
|
input.pause();
|
||||||
|
output.write("\n");
|
||||||
|
if (error) reject(error);
|
||||||
|
else resolve(value);
|
||||||
|
};
|
||||||
|
const onData = (chunk: Buffer | string) => {
|
||||||
|
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;
|
||||||
|
for (const character of text) {
|
||||||
|
if (character === "\u0003") {
|
||||||
|
finish(new Error("Input cancelled."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (character === "\r" || character === "\n") {
|
||||||
|
finish();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (character === "\u007f" || character === "\b") {
|
||||||
|
value = value.slice(0, -1);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
value += character;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
output.write(prompt);
|
||||||
|
input.setRawMode(true);
|
||||||
|
input.resume();
|
||||||
|
input.on("data", onData);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,193 @@
|
|||||||
|
import { createInterface } from "node:readline/promises";
|
||||||
|
import type { DataSource, Repository } from "typeorm";
|
||||||
|
import { durationSeconds } from "../common/interval";
|
||||||
|
import type { AppConfig } from "../config/app.config";
|
||||||
|
import { issueJwt, safeUser } from "../auth/jwt.helpers";
|
||||||
|
import { PasswordService } from "../auth/password.service";
|
||||||
|
import { UserEntity } from "../auth/user.entity";
|
||||||
|
|
||||||
|
export interface OperatorCliInput {
|
||||||
|
line(prompt: string): Promise<string>;
|
||||||
|
secret(prompt: string): Promise<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OperatorCliOutput {
|
||||||
|
write(message: string): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OperatorCliContext {
|
||||||
|
dataSource: Pick<DataSource, "getRepository">;
|
||||||
|
config: Pick<
|
||||||
|
AppConfig,
|
||||||
|
"AUTH_ENABLED" | "AUTH_JWT_SECRET" | "AUTH_JWT_EXPIRES_IN"
|
||||||
|
>;
|
||||||
|
passwords: Pick<PasswordService, "hash">;
|
||||||
|
input: OperatorCliInput;
|
||||||
|
output: OperatorCliOutput;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class OperatorCliError extends Error {
|
||||||
|
constructor(message: string) {
|
||||||
|
super(message);
|
||||||
|
this.name = "OperatorCliError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const USAGE = `Usage:
|
||||||
|
node dist/cli.js user:create
|
||||||
|
node dist/cli.js user:get <username>
|
||||||
|
node dist/cli.js user:delete <username>
|
||||||
|
node dist/cli.js user:token <username> [duration]
|
||||||
|
|
||||||
|
Durations use seconds, minutes, hours, or days (for example: 30m, 1h, 7d).`;
|
||||||
|
|
||||||
|
function validateUsername(raw: string): string {
|
||||||
|
const username = raw.trim();
|
||||||
|
if (!username) throw new OperatorCliError("Username cannot be empty.");
|
||||||
|
if (username.length > 250) {
|
||||||
|
throw new OperatorCliError("Username must be 250 characters or fewer.");
|
||||||
|
}
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkEnabled(context: OperatorCliContext): void {
|
||||||
|
if (!context.config.AUTH_ENABLED) {
|
||||||
|
throw new OperatorCliError(
|
||||||
|
"Operator account commands require AUTH_ENABLED=true.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireArguments(args: string[], min: number, max: number): void {
|
||||||
|
if (args.length < min || args.length > max) {
|
||||||
|
throw new OperatorCliError(USAGE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeUserJson(user: UserEntity): string {
|
||||||
|
return JSON.stringify(safeUser(user), null, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUsernameUniqueError(error: unknown): boolean {
|
||||||
|
if (!error || typeof error !== "object") return false;
|
||||||
|
const message = String(error);
|
||||||
|
return (
|
||||||
|
message.includes("SQLITE_CONSTRAINT_UNIQUE") ||
|
||||||
|
message.includes("UNIQUE constraint failed: users.username")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createUser(
|
||||||
|
users: Repository<UserEntity>,
|
||||||
|
context: OperatorCliContext,
|
||||||
|
): Promise<void> {
|
||||||
|
const username = validateUsername(await context.input.line("Username: "));
|
||||||
|
if (await users.findOneBy({ username })) {
|
||||||
|
throw new OperatorCliError(`Username "${username}" already exists.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const password = await context.input.secret("Password: ");
|
||||||
|
if (!password) throw new OperatorCliError("Password cannot be empty.");
|
||||||
|
if (password.length > 1024) {
|
||||||
|
throw new OperatorCliError("Password must be 1024 characters or fewer.");
|
||||||
|
}
|
||||||
|
const confirmation = await context.input.secret("Confirm password: ");
|
||||||
|
if (password !== confirmation) {
|
||||||
|
throw new OperatorCliError("Passwords do not match.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const passwordHash = await context.passwords.hash(password);
|
||||||
|
try {
|
||||||
|
const user = await users.save(users.create({ username, passwordHash }));
|
||||||
|
context.output.write(`Created user ${JSON.stringify(user.username)}.\n`);
|
||||||
|
} catch (error) {
|
||||||
|
if (isUsernameUniqueError(error)) {
|
||||||
|
throw new OperatorCliError(`Username "${username}" already exists.`);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function findUser(
|
||||||
|
users: Repository<UserEntity>,
|
||||||
|
username: string,
|
||||||
|
): Promise<UserEntity> {
|
||||||
|
const user = await users.findOneBy({ username: validateUsername(username) });
|
||||||
|
if (!user) throw new OperatorCliError("No account found for that username.");
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function runOperatorCommand(
|
||||||
|
args: string[],
|
||||||
|
context: OperatorCliContext,
|
||||||
|
): Promise<void> {
|
||||||
|
const [command, ...commandArgs] = args;
|
||||||
|
if (command === "--help" || command === "-h") {
|
||||||
|
context.output.write(USAGE + "\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
checkEnabled(context);
|
||||||
|
|
||||||
|
const users = context.dataSource.getRepository(UserEntity);
|
||||||
|
switch (command) {
|
||||||
|
case "user:create":
|
||||||
|
requireArguments(commandArgs, 0, 0);
|
||||||
|
await createUser(users, context);
|
||||||
|
return;
|
||||||
|
case "user:get": {
|
||||||
|
requireArguments(commandArgs, 1, 1);
|
||||||
|
const user = await findUser(users, commandArgs[0]);
|
||||||
|
context.output.write(safeUserJson(user) + "\n");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case "user:delete": {
|
||||||
|
requireArguments(commandArgs, 1, 1);
|
||||||
|
const user = await findUser(users, commandArgs[0]);
|
||||||
|
await users.remove(user);
|
||||||
|
context.output.write(`Deleted user ${JSON.stringify(user.username)}.\n`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case "user:token": {
|
||||||
|
requireArguments(commandArgs, 1, 2);
|
||||||
|
const user = await findUser(users, commandArgs[0]);
|
||||||
|
const duration = commandArgs[1] ?? context.config.AUTH_JWT_EXPIRES_IN;
|
||||||
|
const expiresIn = durationSeconds(duration);
|
||||||
|
if (expiresIn === null) {
|
||||||
|
throw new OperatorCliError(
|
||||||
|
"Duration must be a positive number followed by s, m, h, or d (for example, 30m).",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const { token, expiresAt } = issueJwt(
|
||||||
|
user.id,
|
||||||
|
expiresIn,
|
||||||
|
context.config.AUTH_JWT_SECRET,
|
||||||
|
);
|
||||||
|
context.output.write(
|
||||||
|
`Bearer token (expires ${expiresAt.toISOString()}):\n${token}\n`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new OperatorCliError(USAGE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createTerminalInput(): OperatorCliInput {
|
||||||
|
return {
|
||||||
|
async line(prompt: string): Promise<string> {
|
||||||
|
const readline = createInterface({
|
||||||
|
input: process.stdin,
|
||||||
|
output: process.stdout,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
return await readline.question(prompt);
|
||||||
|
} finally {
|
||||||
|
readline.close();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
secret: (prompt: string) =>
|
||||||
|
import("./hidden-input").then(({ readHiddenInput }) =>
|
||||||
|
readHiddenInput(process.stdin, process.stdout, prompt),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -42,8 +42,16 @@ export class E2eExportService {
|
|||||||
private readonly snippetService: SnippetService,
|
private readonly snippetService: SnippetService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async buildE2eTestPackage(scenarioId: string): Promise<{ filename: string; buffer: Buffer }> {
|
/** Builds the package for the latest version, or `version` when given. */
|
||||||
|
async buildE2eTestPackage(
|
||||||
|
scenarioId: string,
|
||||||
|
version?: number,
|
||||||
|
): Promise<{ filename: string; buffer: Buffer }> {
|
||||||
const scenario = await this.scenarioService.findOne(scenarioId);
|
const scenario = await this.scenarioService.findOne(scenarioId);
|
||||||
|
const content = await this.scenarioService.findVersion(
|
||||||
|
scenarioId,
|
||||||
|
version ?? scenario.version,
|
||||||
|
);
|
||||||
const [credentialMap, snippetMap, attachedFiles] = await Promise.all([
|
const [credentialMap, snippetMap, attachedFiles] = await Promise.all([
|
||||||
this.scenarioService.buildCredentialMap(scenarioId),
|
this.scenarioService.buildCredentialMap(scenarioId),
|
||||||
this.snippetService.buildSnippetMap(),
|
this.snippetService.buildSnippetMap(),
|
||||||
@@ -51,10 +59,10 @@ export class E2eExportService {
|
|||||||
]);
|
]);
|
||||||
const envData = scenario.environment?.data ?? {};
|
const envData = scenario.environment?.data ?? {};
|
||||||
|
|
||||||
const slug = slugify(scenario.name);
|
const slug = `${slugify(content.name)}-v${content.version}`;
|
||||||
const files: Record<string, string | Buffer> = {
|
const files: Record<string, string | Buffer> = {
|
||||||
"package.json": this.buildPackageJson(slug),
|
"package.json": this.buildPackageJson(slug),
|
||||||
"playwright.config.ts": this.buildPlaywrightConfig(scenario.timeoutSeconds),
|
"playwright.config.ts": this.buildPlaywrightConfig(content.timeoutSeconds),
|
||||||
".env": this.buildEnvFile(envData),
|
".env": this.buildEnvFile(envData),
|
||||||
"credentials.json": JSON.stringify(credentialMap, null, 2) + "\n",
|
"credentials.json": JSON.stringify(credentialMap, null, 2) + "\n",
|
||||||
".gitignore": [
|
".gitignore": [
|
||||||
@@ -65,7 +73,7 @@ export class E2eExportService {
|
|||||||
".env",
|
".env",
|
||||||
"credentials.json",
|
"credentials.json",
|
||||||
].join("\n") + "\n",
|
].join("\n") + "\n",
|
||||||
"README.md": this.buildReadme(scenario.name, scenario.description),
|
"README.md": this.buildReadme(content.name, content.version, content.description),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Bundle any files attached to the scenario so getScenarioFiles works offline.
|
// Bundle any files attached to the scenario so getScenarioFiles works offline.
|
||||||
@@ -97,7 +105,7 @@ export class E2eExportService {
|
|||||||
// Bundle only the snippets actually referenced (directly or transitively via
|
// Bundle only the snippets actually referenced (directly or transitively via
|
||||||
// other snippets) by this scenario's steps, as individual .js files under snippets/.
|
// other snippets) by this scenario's steps, as individual .js files under snippets/.
|
||||||
const usedAliases = resolveUsedSnippetAliases(
|
const usedAliases = resolveUsedSnippetAliases(
|
||||||
scenario.steps.map((s) => s.execCode ?? ""),
|
content.steps.map((s) => s.execCode ?? ""),
|
||||||
snippetMap,
|
snippetMap,
|
||||||
);
|
);
|
||||||
const snippetManifest: { alias: string; filename: string }[] = [];
|
const snippetManifest: { alias: string; filename: string }[] = [];
|
||||||
@@ -116,7 +124,7 @@ export class E2eExportService {
|
|||||||
snippetManifest.push({ alias, filename });
|
snippetManifest.push({ alias, filename });
|
||||||
}
|
}
|
||||||
|
|
||||||
files["test.spec.ts"] = this.buildTestSpec(scenario, snippetManifest, fileManifest);
|
files["test.spec.ts"] = this.buildTestSpec(content, snippetManifest, fileManifest);
|
||||||
|
|
||||||
const buffer = await this.zip(files);
|
const buffer = await this.zip(files);
|
||||||
return { filename: `${slug}-e2e-test.zip`, buffer };
|
return { filename: `${slug}-e2e-test.zip`, buffer };
|
||||||
@@ -173,9 +181,9 @@ export default defineConfig({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildReadme(scenarioName: string, description: string | null): string {
|
private buildReadme(scenarioName: string, version: number, description: string | null): string {
|
||||||
const descriptionSection = description?.trim() ? `${description.trim()}\n\n` : "";
|
const descriptionSection = description?.trim() ? `${description.trim()}\n\n` : "";
|
||||||
return `# ${scenarioName} - standalone e2e test
|
return `# ${scenarioName} (v${version}) - standalone e2e test
|
||||||
|
|
||||||
${descriptionSection}## Setup
|
${descriptionSection}## Setup
|
||||||
|
|
||||||
|
|||||||
@@ -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";
|
} from "../code-executor/code-executor.service";
|
||||||
import { ExecContextBuilder } from "../code-executor/exec-context.builder";
|
import { ExecContextBuilder } from "../code-executor/exec-context.builder";
|
||||||
import { traceStorage } from "../common/trace-context";
|
import { traceStorage } from "../common/trace-context";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
import { createAppLogger } from "../common/app-logger";
|
||||||
import {
|
import {
|
||||||
EnvironmentData,
|
EnvironmentData,
|
||||||
EnvironmentEntity,
|
EnvironmentEntity,
|
||||||
@@ -30,6 +30,7 @@ import { SnippetService } from "../snippet/snippet.service";
|
|||||||
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
||||||
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
||||||
import { ScenarioRunEntity } from "./scenario-run.entity";
|
import { ScenarioRunEntity } from "./scenario-run.entity";
|
||||||
|
import { RunEventsService } from "./run-events.service";
|
||||||
import { ScenarioService } from "./scenario.service";
|
import { ScenarioService } from "./scenario.service";
|
||||||
|
|
||||||
interface BrowserHandle {
|
interface BrowserHandle {
|
||||||
@@ -41,7 +42,7 @@ interface BrowserHandle {
|
|||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class ScenarioSchedulerService implements OnModuleInit {
|
export class ScenarioSchedulerService implements OnModuleInit {
|
||||||
private readonly logger = new TraceLogger(ScenarioSchedulerService.name);
|
private readonly logger = createAppLogger(ScenarioSchedulerService.name);
|
||||||
private readonly activeRuns = new Set<string>();
|
private readonly activeRuns = new Set<string>();
|
||||||
private readonly runBrowsers = new Map<string, BrowserHandle>();
|
private readonly runBrowsers = new Map<string, BrowserHandle>();
|
||||||
// Cache credential maps per run (built once when a run starts)
|
// Cache credential maps per run (built once when a run starts)
|
||||||
@@ -80,6 +81,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
|
|||||||
private readonly sessionService: SessionService,
|
private readonly sessionService: SessionService,
|
||||||
private readonly sessionContextService: SessionContextService,
|
private readonly sessionContextService: SessionContextService,
|
||||||
private readonly fileStorageService: FileStorageService,
|
private readonly fileStorageService: FileStorageService,
|
||||||
|
private readonly runEvents: RunEventsService,
|
||||||
configService: ConfigService<AppConfig, true>,
|
configService: ConfigService<AppConfig, true>,
|
||||||
) {
|
) {
|
||||||
this.defaultTraceMode = configService.get("PLAYWRIGHT_TRACE_MODE");
|
this.defaultTraceMode = configService.get("PLAYWRIGHT_TRACE_MODE");
|
||||||
@@ -109,7 +111,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
|
|||||||
this.failRun(
|
this.failRun(
|
||||||
run.id,
|
run.id,
|
||||||
"Run aborted: server restarted and playwright session could not be recovered",
|
"Run aborted: server restarted and playwright session could not be recovered",
|
||||||
),
|
).then(() => this.emitFinished(run.id)),
|
||||||
).pipe(
|
).pipe(
|
||||||
Effect.catchAll((err) =>
|
Effect.catchAll((err) =>
|
||||||
Effect.sync(() =>
|
Effect.sync(() =>
|
||||||
@@ -149,6 +151,48 @@ export class ScenarioSchedulerService implements OnModuleInit {
|
|||||||
this.persistLog(runId, null, "error", reason, "run");
|
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(
|
private persistLog(
|
||||||
runId: string,
|
runId: string,
|
||||||
stepRunId: string | null,
|
stepRunId: string | null,
|
||||||
@@ -214,6 +258,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
|
|||||||
run.status = "in_progress";
|
run.status = "in_progress";
|
||||||
await this.runRepo.save(run);
|
await this.runRepo.save(run);
|
||||||
this.logger.log(`Run #${run.id} → in_progress`);
|
this.logger.log(`Run #${run.id} → in_progress`);
|
||||||
|
await this.emitRunEvent("run.started", run.id);
|
||||||
const credMap = await this.scenarioService
|
const credMap = await this.scenarioService
|
||||||
.buildCredentialMap(run.scenarioId)
|
.buildCredentialMap(run.scenarioId)
|
||||||
.catch(() => ({}) as Record<string, unknown>);
|
.catch(() => ({}) as Record<string, unknown>);
|
||||||
@@ -267,6 +312,7 @@ export class ScenarioSchedulerService implements OnModuleInit {
|
|||||||
run.id,
|
run.id,
|
||||||
`Run setup failed: ${String(err)}`,
|
`Run setup failed: ${String(err)}`,
|
||||||
).catch(() => {});
|
).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}`);
|
await this.failRun(runId, `Unexpected error: ${(err as Error).message}`);
|
||||||
} finally {
|
} finally {
|
||||||
|
await this.emitFinished(runId);
|
||||||
// Before runLogSeq is cleared, so the trace log entry keeps its order
|
// Before runLogSeq is cleared, so the trace log entry keeps its order
|
||||||
await this.saveTrace(runId);
|
await this.saveTrace(runId);
|
||||||
this.activeRuns.delete(runId);
|
this.activeRuns.delete(runId);
|
||||||
|
|||||||
@@ -11,12 +11,19 @@ import {
|
|||||||
Post,
|
Post,
|
||||||
Query,
|
Query,
|
||||||
Res,
|
Res,
|
||||||
|
Sse,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
UploadedFile,
|
UploadedFile,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { FileInterceptor } from "@nestjs/platform-express";
|
import { FileInterceptor } from "@nestjs/platform-express";
|
||||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
import { Response } from "express";
|
import { Response } from "express";
|
||||||
|
import { interval, map, merge, type Observable } from "rxjs";
|
||||||
import type { File as MulterFile } from "multer";
|
import type { File as MulterFile } from "multer";
|
||||||
import { stringify as yamlStringify } from "yaml";
|
import { stringify as yamlStringify } from "yaml";
|
||||||
import { AddScenarioCredentialDto } from "./dto/add-scenario-credential.dto";
|
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 { ExportEntity, ScenarioExportDto } from "./dto/scenario-export.dto";
|
||||||
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
|
import { UpdateScenarioStepDto } from "./dto/update-scenario-step.dto";
|
||||||
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
|
import { UpdateScenarioDto } from "./dto/update-scenario.dto";
|
||||||
|
import { RunEventsService } from "./run-events.service";
|
||||||
import { ScenarioService } from "./scenario.service";
|
import { ScenarioService } from "./scenario.service";
|
||||||
import { E2eExportService } from "./e2e-export.service";
|
import { E2eExportService } from "./e2e-export.service";
|
||||||
|
|
||||||
|
interface SseMessage {
|
||||||
|
type: string;
|
||||||
|
data: object;
|
||||||
|
}
|
||||||
|
|
||||||
@ApiTags("scenarios")
|
@ApiTags("scenarios")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("scenarios")
|
@Controller("scenarios")
|
||||||
export class ScenarioController {
|
export class ScenarioController {
|
||||||
|
private static readonly HEARTBEAT_MS = 25_000;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly scenarioService: ScenarioService,
|
private readonly scenarioService: ScenarioService,
|
||||||
private readonly e2eExportService: E2eExportService,
|
private readonly e2eExportService: E2eExportService,
|
||||||
|
private readonly runEvents: RunEventsService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// ── Scenarios ─────────────────────────────────────────────────────────────
|
// ── Scenarios ─────────────────────────────────────────────────────────────
|
||||||
@@ -49,7 +66,10 @@ export class ScenarioController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post("import")
|
@Post("import")
|
||||||
@ApiOperation({ summary: "Import a scenario from an export payload (single object or array)" })
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
"Import a scenario from an export payload (single object or array)",
|
||||||
|
})
|
||||||
@ApiResponse({ status: 201, description: "Scenario imported" })
|
@ApiResponse({ status: 201, description: "Scenario imported" })
|
||||||
importScenario(@Body() payload: unknown) {
|
importScenario(@Body() payload: unknown) {
|
||||||
return this.scenarioService.importScenario(
|
return this.scenarioService.importScenario(
|
||||||
@@ -73,6 +93,23 @@ export class ScenarioController {
|
|||||||
return this.scenarioService.findAllRuns(query);
|
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")
|
@Get("run-defaults")
|
||||||
@ApiOperation({ summary: "Get server-configured defaults for new runs" })
|
@ApiOperation({ summary: "Get server-configured defaults for new runs" })
|
||||||
@ApiResponse({ status: 200 })
|
@ApiResponse({ status: 200 })
|
||||||
@@ -172,15 +209,19 @@ export class ScenarioController {
|
|||||||
|
|
||||||
@Get(":id/export-e2e")
|
@Get(":id/export-e2e")
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Export a scenario as a standalone, plug-and-play Playwright e2e test (zip)",
|
summary:
|
||||||
|
"Export a scenario as a standalone, plug-and-play Playwright e2e test (zip)",
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 200, description: "Zip archive" })
|
@ApiResponse({ status: 200, description: "Zip archive" })
|
||||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
@ApiResponse({ status: 404, description: "Scenario or version not found" })
|
||||||
async exportE2eTest(
|
async exportE2eTest(
|
||||||
@Param("id", ParseUUIDPipe) id: string,
|
@Param("id", ParseUUIDPipe) id: string,
|
||||||
|
@Query("version", new ParseIntPipe({ optional: true }))
|
||||||
|
version: number | undefined,
|
||||||
@Res() res: Response,
|
@Res() res: Response,
|
||||||
) {
|
) {
|
||||||
const { filename, buffer } = await this.e2eExportService.buildE2eTestPackage(id);
|
const { filename, buffer } =
|
||||||
|
await this.e2eExportService.buildE2eTestPackage(id, version);
|
||||||
res.setHeader("Content-Type", "application/zip");
|
res.setHeader("Content-Type", "application/zip");
|
||||||
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
|
||||||
res.setHeader("Content-Length", buffer.length);
|
res.setHeader("Content-Length", buffer.length);
|
||||||
@@ -237,7 +278,8 @@ export class ScenarioController {
|
|||||||
|
|
||||||
@Get(":id/used-snippets")
|
@Get(":id/used-snippets")
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "List snippets referenced (directly or transitively) by this scenario's steps",
|
summary:
|
||||||
|
"List snippets referenced (directly or transitively) by this scenario's steps",
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 200 })
|
@ApiResponse({ status: 200 })
|
||||||
@ApiResponse({ status: 404, description: "Scenario not found" })
|
@ApiResponse({ status: 404, description: "Scenario not found" })
|
||||||
@@ -342,7 +384,9 @@ export class ScenarioController {
|
|||||||
const fmt = format === "csv" ? "csv" : "md";
|
const fmt = format === "csv" ? "csv" : "md";
|
||||||
const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
|
const content = await this.scenarioService.exportRunLogs(id, runId, fmt);
|
||||||
const contentType =
|
const contentType =
|
||||||
fmt === "csv" ? "text/csv; charset=utf-8" : "text/markdown; charset=utf-8";
|
fmt === "csv"
|
||||||
|
? "text/csv; charset=utf-8"
|
||||||
|
: "text/markdown; charset=utf-8";
|
||||||
const ext = fmt === "csv" ? "csv" : "md";
|
const ext = fmt === "csv" ? "csv" : "md";
|
||||||
res.setHeader("Content-Type", contentType);
|
res.setHeader("Content-Type", contentType);
|
||||||
res.setHeader(
|
res.setHeader(
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { ScenarioCredentialEntity } from "./scenario-credential.entity";
|
|||||||
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
import { ScenarioRunLogEntity } from "./scenario-run-log.entity";
|
||||||
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
import { ScenarioRunStepEntity } from "./scenario-run-step.entity";
|
||||||
import { ScenarioRunEntity } from "./scenario-run.entity";
|
import { ScenarioRunEntity } from "./scenario-run.entity";
|
||||||
|
import { RunEventsService } from "./run-events.service";
|
||||||
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
|
import { ScenarioSchedulerService } from "./scenario-scheduler.service";
|
||||||
import { ScenarioVersionEntity } from "./scenario-version.entity";
|
import { ScenarioVersionEntity } from "./scenario-version.entity";
|
||||||
import { ScenarioStepEntity } from "./scenario-step.entity";
|
import { ScenarioStepEntity } from "./scenario-step.entity";
|
||||||
@@ -43,7 +44,12 @@ import { E2eExportService } from "./e2e-export.service";
|
|||||||
FileModule,
|
FileModule,
|
||||||
],
|
],
|
||||||
controllers: [ScenarioController],
|
controllers: [ScenarioController],
|
||||||
providers: [ScenarioService, ScenarioSchedulerService, E2eExportService],
|
providers: [
|
||||||
|
ScenarioService,
|
||||||
|
ScenarioSchedulerService,
|
||||||
|
E2eExportService,
|
||||||
|
RunEventsService,
|
||||||
|
],
|
||||||
exports: [ScenarioService, E2eExportService],
|
exports: [ScenarioService, E2eExportService],
|
||||||
})
|
})
|
||||||
export class ScenarioModule {}
|
export class ScenarioModule {}
|
||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
OnModuleDestroy,
|
OnModuleDestroy,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import type { Browser, BrowserContext, Page } from "playwright";
|
import type { Browser, BrowserContext, Page } from "playwright";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
import { createAppLogger } from "../common/app-logger";
|
||||||
import { SessionService } from "./session.service";
|
import { SessionService } from "./session.service";
|
||||||
|
|
||||||
export interface SessionHandle {
|
export interface SessionHandle {
|
||||||
@@ -21,7 +21,7 @@ export interface SessionHandle {
|
|||||||
*/
|
*/
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SessionContextService implements OnModuleDestroy {
|
export class SessionContextService implements OnModuleDestroy {
|
||||||
private readonly logger = new TraceLogger(SessionContextService.name);
|
private readonly logger = createAppLogger(SessionContextService.name);
|
||||||
private readonly handles = new Map<string, SessionHandle>();
|
private readonly handles = new Map<string, SessionHandle>();
|
||||||
|
|
||||||
constructor(private readonly sessionService: SessionService) {}
|
constructor(private readonly sessionService: SessionService) {}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Injectable } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { Interval } from "@nestjs/schedule";
|
import { Interval } from "@nestjs/schedule";
|
||||||
import { TraceLogger } from "../common/trace-logger";
|
import { createAppLogger } from "../common/app-logger";
|
||||||
import { AppConfig } from "../config/app.config";
|
import { AppConfig } from "../config/app.config";
|
||||||
import { SessionContextService } from "./session-context.service";
|
import { SessionContextService } from "./session-context.service";
|
||||||
import { SessionService } from "./session.service";
|
import { SessionService } from "./session.service";
|
||||||
@@ -13,7 +13,7 @@ import { SessionService } from "./session.service";
|
|||||||
*/
|
*/
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SessionSchedulerService {
|
export class SessionSchedulerService {
|
||||||
private readonly logger = new TraceLogger(SessionSchedulerService.name);
|
private readonly logger = createAppLogger(SessionSchedulerService.name);
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly sessionService: SessionService,
|
private readonly sessionService: SessionService,
|
||||||
|
|||||||
@@ -8,7 +8,12 @@ import {
|
|||||||
ParseUUIDPipe,
|
ParseUUIDPipe,
|
||||||
Query,
|
Query,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiOperation,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
import { SessionQueryDto } from "./session-query.dto";
|
import { SessionQueryDto } from "./session-query.dto";
|
||||||
import { SessionContextService } from "./session-context.service";
|
import { SessionContextService } from "./session-context.service";
|
||||||
import { SessionService } from "./session.service";
|
import { SessionService } from "./session.service";
|
||||||
@@ -19,6 +24,7 @@ function maskToken(token: string, head = 6, tail = 4): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@ApiTags("sessions")
|
@ApiTags("sessions")
|
||||||
|
@ApiBearerAuth()
|
||||||
@Controller("sessions")
|
@Controller("sessions")
|
||||||
export class SessionController {
|
export class SessionController {
|
||||||
constructor(
|
constructor(
|
||||||
|
|||||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user