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 | ||
|
|
a8d00056ff | ||
|
|
639b80f468 | ||
|
|
718a12c2f4 | ||
|
|
4e55d14599 | ||
|
|
0f84db57f1 | ||
|
|
959b3b70c9 | ||
|
|
2281a8729b | ||
|
|
e3c2c0cebb | ||
|
|
daecf3d539 | ||
|
|
71259bc11d | ||
|
|
d085ea3ded | ||
|
|
1273491eee | ||
|
|
6cba785e2f | ||
|
|
5152fffe82 | ||
|
|
9df8a652dc | ||
|
|
e577ee8683 | ||
|
|
0e998333e0 | ||
|
|
2840df68b2 | ||
|
|
0341fc2201 | ||
|
|
bba6eb2f94 | ||
|
|
531754c3fa | ||
|
|
cafc126d1b | ||
|
|
f24a1b7dd5 | ||
|
|
63c2df96f1 |
No files matched your search
@@ -8,6 +8,19 @@
|
||||
# NODE_ENV=development
|
||||
# PORT=3000
|
||||
|
||||
## Application log output: console (default) or debug (controlled by DEBUG namespaces)
|
||||
# LOG_MODE=console
|
||||
|
||||
## Optional account authentication (disabled unless explicitly enabled)
|
||||
# AUTH_ENABLED=true
|
||||
## Required when AUTH_ENABLED=true. Set a private, high-entropy value outside source control.
|
||||
# AUTH_JWT_SECRET=replace-with-a-private-random-secret
|
||||
## Browser cookie name and default JWT lifetime
|
||||
# AUTH_COOKIE_NAME=liqa_auth
|
||||
# AUTH_JWT_EXPIRES_IN=24h
|
||||
## Expired logout revocations are cleaned at startup and on this cron schedule.
|
||||
# AUTH_REVOKED_TOKEN_CLEANUP_CRON=0 3 * * *
|
||||
|
||||
## Origins allowed to call the API cross-origin (comma separated). Default: the
|
||||
## Vite dev server (http://localhost:5173) in development, the compose port
|
||||
## (http://localhost:13000) in production
|
||||
@@ -32,6 +45,11 @@
|
||||
## (traces often reach ~10 MB per run; can be overridden per run in the run modal)
|
||||
# PLAYWRIGHT_TRACE_MODE=off
|
||||
|
||||
## Run log data blocks whose pretty-printed JSON exceeds either limit start
|
||||
## collapsed in the UI (bytes, lines); served to the client via /manifest.json
|
||||
# RUN_LOG_DATA_COLLAPSE_BYTES=256
|
||||
# RUN_LOG_DATA_COLLAPSE_LINES=5
|
||||
|
||||
## Chromium binary to use instead of Playwright's own (not needed in Docker,
|
||||
## which ships Playwright's chromium-headless-shell)
|
||||
# PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
# 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 release
|
||||
# tag push (vX.Y.Z), runs both jobs unconditionally and then builds the Docker
|
||||
# image and pushes it to this Gitea instance's container registry, tagged with
|
||||
# the version and `latest`. The tag must match the root package.json version.
|
||||
#
|
||||
# Needs a repository (or owner) secret REGISTRY_TOKEN: a Gitea access token
|
||||
# with package write access for the repository owner. The registry host is
|
||||
# set explicitly below rather than taken from the server URL, which is the
|
||||
# address the runner was registered with and may be internal-only.
|
||||
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [master]
|
||||
tags: ['v[0-9]+.[0-9]+.[0-9]+']
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
REGISTRY: git.hq.ars9.space
|
||||
|
||||
jobs:
|
||||
# Not needed on tag pushes: server and client always run there
|
||||
changes:
|
||||
if: ${{ !startsWith(github.ref, 'refs/tags/') }}
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
server: ${{ steps.filter.outputs.server }}
|
||||
client: ${{ steps.filter.outputs.client }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dorny/paths-filter@v3
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
server:
|
||||
- 'server/**'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
- '.gitea/workflows/ci.yml'
|
||||
client:
|
||||
- 'client/**'
|
||||
- 'package.json'
|
||||
- 'package-lock.json'
|
||||
- '.gitea/workflows/ci.yml'
|
||||
|
||||
server:
|
||||
needs: changes
|
||||
# changes is skipped on tag pushes, hence !cancelled()
|
||||
if: |
|
||||
!cancelled() &&
|
||||
(startsWith(github.ref, 'refs/tags/') || needs.changes.outputs.server == 'true')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci -w server
|
||||
- name: Lint
|
||||
run: npm run -w server lint -- --max-warnings=0
|
||||
- name: Type-check
|
||||
run: npx tsc --noEmit -p server/tsconfig.json
|
||||
- name: Test
|
||||
run: npm test -w server
|
||||
- name: Build
|
||||
run: npm run -w server build
|
||||
|
||||
client:
|
||||
needs: changes
|
||||
# changes is skipped on tag pushes, hence !cancelled()
|
||||
if: |
|
||||
!cancelled() &&
|
||||
(startsWith(github.ref, 'refs/tags/') || needs.changes.outputs.client == 'true')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci -w client
|
||||
- name: Lint
|
||||
run: npm run -w client lint -- --max-warnings=0
|
||||
- name: Build
|
||||
run: npm run -w client build
|
||||
- name: Install headless Chromium for Storybook tests
|
||||
run: npx playwright install --with-deps --only-shell chromium
|
||||
- name: Storybook tests
|
||||
run: npm run -w client test:storybook
|
||||
|
||||
image:
|
||||
needs: [server, client]
|
||||
if: ${{ !failure() && !cancelled() && startsWith(github.ref, 'refs/tags/') }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Check the tag matches package.json
|
||||
run: |
|
||||
version=$(node -p "require('./package.json').version")
|
||||
if [ "${GITHUB_REF_NAME}" != "v${version}" ]; then
|
||||
echo "tag ${GITHUB_REF_NAME} does not match package.json version ${version}"
|
||||
exit 1
|
||||
fi
|
||||
echo "VERSION=${version}" >> "$GITHUB_ENV"
|
||||
- name: Log in to the registry
|
||||
env:
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
OWNER: ${{ github.repository_owner }}
|
||||
run: |
|
||||
echo "IMAGE=${REGISTRY}/$(echo "${GITHUB_REPOSITORY}" | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_ENV"
|
||||
echo "$REGISTRY_TOKEN" | docker login "$REGISTRY" -u "$OWNER" --password-stdin
|
||||
- name: Build
|
||||
run: docker build --build-arg VERSION="${VERSION}" -t "${IMAGE}:${VERSION}" -t "${IMAGE}:latest" .
|
||||
- name: Push
|
||||
run: |
|
||||
docker push "${IMAGE}:${VERSION}"
|
||||
docker push "${IMAGE}:latest"
|
||||
+124
@@ -2,6 +2,130 @@
|
||||
|
||||
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
|
||||
|
||||
Changes since 1.24.1:
|
||||
|
||||
### Added
|
||||
|
||||
- Large run log data blocks start collapsed behind a "Show data (size, lines)" toggle: data whose pretty-printed JSON is over `RUN_LOG_DATA_COLLAPSE_BYTES` (default 256) bytes or `RUN_LOG_DATA_COLLAPSE_LINES` (default 5) lines. An "Expand data" / "Collapse data" button next to the Logs heading opens or closes all of them.
|
||||
- "Copy logs" button on the run page: copies the currently filtered logs to the clipboard as plain text, with every data block expanded.
|
||||
- `GET /manifest.json`: public client configuration served by the server - the app name and version, and the run log data limits. The UI caches it in `localStorage` and revalidates it on page load and when the tab is refocused after a while.
|
||||
|
||||
### Changed
|
||||
|
||||
- The sidebar footer shows the server's version (from `/manifest.json`); its tooltip suggests reloading the page when it differs from the version the UI was built with.
|
||||
- Run log data blocks are aligned with the context/message column instead of the level column.
|
||||
|
||||
## 1.24.1 - 2026-10-02
|
||||
|
||||
Changes since 1.24.0:
|
||||
|
||||
### Added
|
||||
|
||||
- `context.assert(fn, description, details?)`: optional `details` argument. On failure, the `assertion:fail` log entry stores `{ details, error }` as data (`error` is the exception message when `fn` threw), so large diagnostics such as a response body can stay out of the message. The exported e2e runtime accepts and prints it too.
|
||||
- The "Step N passed" log entry carries the step's return value as data.
|
||||
- File names in the run Artifacts and scenario Files tables link to the file content, opening it in a new tab (shown inline when the browser can display it).
|
||||
|
||||
### Changed
|
||||
|
||||
- For assertion failures, the "Step N failed" and "Snippet X failed" log entries name only the assertion (`Assertion failed: <description>`) instead of repeating the failure details. The step run's description keeps the full message.
|
||||
- Log output shows elapsed time in whole seconds (`+14s`), matching the stored timestamp resolution.
|
||||
|
||||
## 1.24.0 - 2026-10-01
|
||||
|
||||
Changes since 1.23.0:
|
||||
|
||||
### Added
|
||||
|
||||
- Code reference in the UI: a (?) button next to the Code label on the step and snippet create/edit pages opens a modal documenting the script runtime - the globals (`context`, `expect`, `console`, and `args` in snippets) and every `context` member with examples, including pitfalls such as awaiting `getStepOutput()` and `assert()`, and `downloadFile()` not sending the browser's cookies.
|
||||
|
||||
### Changed
|
||||
|
||||
- `Modal` UI component: new `size="lg"` for long, document-like content. Dialogs are now capped to the viewport height and their body scrolls, instead of overflowing the screen.
|
||||
|
||||
## 1.23.0 - 2026-10-01
|
||||
|
||||
Changes since 1.22.2:
|
||||
|
||||
### Added
|
||||
|
||||
- Run log entries now carry a `context` (where the message was generated: `step:<N>`, `snippet:<alias>`, `assertion:pass`/`fail`, or `run`) and a `data` field: `context.log`/`warn`/`error` and `console.*` split their arguments so strings join into `message` while object/array arguments are kept separate as `data` (JSON), instead of being `JSON.stringify`'d into the message text.
|
||||
- Added a `debug` log level (`context.debug()`, `console.debug()`), alongside `log`/`warn`/`error`.
|
||||
- New `LogOutput` UI component: a terminal-style log viewer on the run detail page, color-coded by level, with an elapsed-time-since-start column, a context tag, and `data` rendered pretty-printed in a separate block below the message. The full log list is shown (no more pagination), capped to a scrollable block.
|
||||
- Run log CSV/Markdown export (`GET /scenarios/:id/runs/:runId/export`) include the new `context` and `data` columns/blocks; the logs search (`?q=`) also matches `context`.
|
||||
|
||||
## 1.22.2 - 2026-10-01
|
||||
|
||||
Changes since 1.22.1:
|
||||
|
||||
### Added
|
||||
|
||||
- MIT license (`LICENSE`), declared in all `package.json` files and the README.
|
||||
- The Docker image includes the license notices of everything it ships: `scripts/third-party-licenses.mjs` collects the license of every production dependency of the client and server, the Node.js license is added, and the result is served at `/licenses.txt`, linked as "Licenses" in the sidebar footer.
|
||||
- OCI image labels for title, version, license and source; CI passes the version as the `VERSION` build arg.
|
||||
|
||||
### Fixed
|
||||
|
||||
- The Docker image keeps packages' `LICENSE.md`/`NOTICE.md` files, which the 1.22.1 slimming step deleted along with other Markdown files.
|
||||
|
||||
## 1.22.1 - 2026-10-01
|
||||
|
||||
Changes since 1.22.0:
|
||||
|
||||
### Changed
|
||||
|
||||
- The Docker image is about 20% smaller (1.09 GB → 876 MB on disk, 251 MB → 220 MB compressed). Production dependencies and Chromium are installed in a separate stage that drops files nothing loads at runtime (source maps, TypeScript sources and declarations, docs, TypeORM's browser build, better-sqlite3's C sources, Playwright's ffmpeg). The runtime image is `debian:bookworm-slim` with only the `node` binary, so it no longer contains `npm`, `npx`, `yarn` or `corepack`.
|
||||
|
||||
## 1.22.0 - 2026-10-01
|
||||
|
||||
Changes since 1.21.1:
|
||||
|
||||
@@ -4,7 +4,7 @@ liqa is a browser automation and QA service for web applications. It stores **sc
|
||||
|
||||
It is an npm workspace with two packages:
|
||||
|
||||
- `server/` - NestJS API + scheduler + MCP server, SQLite via TypeORM; the schema is managed by migrations in `server/src/database/migrations/` (see "Database migrations" in `docs/development.md`). Any entity change needs a generated migration - `test/migrations.spec.ts` fails otherwise. REST API under `/api/v1`, Swagger UI at `/docs`, MCP at `/mcp`, health at `/health`.
|
||||
- `server/` - NestJS API + scheduler + MCP server, SQLite via TypeORM; the schema is managed by migrations in `server/src/database/migrations/` (see "Database migrations" in `docs/development.md`). Any entity change needs a generated migration - `test/migrations.spec.ts` fails otherwise. REST API under `/api/v1`, Swagger UI at `/docs`, MCP at `/mcp`, health at `/health`, public client configuration at `/manifest.json`.
|
||||
- `client/` - React 19 + Vite SPA (i18n strings in `client/src/i18n/locales/en.json`).
|
||||
|
||||
## Docs
|
||||
@@ -14,6 +14,7 @@ It is an npm workspace with two packages:
|
||||
- [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/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
|
||||
- [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`)
|
||||
@@ -26,6 +27,14 @@ Rebuild and restart: `docker compose up -d --build`. Check with `docker compose
|
||||
|
||||
The live database is `data/liqa.db`. The container applies pending migrations before starting the server, so back it up before deploying a release with new migrations.
|
||||
|
||||
## Branching
|
||||
|
||||
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
|
||||
|
||||
Before committing, run and pass all of these (and report the results):
|
||||
@@ -43,14 +52,24 @@ 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`).
|
||||
- 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).
|
||||
2. Run the code quality checks above.
|
||||
When asked to release:
|
||||
|
||||
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.
|
||||
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).
|
||||
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.
|
||||
7. **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.
|
||||
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. **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:
|
||||
|
||||
```bash
|
||||
v=<version>
|
||||
awk -v v="$v" 'index($0, "## " v " ") == 1 {p = 1; print; next} p && /^## / {exit} p' CHANGELOG.md \
|
||||
| git tag -a "v$v" --cleanup=whitespace -F -
|
||||
```
|
||||
|
||||
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. **Ask the user whether to rebuild and restart the docker compose containers** (`docker compose up -d --build`); don't do it without confirmation.
|
||||
+72
-7
@@ -28,8 +28,70 @@ COPY server/tsconfig*.json ./server/
|
||||
COPY server/src ./server/src
|
||||
RUN npm run -w server build
|
||||
|
||||
# ── Runtime dependencies ──────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS runtime-deps
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
COPY server/package.json ./server/
|
||||
|
||||
# Production dependencies and Playwright's headless-only Chromium build,
|
||||
# matching the installed Playwright version. All browser launches are
|
||||
# headless, so the full desktop Chromium (GTK, Mesa/LLVM, icon themes) isn't
|
||||
# needed, and neither is ffmpeg (only used for video recording).
|
||||
#
|
||||
# Then drop what nothing loads at runtime: source maps, TypeScript sources and
|
||||
# declarations, docs (but not license files), TypeORM's browser build and
|
||||
# better-sqlite3's C sources (the addon is already compiled).
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||
RUN npm ci --omit=dev -w server \
|
||||
&& npx playwright install --only-shell chromium \
|
||||
&& rm -rf /ms-playwright/ffmpeg-* \
|
||||
&& find node_modules -type f \( \
|
||||
-name '*.map' -o -name '*.ts' -o -name '*.mts' -o -name '*.cts' \
|
||||
-o \( \( -iname '*.md' -o -iname '*.markdown' \) \
|
||||
! -iname 'licen[cs]e*' ! -iname 'notice*' ! -iname 'copying*' \) \
|
||||
\) -delete \
|
||||
&& rm -rf node_modules/typeorm/browser \
|
||||
node_modules/better-sqlite3/deps \
|
||||
node_modules/better-sqlite3/src
|
||||
|
||||
# ── License notices ───────────────────────────────────────────────────────────
|
||||
# One file with the project's LICENSE and the license of everything the image
|
||||
# ships: the production dependencies of both workspaces (the client's are
|
||||
# bundled into its build, so their license files aren't in the image
|
||||
# otherwise) and the Node.js binary, whose LICENSE the node image doesn't
|
||||
# include.
|
||||
FROM node:24-slim AS licenses
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json LICENSE ./
|
||||
COPY client/package.json ./client/
|
||||
COPY server/package.json ./server/
|
||||
COPY scripts/third-party-licenses.mjs ./scripts/
|
||||
RUN npm ci --omit=dev --ignore-scripts \
|
||||
&& node scripts/third-party-licenses.mjs > licenses.txt \
|
||||
&& node -e ' \
|
||||
const url = `https://raw.githubusercontent.com/nodejs/node/v${process.versions.node}/LICENSE`; \
|
||||
fetch(url).then(async (r) => { \
|
||||
if (!r.ok) throw new Error(`${url}: ${r.status}`); \
|
||||
const rule = "-".repeat(79); \
|
||||
process.stdout.write(`\n${rule}\n\nnode@${process.versions.node}\nLicense: MIT\n\n${(await r.text()).trim()}\n`); \
|
||||
}).catch((e) => { console.error(e.message); process.exit(1); });' >> licenses.txt
|
||||
|
||||
# ── Runtime ───────────────────────────────────────────────────────────────────
|
||||
FROM node:24-slim AS runtime
|
||||
# Plain Debian with just the node binary: npm, yarn, corepack and the C
|
||||
# headers that come with the node image aren't needed to run the app.
|
||||
FROM debian:bookworm-slim AS runtime
|
||||
|
||||
# Set by CI from the root package.json version
|
||||
ARG VERSION=dev
|
||||
LABEL org.opencontainers.image.title="liqa" \
|
||||
org.opencontainers.image.version="${VERSION}" \
|
||||
org.opencontainers.image.licenses="MIT" \
|
||||
org.opencontainers.image.source="https://git.hq.ars9.space/ars9/liqa"
|
||||
|
||||
# Runtime only: in the build stages it would make npm ci skip devDependencies
|
||||
ENV NODE_ENV=production
|
||||
@@ -63,22 +125,25 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
libxrandr2 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=runtime-deps /usr/local/bin/node /usr/local/bin/node
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
COPY server/package.json ./server/
|
||||
|
||||
# Playwright's headless-only Chromium build, matching the installed Playwright
|
||||
# version. All browser launches are headless, so the full desktop Chromium
|
||||
# (GTK, Mesa/LLVM, icon themes) isn't needed.
|
||||
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright
|
||||
RUN npm ci --omit=dev -w server \
|
||||
&& npx playwright install --only-shell chromium \
|
||||
&& npm cache clean --force
|
||||
COPY --from=runtime-deps /ms-playwright /ms-playwright
|
||||
COPY --from=runtime-deps /app/node_modules ./node_modules
|
||||
|
||||
COPY --from=server-build /app/server/dist ./dist
|
||||
COPY --from=client-build /app/client/dist ./client
|
||||
|
||||
# The project's license, and every shipped component's license notices (also
|
||||
# served by the app at /licenses.txt)
|
||||
COPY LICENSE ./
|
||||
COPY --from=licenses /app/licenses.txt ./client/licenses.txt
|
||||
|
||||
# Serve the built client at / (see server/src/common/client-static.ts)
|
||||
ENV CLIENT_DIR=client
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Andrii Arsenin
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -12,8 +12,24 @@ docker compose up -d --build
|
||||
|
||||
No configuration is needed: every setting has a default. To override one, copy `.env.example` to `.env` and uncomment it.
|
||||
|
||||
Authentication is **disabled by default**. To enable operator-managed accounts, set `AUTH_ENABLED=true` and provide a private `AUTH_JWT_SECRET`; then rebuild/restart the service and provision an account with the CLI. See [operator authentication](docs/development.md#operator-account-commands) for setup and browser/API usage. Existing deployments remain unauthenticated until explicitly enabled.
|
||||
|
||||
Everything is served from one container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`. Data is kept in `./data/`.
|
||||
|
||||
To see it work, import and run the [self-test example](examples/self-test/): a scenario that tests liqa itself using an environment, a credential and snippets.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
To install liqa from the published image, without cloning this repo:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://git.hq.ars9.space/ars9/liqa/raw/branch/master/scripts/install.sh | bash
|
||||
```
|
||||
|
||||
This asks for an install directory, a port and a version (latest by default), then writes a `compose.yaml` and a `data/` directory there. Start it with `docker compose up -d` in that directory.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
@@ -37,4 +53,13 @@ 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/mcp.md](docs/mcp.md) - MCP tool reference
|
||||
- [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
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE) © 2026 Andrii Arsenin
|
||||
|
||||
Third-party packages keep their own licenses. The Docker image includes all their notices, and the app serves them at `/licenses.txt` (linked as "Licenses" in the sidebar footer). See [docs/development.md](docs/development.md#licenses).
|
||||
@@ -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,197 @@
|
||||
import { useState } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, userEvent, within } from 'storybook/test';
|
||||
import { LogOutput, type LogOutputEntry } from '../../src/ui/LogOutput/LogOutput';
|
||||
import { formatLogText } from '../../src/ui/LogOutput/logText';
|
||||
|
||||
const meta: Meta<typeof LogOutput> = {
|
||||
title: 'UI/LogOutput',
|
||||
component: LogOutput,
|
||||
tags: ['autodocs'],
|
||||
parameters: { layout: 'padded' },
|
||||
};
|
||||
export default meta;
|
||||
|
||||
type Story = StoryObj<typeof LogOutput>;
|
||||
|
||||
const secondsAgo = (n: number) => new Date(Date.now() - n * 1000).toISOString();
|
||||
|
||||
export const Default: Story = {
|
||||
args: {
|
||||
startTime: secondsAgo(60),
|
||||
entries: [
|
||||
{
|
||||
id: 0,
|
||||
level: 'debug',
|
||||
context: 'step:1',
|
||||
message: 'Resolved credential alias "sdJwtKey" to a file credential',
|
||||
createdAt: secondsAgo(61),
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
level: 'log',
|
||||
context: 'step:1',
|
||||
message: 'Step 1 started: Login with PKCS',
|
||||
createdAt: secondsAgo(60),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
level: 'log',
|
||||
context: 'snippet:loginWithPkcs',
|
||||
message: 'Snippet "loginWithPkcs" started',
|
||||
createdAt: secondsAgo(58),
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
level: 'log',
|
||||
context: 'snippet:loginWithPkcs',
|
||||
message: 'Saved credential as run file:',
|
||||
data: JSON.stringify({
|
||||
id: '181d8ae2-4aee-4f33-a657-210efe7fe668',
|
||||
name: 'credential.sd-jwt',
|
||||
mimeType: 'application/octet-stream',
|
||||
size: 1657,
|
||||
sha256: '9c4226999c700a39bda30279907e4479a5b3920ccde5c75771ea0e264c638c0',
|
||||
path: 'data/files/18/181d/181d8ae2-4aee-4f33-a657-210efe7fe668',
|
||||
}),
|
||||
createdAt: secondsAgo(57),
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
level: 'log',
|
||||
context: 'snippet:loginWithPkcs',
|
||||
message: 'Navigating to ID login: https://id.example.com',
|
||||
createdAt: secondsAgo(57),
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
level: 'log',
|
||||
context: 'assertion:pass',
|
||||
message: 'Assertion passed: page must have redirected to cabinet URL',
|
||||
createdAt: secondsAgo(40),
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
level: 'warn',
|
||||
context: 'snippet:loginWithPkcs',
|
||||
message: 'Retrying file upload after a transient error',
|
||||
createdAt: secondsAgo(39),
|
||||
},
|
||||
{
|
||||
id: 7,
|
||||
level: 'log',
|
||||
context: 'step:1',
|
||||
message: 'Step 1 passed',
|
||||
createdAt: secondsAgo(30),
|
||||
},
|
||||
{
|
||||
id: 8,
|
||||
level: 'error',
|
||||
context: 'assertion:fail',
|
||||
message: 'Assertion failed: Document validation must pass (got 422)',
|
||||
createdAt: secondsAgo(10),
|
||||
},
|
||||
{
|
||||
id: 9,
|
||||
level: 'error',
|
||||
context: 'step:2',
|
||||
message: 'Step 2 failed: Document validation must pass (got 422)',
|
||||
createdAt: secondsAgo(9),
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export const Scrollable: Story = {
|
||||
args: {
|
||||
maxHeight: 160,
|
||||
startTime: secondsAgo(60),
|
||||
entries: Array.from({ length: 30 }, (_, i) => ({
|
||||
id: i,
|
||||
level: (['log', 'log', 'log', 'warn', 'error'] as const)[i % 5],
|
||||
context: `step:${Math.floor(i / 6) + 1}`,
|
||||
message: `Log entry ${i + 1}`,
|
||||
createdAt: secondsAgo(60 - i * 2),
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
const largeDataEntries: LogOutputEntry[] = [
|
||||
{
|
||||
id: 0,
|
||||
level: 'log',
|
||||
context: 'step:1',
|
||||
message: 'Small payload:',
|
||||
data: JSON.stringify({ status: 200 }),
|
||||
createdAt: secondsAgo(20),
|
||||
},
|
||||
{
|
||||
id: 1,
|
||||
level: 'log',
|
||||
context: 'step:1',
|
||||
message: 'Large payload:',
|
||||
data: JSON.stringify({
|
||||
user: { id: 42, name: 'Jane Doe', roles: ['admin', 'qa'] },
|
||||
token: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI0MiJ9',
|
||||
}),
|
||||
createdAt: secondsAgo(18),
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
level: 'warn',
|
||||
context: 'step:2',
|
||||
message: 'Another large payload:',
|
||||
data: JSON.stringify(Array.from({ length: 8 }, (_, i) => ({ row: i }))),
|
||||
createdAt: secondsAgo(10),
|
||||
},
|
||||
];
|
||||
|
||||
function LargeDataLog() {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-start' }}>
|
||||
<button type="button" onClick={() => setExpanded((v) => !v)}>
|
||||
{expanded ? 'Collapse all' : 'Expand all'}
|
||||
</button>
|
||||
<LogOutput startTime={secondsAgo(20)} entries={largeDataEntries} dataExpanded={expanded} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Data blocks over the default limits (256 bytes, 5 lines) start collapsed. */
|
||||
export const LargeData: Story = {
|
||||
render: () => <LargeDataLog />,
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
// Data blocks are syntax-highlighted into separate tokens, so check the log's text
|
||||
const log = canvas.getByRole('log');
|
||||
// Only the small payload is visible initially
|
||||
await expect(log).toHaveTextContent('"status": 200');
|
||||
await expect(log).not.toHaveTextContent('Jane Doe');
|
||||
const toggles = canvas.getAllByRole('button', { name: /^Show data/ });
|
||||
await expect(toggles).toHaveLength(2);
|
||||
|
||||
await userEvent.click(toggles[0]);
|
||||
await expect(log).toHaveTextContent('Jane Doe');
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Hide data' }));
|
||||
await expect(log).not.toHaveTextContent('Jane Doe');
|
||||
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Expand all' }));
|
||||
await expect(log).toHaveTextContent('Jane Doe');
|
||||
await expect(canvas.getAllByRole('button', { name: 'Hide data' })).toHaveLength(2);
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Collapse all' }));
|
||||
await expect(log).not.toHaveTextContent('Jane Doe');
|
||||
|
||||
// The plain-text form always includes every data block
|
||||
const text = formatLogText(largeDataEntries, largeDataEntries[0].createdAt);
|
||||
await expect(text).toContain('[step:1] Large payload:\n {');
|
||||
await expect(text).toContain('"name": "Jane Doe"');
|
||||
},
|
||||
};
|
||||
|
||||
export const Empty: Story = {
|
||||
args: {
|
||||
entries: [],
|
||||
emptyMessage: 'No logs yet.',
|
||||
},
|
||||
};
|
||||
@@ -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();
|
||||
},
|
||||
};
|
||||
@@ -4,13 +4,22 @@ import { expect, userEvent, within } from 'storybook/test';
|
||||
import { Modal } from '../../src/ui/Modal/Modal';
|
||||
import { Button } from '../../src/ui/Button/Button';
|
||||
|
||||
function ModalDemo({ title, body }: { title: string; body: string }) {
|
||||
function ModalDemo({
|
||||
title,
|
||||
body,
|
||||
size,
|
||||
}: {
|
||||
title: string;
|
||||
body: React.ReactNode;
|
||||
size?: 'md' | 'lg';
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<Button onClick={() => setOpen(true)}>Open modal</Button>
|
||||
<Modal
|
||||
open={open}
|
||||
size={size}
|
||||
title={title}
|
||||
onClose={() => setOpen(false)}
|
||||
footer={
|
||||
@@ -61,3 +70,29 @@ export const ClosesOnEscapeAndBackdrop: Story = {
|
||||
await expect(canvas.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const Large: Story = {
|
||||
args: {
|
||||
title: 'Code reference',
|
||||
size: 'lg',
|
||||
body: (
|
||||
<>
|
||||
{Array.from({ length: 60 }, (_, i) => (
|
||||
<p key={i}>Paragraph {i + 1} of a long, document-like modal body.</p>
|
||||
))}
|
||||
</>
|
||||
),
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Open modal' }));
|
||||
const dialog = canvas.getByRole('dialog', { name: 'Code reference' });
|
||||
// The dialog stays within the viewport; its body scrolls instead.
|
||||
await expect(dialog.getBoundingClientRect().height).toBeLessThanOrEqual(window.innerHeight);
|
||||
const body = within(dialog).getByText(
|
||||
'Paragraph 1 of a long, document-like modal body.',
|
||||
).parentElement!;
|
||||
await expect(body.scrollHeight).toBeGreaterThan(body.clientHeight);
|
||||
await expect(within(dialog).getByRole('button', { name: 'Confirm' })).toBeVisible();
|
||||
},
|
||||
};
|
||||
@@ -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);
|
||||
},
|
||||
};
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"name": "liqa-client",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"author": "Andrii Arsenin",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -36,11 +36,19 @@
|
||||
min-height: 100%;
|
||||
}
|
||||
|
||||
.footerButtons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.sideFooter {
|
||||
margin-top: auto;
|
||||
padding: var(--space-3) var(--space-2) var(--space-2);
|
||||
border-top: var(--border-width) solid var(--color-border);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
@@ -52,6 +60,78 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.versionLink {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.versionLink:hover,
|
||||
.versionLink:focus-visible {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.signOut,
|
||||
.expandForSignOut {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
color: var(--color-text-muted);
|
||||
background: transparent;
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.signOut:hover,
|
||||
.expandForSignOut:hover {
|
||||
color: var(--color-text);
|
||||
background: var(--color-secondary);
|
||||
}
|
||||
|
||||
.signOut:focus-visible,
|
||||
.expandForSignOut:focus-visible,
|
||||
.logoutFailure button:focus-visible {
|
||||
outline: 2px solid var(--color-primary-text);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.signOut:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.logoutFailure {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2);
|
||||
color: var(--color-error-fg);
|
||||
background: var(--color-error-bg);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.logoutFailure button {
|
||||
min-height: 32px;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
border: var(--border-width) solid currentColor;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.expandForSignOut {
|
||||
position: fixed;
|
||||
left: 8px;
|
||||
bottom: 12px;
|
||||
z-index: 20;
|
||||
background: var(--color-bg-subtle);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
.navItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+108
-5
@@ -1,11 +1,19 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
|
||||
import { LogOut } from 'lucide-react';
|
||||
import { NavLink, Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import styles from './App.module.css';
|
||||
import { SidePanel, ThemeSwitcher } from './ui';
|
||||
import { NotificationToggle, SidePanel, ThemeSwitcher } from './ui';
|
||||
import liqaLogo from './assets/liqa.svg';
|
||||
import { useManifest } from './hooks/useManifest';
|
||||
import { useRunNotifications } from './hooks/useRunNotifications';
|
||||
import { useAuth } from './auth/useAuth';
|
||||
import { safeReturnTo } from './auth/returnTo';
|
||||
import { AuthStatusPage } from './pages/auth/AuthStatusPage';
|
||||
import { LoginPage } from './pages/auth/LoginPage';
|
||||
import { SignOutControl } from './pages/auth/SignOutControl';
|
||||
|
||||
const EnvironmentsPage = lazy(() =>
|
||||
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
|
||||
@@ -107,10 +115,59 @@ const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator:
|
||||
|
||||
export default function App() {
|
||||
const { t } = useTranslation();
|
||||
const auth = useAuth();
|
||||
const location = useLocation();
|
||||
const [search] = useSearchParams();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [loggingOut, setLoggingOut] = useState(false);
|
||||
const [logoutFailed, setLogoutFailed] = useState(false);
|
||||
const focusSignOut = useRef(false);
|
||||
const { version } = useManifest();
|
||||
const notifications = useRunNotifications();
|
||||
|
||||
useEffect(() => {
|
||||
if (!collapsed && focusSignOut.current) {
|
||||
focusSignOut.current = false;
|
||||
document.querySelector<HTMLButtonElement>('[data-sign-out="true"]')?.focus();
|
||||
}
|
||||
}, [collapsed]);
|
||||
|
||||
async function signOut() {
|
||||
if (loggingOut) return;
|
||||
setLoggingOut(true);
|
||||
setLogoutFailed(false);
|
||||
try {
|
||||
await auth.logout();
|
||||
} catch {
|
||||
setLogoutFailed(true);
|
||||
} finally {
|
||||
setLoggingOut(false);
|
||||
}
|
||||
}
|
||||
|
||||
const onLogin = location.pathname === '/login';
|
||||
if (auth.enabled && (auth.status === 'checking' || auth.status === 'disabled')) {
|
||||
return <AuthStatusPage />;
|
||||
}
|
||||
if (auth.enabled && auth.status === 'error') {
|
||||
return <AuthStatusPage failed onRetry={() => void auth.checkSession()} />;
|
||||
}
|
||||
if (!auth.enabled && onLogin) return <Navigate to="/scenarios" replace />;
|
||||
if (auth.enabled && auth.status === 'authenticated' && onLogin) {
|
||||
return <Navigate to={safeReturnTo(search.get('returnTo')) ?? '/scenarios'} replace />;
|
||||
}
|
||||
if (auth.enabled && auth.status === 'unauthenticated' && !onLogin) {
|
||||
const returnTo =
|
||||
safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios';
|
||||
return <Navigate to={`/login?returnTo=${encodeURIComponent(returnTo)}`} replace />;
|
||||
}
|
||||
if (onLogin) return <LoginPage />;
|
||||
|
||||
return (
|
||||
<div className={styles.shell}>
|
||||
<SidePanel
|
||||
collapsed={collapsed}
|
||||
onCollapsedChange={setCollapsed}
|
||||
header={
|
||||
<div className={styles.header}>
|
||||
<img src={liqaLogo} alt="Liqa" className={styles.brand} />
|
||||
@@ -139,12 +196,58 @@ export default function App() {
|
||||
</nav>
|
||||
|
||||
<div className={styles.sideFooter}>
|
||||
<ThemeSwitcher />
|
||||
<div className={styles.version}>v{__APP_VERSION__}</div>
|
||||
<div className={styles.footerButtons}>
|
||||
<ThemeSwitcher />
|
||||
{notifications && (
|
||||
<NotificationToggle state={notifications.state} onToggle={notifications.toggle} />
|
||||
)}
|
||||
{auth.enabled && auth.status === 'authenticated' && (
|
||||
<SignOutControl
|
||||
pending={loggingOut}
|
||||
failed={logoutFailed}
|
||||
onSignOut={() => void signOut()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.version}>
|
||||
<span
|
||||
title={
|
||||
version !== __APP_VERSION__
|
||||
? t('nav.version_mismatch', { client: __APP_VERSION__ })
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
v{version}
|
||||
</span>{' '}
|
||||
·{' '}
|
||||
<a
|
||||
className={styles.versionLink}
|
||||
href="/licenses.txt"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{t('nav.licenses')}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</SidePanel>
|
||||
|
||||
{collapsed && auth.enabled && auth.status === 'authenticated' && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.expandForSignOut}
|
||||
aria-label={t('auth.show_sign_out')}
|
||||
title={t('auth.show_sign_out')}
|
||||
onClick={() => {
|
||||
focusSignOut.current = true;
|
||||
setCollapsed(false);
|
||||
}}
|
||||
>
|
||||
<LogOut size={18} aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<main className={styles.main}>
|
||||
<Suspense fallback={<p>Loading…</p>}>
|
||||
<Routes>
|
||||
|
||||
@@ -28,7 +28,28 @@ const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/
|
||||
'',
|
||||
);
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
/** URL of the server-sent events stream of run lifecycle events. */
|
||||
export const RUN_EVENTS_URL = `${BASE_URL}/scenarios/runs/events`;
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public readonly status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
quietErrors?: boolean;
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
options: RequestOptions = {},
|
||||
): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
const headers = new Headers(init?.headers);
|
||||
@@ -38,18 +59,26 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
|
||||
res = await fetch(`${BASE_URL}${path}`, {
|
||||
...init,
|
||||
credentials: init?.credentials ?? 'include',
|
||||
headers,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = (err as Error).message || 'Network request failed';
|
||||
emitApiErrorToast(message);
|
||||
if (!options.quietErrors) emitApiErrorToast(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => res.statusText);
|
||||
const message = `${res.status} ${text}`;
|
||||
emitApiErrorToast(message);
|
||||
throw new Error(message);
|
||||
const error = new ApiError(res.status, message);
|
||||
if (res.status === 401 && !path.startsWith('/auth/')) {
|
||||
const event = new CustomEvent('liqa:unauthorized', { cancelable: true });
|
||||
const handled = !window.dispatchEvent(event);
|
||||
if (!handled && !options.quietErrors) emitApiErrorToast(message);
|
||||
} else if (!options.quietErrors && !path.startsWith('/auth/')) {
|
||||
emitApiErrorToast(message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const contentLength = res.headers.get('content-length');
|
||||
if (res.status === 204 || contentLength === '0') return undefined as T;
|
||||
@@ -62,6 +91,30 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
return text as T;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
username: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export const auth = {
|
||||
async login(username: string, password: string): Promise<AuthUser> {
|
||||
const response = await request<{ user: AuthUser }>(
|
||||
'/auth/login',
|
||||
{ method: 'POST', body: JSON.stringify({ username, password }) },
|
||||
{ quietErrors: true },
|
||||
);
|
||||
return response.user;
|
||||
},
|
||||
me(): Promise<AuthUser> {
|
||||
return request('/auth/me', undefined, { quietErrors: true });
|
||||
},
|
||||
logout(): Promise<void> {
|
||||
return request('/auth/logout', { method: 'POST' }, { quietErrors: true });
|
||||
},
|
||||
};
|
||||
|
||||
// ── Credentials ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const credentials = {
|
||||
@@ -123,8 +176,9 @@ export const snippets = {
|
||||
versions(id: string): Promise<SnippetVersion[]> {
|
||||
return request(`/snippets/${id}/versions`);
|
||||
},
|
||||
exportSnippet(id: string): Promise<unknown> {
|
||||
return request(`/snippets/${id}/export`);
|
||||
exportSnippet(id: string, version?: number): Promise<unknown> {
|
||||
const query = version === undefined ? '' : `?version=${version}`;
|
||||
return request(`/snippets/${id}/export${query}`);
|
||||
},
|
||||
};
|
||||
|
||||
@@ -247,7 +301,12 @@ export const scenarios = {
|
||||
},
|
||||
exportScenario(
|
||||
id: string,
|
||||
options: { includeEnvironment: boolean; credentialIds: string[]; snippetIds: string[] } = {
|
||||
options: {
|
||||
includeEnvironment: boolean;
|
||||
credentialIds: string[];
|
||||
snippetIds: string[];
|
||||
version?: number;
|
||||
} = {
|
||||
includeEnvironment: false,
|
||||
credentialIds: [],
|
||||
snippetIds: [],
|
||||
@@ -255,6 +314,9 @@ export const scenarios = {
|
||||
): Promise<string> {
|
||||
const params = new URLSearchParams();
|
||||
params.set('includeEnvironment', String(options.includeEnvironment));
|
||||
if (options.version !== undefined) {
|
||||
params.set('version', String(options.version));
|
||||
}
|
||||
for (const cid of options.credentialIds) {
|
||||
params.append('credentialIds', cid);
|
||||
}
|
||||
@@ -263,8 +325,9 @@ export const scenarios = {
|
||||
}
|
||||
return request(`/scenarios/${id}/export?${params.toString()}`);
|
||||
},
|
||||
exportE2eTestUrl(id: string): string {
|
||||
return `${BASE_URL}/scenarios/${id}/export-e2e`;
|
||||
exportE2eTestUrl(id: string, version?: number): string {
|
||||
const query = version === undefined ? '' : `?version=${version}`;
|
||||
return `${BASE_URL}/scenarios/${id}/export-e2e${query}`;
|
||||
},
|
||||
usedSnippets(id: string): Promise<UsedSnippet[]> {
|
||||
return request(`/scenarios/${id}/used-snippets`);
|
||||
|
||||
+15
-1
@@ -147,7 +147,7 @@ export interface RunDefaults {
|
||||
|
||||
export type RunStepStatus = 'waiting' | 'pending' | 'in_progress' | 'pass' | 'fail' | 'cancelled';
|
||||
|
||||
export type LogLevel = 'log' | 'warn' | 'error';
|
||||
export type LogLevel = 'debug' | 'log' | 'warn' | 'error';
|
||||
|
||||
export interface ScenarioRun {
|
||||
id: string;
|
||||
@@ -189,7 +189,11 @@ export interface ScenarioRunLog {
|
||||
runId: string;
|
||||
stepRunId: string | null;
|
||||
level: LogLevel;
|
||||
/** Where the message was generated, e.g. "step:2", "snippet:login", "assertion:pass". */
|
||||
context: string | null;
|
||||
message: string;
|
||||
/** JSON payload attached to the message (e.g. a created file's metadata), as a raw string. */
|
||||
data: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
@@ -230,3 +234,13 @@ export interface ImportedItem {
|
||||
export interface ImportResult {
|
||||
imported: ImportedItem[];
|
||||
}
|
||||
|
||||
/** Run lifecycle event pushed by the server on `GET /scenarios/runs/events`. */
|
||||
export interface RunEvent {
|
||||
type: 'run.started' | 'run.finished';
|
||||
runId: string;
|
||||
scenarioId: string;
|
||||
scenarioName: string;
|
||||
status: ScenarioRunStatus;
|
||||
at: string;
|
||||
}
|
||||
@@ -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,20 @@
|
||||
.helpButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2px;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: none;
|
||||
color: var(--color-text-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.helpButton:hover {
|
||||
color: var(--color-primary);
|
||||
}
|
||||
|
||||
.helpButton:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.35);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CircleHelp, X } from 'lucide-react';
|
||||
import { Modal, Button, MarkdownContent } from '../../ui';
|
||||
import content from './code-help.md?raw';
|
||||
import styles from './CodeHelpModal.module.css';
|
||||
|
||||
export interface CodeHelpModalProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
/** Reference for the script runtime (`context`, `expect`, ...) available to step and snippet code. */
|
||||
export function CodeHelpModal({ open, onClose }: CodeHelpModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
size="lg"
|
||||
title={t('code_help.title')}
|
||||
onClose={onClose}
|
||||
footer={
|
||||
<Button variant="secondary" onClick={onClose}>
|
||||
<X size={14} />
|
||||
{t('code_help.close')}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<MarkdownContent content={content} />
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** A (?) button that opens the {@link CodeHelpModal}; place it next to a code field label. */
|
||||
export function CodeHelpButton() {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.helpButton}
|
||||
onClick={() => setOpen(true)}
|
||||
aria-label={t('code_help.open')}
|
||||
title={t('code_help.open')}
|
||||
>
|
||||
<CircleHelp size={16} />
|
||||
</button>
|
||||
<CodeHelpModal open={open} onClose={() => setOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
Step code and snippet code are the **body of an async function**. Use `await` freely; whatever you `return` becomes the step (or snippet) output.
|
||||
|
||||
```js
|
||||
async (context) => {
|
||||
// your code here
|
||||
}
|
||||
```
|
||||
|
||||
All steps of a run share one browser, one browser context and one page, so state carries over from step to step: the current URL, cookies, local storage, open dialogs.
|
||||
|
||||
A step **passes** when its code returns, and **fails** when it throws or exceeds its timeout. When a step fails, the remaining steps are cancelled, and a screenshot and the page HTML are saved to the run's files.
|
||||
|
||||
## Globals
|
||||
|
||||
| Name | Description |
|
||||
| --- | --- |
|
||||
| `context` | The run context, described below. |
|
||||
| `expect` | Playwright's [`expect`](https://playwright.dev/docs/test-assertions), with auto-retrying web assertions. |
|
||||
| `console` | Writes to the run log: `log`/`info` → `log`, plus `warn`, `error` and `debug`. |
|
||||
| `args` | **Snippets only.** The extra arguments passed to `context.runSnippet(name, ...args)`. |
|
||||
|
||||
Code runs in the server process with Node.js. It is trusted code, not sandboxed.
|
||||
|
||||
## Browser
|
||||
|
||||
### `context.page`
|
||||
|
||||
The Playwright [`Page`](https://playwright.dev/docs/api/class-page) of the run.
|
||||
|
||||
```js
|
||||
await context.page.goto(context.getEnv("base_url"));
|
||||
await context.page.getByRole("button", { name: "Sign in" }).click();
|
||||
await expect(context.page.locator("h1")).toHaveText("Dashboard");
|
||||
```
|
||||
|
||||
### `context.browser`
|
||||
|
||||
The Playwright [`BrowserContext`](https://playwright.dev/docs/api/class-browsercontext) the page belongs to. Use it for cookies, storage state, extra pages and HTTP requests that share the browser's cookies.
|
||||
|
||||
```js
|
||||
const cookies = await context.browser.cookies();
|
||||
const res = await context.browser.request.get(context.getEnv("api_url") + "/me");
|
||||
```
|
||||
|
||||
### `context.dumpDom(selector?)` → `Promise<DomNode>`
|
||||
|
||||
Returns a simplified tree of the live DOM, starting at `selector` (default `"body"`). Decorative and layout elements are filtered out. The tree keeps landmarks, interactive elements, and elements with `role`, `data-testid`, `data-qa`, `data-action` or `data-element-id`. Each node has `tag` and `children`, plus `role`, `testid`, `id`, `name`, `type`, `text`, `href`, `checked`, `disabled`, etc. when they are present. This is useful for finding selectors without a screenshot.
|
||||
|
||||
If nothing matches `selector`, it returns a node with `tag: "ERROR"` instead of throwing.
|
||||
|
||||
```js
|
||||
context.log("Login form:", await context.dumpDom("form"));
|
||||
```
|
||||
|
||||
## Environment
|
||||
|
||||
### `context.env`
|
||||
|
||||
A copy of the selected environment's key/value map, `{}` when there is none. A missing key reads as `undefined`.
|
||||
|
||||
### `context.getEnv(key)` → `string`
|
||||
|
||||
Returns the environment value for `key`, and **throws** if it is not defined. Prefer it over `context.env[key]` for required settings: the step then fails with a clear message.
|
||||
|
||||
```js
|
||||
const baseUrl = context.getEnv("base_url");
|
||||
const locale = context.env.locale ?? "en";
|
||||
```
|
||||
|
||||
## Credentials
|
||||
|
||||
### `context.getCredential(alias)` → `unknown`
|
||||
|
||||
Returns the payload of the credential assigned to this scenario under `alias` (see **Credentials** on the scenario page). JSON data is returned parsed, anything else as a string. **Throws** if no credential has that alias.
|
||||
|
||||
```js
|
||||
const { username, password } = context.getCredential("admin");
|
||||
await context.page.getByLabel("Username").fill(username);
|
||||
await context.page.getByLabel("Password").fill(password);
|
||||
```
|
||||
|
||||
## Step outputs
|
||||
|
||||
### `context.getStepOutput(order)` → `Promise<unknown>`
|
||||
|
||||
Returns the output (the return value) of another step in the same run. **It is async, so `await` it.**
|
||||
|
||||
- A positive `order` is absolute: `1` is the first step.
|
||||
- A negative `order` is relative: `-1` is the previous step.
|
||||
|
||||
Returns `null` if that step does not exist, has not run, or returned nothing. A step's output is stored as JSON, so only JSON-serializable values come back as they were returned (no functions, `Date` becomes a string, Playwright objects are not usable).
|
||||
|
||||
```js
|
||||
// step 2
|
||||
return { orderId: await context.page.locator("#order-id").textContent() };
|
||||
|
||||
// step 3
|
||||
const { orderId } = await context.getStepOutput(-1);
|
||||
```
|
||||
|
||||
## Logging
|
||||
|
||||
### `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`, `context.debug(...args)`
|
||||
|
||||
Write an entry with that level to the run log. `console.*` does the same. Strings, numbers and booleans are joined with spaces into the message. Objects and arrays are kept separate as structured **data**, shown pretty-printed under the message: one object is stored as is, several are stored as an array.
|
||||
|
||||
```js
|
||||
context.log("Created user", user.id, user); // message "Created user 42", data = user
|
||||
```
|
||||
|
||||
Every entry is tagged with where it came from: `step:<N>`, or `snippet:<alias>` while a snippet runs.
|
||||
|
||||
## Assertions
|
||||
|
||||
### `context.assert(fn, description, details?)` → `Promise<void>`
|
||||
|
||||
Runs `fn` (sync or async) and requires it to return exactly `true`.
|
||||
|
||||
- On success, it logs `description` (tagged `assertion:pass`).
|
||||
- If `fn` returns anything else or throws, it logs `Assertion failed: <description>` as an error (tagged `assertion:fail`) and throws, which fails the step. The entry's data holds `details` (if given) and the exception message as `error` (if `fn` threw).
|
||||
|
||||
Await it, or a failure will not stop the step.
|
||||
|
||||
```js
|
||||
await context.assert(
|
||||
async () => (await context.page.locator(".cart-item").count()) === 3,
|
||||
"Cart contains 3 items",
|
||||
);
|
||||
```
|
||||
|
||||
Pass large diagnostics (e.g. a response body) as `details` rather than in `description`, so the message stays short:
|
||||
|
||||
```js
|
||||
await context.assert(() => response.ok(), "Validation must pass", {
|
||||
status: response.status(),
|
||||
body: await response.json(),
|
||||
});
|
||||
```
|
||||
|
||||
Use `expect` instead for assertions that wait and retry until the page matches, e.g. `await expect(locator).toBeVisible()`.
|
||||
|
||||
## Snippets
|
||||
|
||||
### `context.runSnippet(name, ...args)` → `Promise<unknown>`
|
||||
|
||||
Runs a stored snippet with the same `context` (same page, environment and credentials) and returns the snippet's return value. Extra arguments are available inside the snippet as `args`.
|
||||
|
||||
- `name` is the snippet alias, which runs its latest version.
|
||||
- `alias@<version>` (e.g. `login@3`) pins a specific version.
|
||||
|
||||
Start, finish and failure are logged. If the snippet throws, the error propagates and fails the calling step unless you catch it. Snippets can call other snippets.
|
||||
|
||||
```js
|
||||
// step code
|
||||
const user = await context.runSnippet("login", "admin", { remember: true });
|
||||
|
||||
// snippet "login"
|
||||
const [alias, opts] = args;
|
||||
const { username, password } = context.getCredential(alias);
|
||||
// ...
|
||||
return { username };
|
||||
```
|
||||
|
||||
## Files
|
||||
|
||||
### `context.getScenarioFiles(opts?)` → `Promise<{ items, total }>`
|
||||
|
||||
Lists the files uploaded to this scenario (see **Files** on the scenario page). `opts` takes `limit` and `offset` for paging. Each item has `id`, `name`, `mimeType`, `size`, `sha256` and `path`, the absolute path on the server's disk, which you can pass to Playwright:
|
||||
|
||||
```js
|
||||
const { items } = await context.getScenarioFiles();
|
||||
const doc = items.find((f) => f.name === "contract.pdf");
|
||||
await context.page.locator("input[type=file]").setInputFiles(doc.path);
|
||||
```
|
||||
|
||||
### `context.downloadFile(url, opts?)` → `Promise<FileInfo>`
|
||||
|
||||
Fetches `url` on the server and saves the response as a file of the current run. It returns the same fields as a scenario file (`id`, `name`, `mimeType`, `size`, `sha256`, `path`).
|
||||
|
||||
- `opts`: `method`, `headers`, `body` (a string) and `filename`. Without `filename`, the last segment of the URL path is used, and the MIME type is derived from the file extension.
|
||||
- Redirects are followed. Any final status other than 200 throws. The limits are 100 MB and a 30 s timeout.
|
||||
- `url` may be a `data:` URI (`data:<type>;base64,<data>` or `data:<type>,<percent-encoded>`), which saves content generated in the script without a network request. Pass `filename` in this case.
|
||||
- Only works during a real scenario run. It throws in ad-hoc execution such as the `exec_code` MCP tool.
|
||||
- This is a server-side request: it does **not** send the browser's cookies. Pass them in `headers` if the URL needs a session.
|
||||
|
||||
```js
|
||||
await context.downloadFile(
|
||||
"data:application/json;base64," + btoa(JSON.stringify(report)),
|
||||
{ filename: "report.json" },
|
||||
);
|
||||
```
|
||||
|
||||
## Timeouts
|
||||
|
||||
Each step has its own timeout, or else the scenario's timeout, or else 60 s. The whole run fails once it exceeds the scenario's timeout (600 s by default). That check happens between steps.
|
||||
@@ -6,3 +6,5 @@ export { RunScenarioModal } from './RunScenarioModal';
|
||||
export type { RunScenarioModalProps } from './RunScenarioModal';
|
||||
export { ExportLogsModal } from './ExportLogsModal';
|
||||
export type { ExportLogsModalProps, LogExportFormat } from './ExportLogsModal';
|
||||
export { CodeHelpModal, CodeHelpButton } from './CodeHelpModal';
|
||||
export type { CodeHelpModalProps } from './CodeHelpModal';
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useSyncExternalStore } from 'react';
|
||||
import { getManifest, subscribeManifest, type Manifest } from '../lib/manifest';
|
||||
|
||||
/**
|
||||
* Public client configuration from the server's /manifest.json: the cached
|
||||
* copy (or defaults) at first, updated once the fresh one arrives.
|
||||
*/
|
||||
export function useManifest(): Manifest {
|
||||
return useSyncExternalStore(subscribeManifest, getManifest);
|
||||
}
|
||||
@@ -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": {
|
||||
"button_cancel": "Cancel",
|
||||
"button_confirm": "Confirm",
|
||||
@@ -12,6 +32,11 @@
|
||||
"confirm_remove_credential": "Are you sure you want to remove this credential from scenario?",
|
||||
"save_session": "Save session"
|
||||
},
|
||||
"code_help": {
|
||||
"open": "Code reference",
|
||||
"title": "Code reference",
|
||||
"close": "Close"
|
||||
},
|
||||
"errors": {
|
||||
"not_found": "Not found",
|
||||
"not_found_session": "Session {{id}} does not exist or has been deleted.",
|
||||
@@ -22,6 +47,8 @@
|
||||
"generic": "Something went wrong. Please try again."
|
||||
},
|
||||
"nav": {
|
||||
"licenses": "Licenses",
|
||||
"version_mismatch": "Server version; this page was built for v{{client}}. Reload to update.",
|
||||
"environments": "Environments",
|
||||
"credentials": "Credentials",
|
||||
"snippets": "Snippets",
|
||||
@@ -220,9 +247,7 @@
|
||||
"export_include_snippets": "Include Snippets",
|
||||
"form_timeout": "Scenario Timeout (seconds)",
|
||||
"form_timeout_placeholder": "Default: 600",
|
||||
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)",
|
||||
"field_name": "Name",
|
||||
"field_id": "ID"
|
||||
"form_timeout_hint": "Max seconds for the entire scenario run (default: 600)"
|
||||
},
|
||||
"theme": {
|
||||
"switch_to_light": "Switch to light theme",
|
||||
@@ -230,6 +255,17 @@
|
||||
"light_mode": "Light mode",
|
||||
"dark_mode": "Dark mode"
|
||||
},
|
||||
"notifications": {
|
||||
"enable": "Enable browser notifications for runs",
|
||||
"disable": "Disable browser notifications for runs",
|
||||
"blocked": "Notifications are blocked in your browser settings",
|
||||
"run_started_title": "Run started: {{scenario}}",
|
||||
"run_started_body": "The scenario run is in progress.",
|
||||
"run_pass_title": "Run passed: {{scenario}}",
|
||||
"run_pass_body": "All steps passed.",
|
||||
"run_fail_title": "Run failed: {{scenario}}",
|
||||
"run_fail_body": "The scenario run failed."
|
||||
},
|
||||
"revealable": {
|
||||
"hidden": "Hidden so secrets aren't exposed on screen.",
|
||||
"reveal": "Reveal",
|
||||
@@ -299,6 +335,14 @@
|
||||
"log_message": "Message",
|
||||
"log_time": "Time",
|
||||
"action_download_logs": "Download logs",
|
||||
"action_copy_logs": "Copy logs",
|
||||
"logs_copied": "Logs copied to clipboard",
|
||||
"logs_copy_failed": "Could not copy logs to clipboard",
|
||||
"logs_expand_data": "Expand data",
|
||||
"logs_collapse_data": "Collapse data",
|
||||
"logs_show_data_one": "Show data ({{size}}, {{count}} line)",
|
||||
"logs_show_data_other": "Show data ({{size}}, {{count}} lines)",
|
||||
"logs_hide_data": "Hide data",
|
||||
"action_repeat": "Repeat run",
|
||||
"repeat_no_environment": "The environment used by this run no longer exists",
|
||||
"export_logs_modal_title": "Export logs",
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { DEFAULT_LOG_DATA_LIMITS, type LogDataLimits } from '../ui/LogOutput/logText';
|
||||
|
||||
/** Public client configuration served by the server at /manifest.json. */
|
||||
export interface Manifest {
|
||||
name: string;
|
||||
/** Server version; can differ from the client build's __APP_VERSION__ until the page is reloaded. */
|
||||
version: string;
|
||||
runLogs: {
|
||||
dataLimits: LogDataLimits;
|
||||
};
|
||||
auth: {
|
||||
enabled: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export const DEFAULT_MANIFEST: Manifest = {
|
||||
name: 'liqa',
|
||||
version: __APP_VERSION__,
|
||||
runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS },
|
||||
auth: { enabled: false },
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'liqa-manifest';
|
||||
/** A tab coming back into view refetches the manifest if it is older than this. */
|
||||
const REFRESH_AFTER_MS = 5 * 60 * 1000;
|
||||
|
||||
// Served next to the API's /api/v1 (so "/manifest.json" by default, or on
|
||||
// VITE_API_URL's origin when the client talks to another server)
|
||||
const MANIFEST_URL = new URL(
|
||||
'../../manifest.json',
|
||||
new URL(
|
||||
`${(import.meta.env.VITE_API_URL ?? '/api/v1').replace(/\/$/, '')}/`,
|
||||
window.location.href,
|
||||
),
|
||||
).toString();
|
||||
|
||||
/** Fills fields missing from `raw` (e.g. a manifest cached by an older version) with defaults. */
|
||||
function normalize(raw: unknown): Manifest | null {
|
||||
if (typeof raw !== 'object' || raw === null) return null;
|
||||
const m = raw as Partial<Manifest>;
|
||||
const limits: Partial<LogDataLimits> = m.runLogs?.dataLimits ?? {};
|
||||
const num = (v: unknown, fallback: number) => (typeof v === 'number' && v >= 0 ? v : fallback);
|
||||
return {
|
||||
name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name,
|
||||
version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version,
|
||||
auth: { enabled: m.auth?.enabled === true },
|
||||
runLogs: {
|
||||
dataLimits: {
|
||||
bytes: num(limits.bytes, DEFAULT_LOG_DATA_LIMITS.bytes),
|
||||
lines: num(limits.lines, DEFAULT_LOG_DATA_LIMITS.lines),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Storage can be unavailable (private mode, blocked site data): the manifest
|
||||
// then just comes from the network on every page load
|
||||
function readCache(): Manifest | null {
|
||||
try {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
return stored ? normalize(JSON.parse(stored)) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(manifest: Manifest) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(manifest));
|
||||
} catch {
|
||||
// ignore, see readCache
|
||||
}
|
||||
}
|
||||
|
||||
let current: Manifest = readCache() ?? DEFAULT_MANIFEST;
|
||||
let fetchedAt = 0;
|
||||
let inFlight: Promise<void> | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
/**
|
||||
* Fetches the manifest and notifies subscribers if it changed. Failures are
|
||||
* silent: the cached (or default) manifest stays in use.
|
||||
*/
|
||||
export function refreshManifest(): Promise<void> {
|
||||
inFlight ??= fetch(MANIFEST_URL, {
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'include',
|
||||
})
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((raw: unknown) => {
|
||||
const next = normalize(raw);
|
||||
if (!next) return;
|
||||
fetchedAt = Date.now();
|
||||
writeCache(next);
|
||||
if (JSON.stringify(next) !== JSON.stringify(current)) {
|
||||
current = next;
|
||||
listeners.forEach((l) => l());
|
||||
}
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
return inFlight;
|
||||
}
|
||||
|
||||
function onVisibilityChange() {
|
||||
if (document.visibilityState === 'visible' && Date.now() - fetchedAt > REFRESH_AFTER_MS) {
|
||||
void refreshManifest();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stale-while-revalidate: subscribers get the localStorage copy right away,
|
||||
* and the manifest is refetched once per page load (the server answers 304
|
||||
* while it is unchanged) and when the tab becomes visible again after a while.
|
||||
*/
|
||||
export function subscribeManifest(listener: () => void): () => void {
|
||||
if (listeners.size === 0) document.addEventListener('visibilitychange', onVisibilityChange);
|
||||
listeners.add(listener);
|
||||
if (fetchedAt === 0) void refreshManifest();
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0) document.removeEventListener('visibilitychange', onVisibilityChange);
|
||||
};
|
||||
}
|
||||
|
||||
export function getManifest(): Manifest {
|
||||
return current;
|
||||
}
|
||||
+13
-2
@@ -6,15 +6,26 @@ import './i18n';
|
||||
import './ui/tokens.css';
|
||||
import App from './App';
|
||||
import { ToastProvider } from './ui';
|
||||
import { AuthProvider } from './auth/AuthContext';
|
||||
import { ApiError } from './api/client';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: (failureCount, error) =>
|
||||
error instanceof ApiError && error.status === 401 ? false : failureCount < 3,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
@@ -255,6 +255,12 @@
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.labelRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.textarea {
|
||||
width: 100%;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState, useCallback } from 'react';
|
||||
import { useNavigate, useParams, Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useManifest } from '../../hooks/useManifest';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { runs, runFiles } from '../../api';
|
||||
import type {
|
||||
Scenario,
|
||||
ScenarioRunDetail,
|
||||
ScenarioRunStep,
|
||||
ScenarioRunLog,
|
||||
ScenarioRunStatus,
|
||||
RunStepStatus,
|
||||
LogLevel,
|
||||
FileMetadata,
|
||||
} from '../../api';
|
||||
import { scenarios } from '../../api';
|
||||
@@ -27,7 +26,9 @@ import {
|
||||
Card,
|
||||
CodeBlock,
|
||||
DescriptionList,
|
||||
Pagination,
|
||||
formatLogText,
|
||||
hasLargeData,
|
||||
LogOutput,
|
||||
Search,
|
||||
Table,
|
||||
Timestamp,
|
||||
@@ -40,6 +41,7 @@ import {
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
ClipboardList,
|
||||
Copy,
|
||||
Activity,
|
||||
Download,
|
||||
Trash2,
|
||||
@@ -70,12 +72,6 @@ const STEP_STATUS_VARIANT: Record<RunStepStatus, BadgeVariant> = {
|
||||
cancelled: 'warning',
|
||||
};
|
||||
|
||||
const LOG_LEVEL_VARIANT: Record<LogLevel, BadgeVariant> = {
|
||||
log: 'neutral',
|
||||
warn: 'warning',
|
||||
error: 'error',
|
||||
};
|
||||
|
||||
const FINAL: ScenarioRunStatus[] = ['pass', 'fail'];
|
||||
|
||||
export function RunDetailPage() {
|
||||
@@ -89,6 +85,7 @@ function RunDetail() {
|
||||
const { id, runId } = useParams<{ id: string; runId: string }>();
|
||||
const navigate = useNavigate();
|
||||
const toast = useToast();
|
||||
const logDataLimits = useManifest().runLogs.dataLimits;
|
||||
|
||||
const [scenario, setScenario] = useState<Scenario | null>(null);
|
||||
const [run, setRun] = useState<ScenarioRunDetail | null>(null);
|
||||
@@ -97,7 +94,6 @@ function RunDetail() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [polling, setPolling] = useState(false);
|
||||
const [pulseKey, setPulseKey] = useState(0);
|
||||
const [logPage, setLogPage] = useState(1);
|
||||
const [logSearch, setLogSearch] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [expandAll, setExpandAll] = useState(false);
|
||||
@@ -111,8 +107,8 @@ function RunDetail() {
|
||||
const [pendingDeleteFile, setPendingDeleteFile] = useState<FileMetadata | null>(null);
|
||||
const [deletingFile, setDeletingFile] = useState(false);
|
||||
const [repeating, setRepeating] = useState(false);
|
||||
const [logDataExpanded, setLogDataExpanded] = useState(false);
|
||||
const logSearchRef = useRef('');
|
||||
const LOG_PAGE_SIZE = 25;
|
||||
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
const stopPolling = () => {
|
||||
@@ -154,6 +150,33 @@ function RunDetail() {
|
||||
}
|
||||
};
|
||||
|
||||
const logEntries = useMemo(
|
||||
() =>
|
||||
(run?.logs ?? []).map((l) => ({
|
||||
id: l.id,
|
||||
level: l.level,
|
||||
context: l.context,
|
||||
message: l.message,
|
||||
data: l.data,
|
||||
createdAt: l.createdAt,
|
||||
})),
|
||||
[run?.logs],
|
||||
);
|
||||
const logsHaveLargeData = useMemo(
|
||||
() => hasLargeData(logEntries, logDataLimits),
|
||||
[logEntries, logDataLimits],
|
||||
);
|
||||
|
||||
// Copies the (filtered) logs as plain text with every data block expanded
|
||||
const handleCopyLogs = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(formatLogText(logEntries, run?.createdAt));
|
||||
toast.success(t('runs.logs_copied'));
|
||||
} catch {
|
||||
toast.error(t('runs.logs_copy_failed'));
|
||||
}
|
||||
};
|
||||
|
||||
const handleRepeatRun = async () => {
|
||||
if (!id || !run?.environmentId) return;
|
||||
setRepeating(true);
|
||||
@@ -221,7 +244,6 @@ function RunDetail() {
|
||||
const t = setTimeout(() => {
|
||||
setDebouncedSearch(logSearch);
|
||||
logSearchRef.current = logSearch;
|
||||
setLogPage(1);
|
||||
}, 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [logSearch]);
|
||||
@@ -400,26 +422,6 @@ function RunDetail() {
|
||||
},
|
||||
];
|
||||
|
||||
const logColumns: TableColumn<ScenarioRunLog>[] = [
|
||||
{
|
||||
key: 'level',
|
||||
header: t('runs.log_level'),
|
||||
width: 70,
|
||||
render: (l) => <Badge variant={LOG_LEVEL_VARIANT[l.level]}>{l.level}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'message',
|
||||
header: t('runs.log_message'),
|
||||
render: (l) => <code style={{ wordBreak: 'break-word' }}>{l.message}</code>,
|
||||
},
|
||||
{
|
||||
key: 'time',
|
||||
header: t('runs.log_time'),
|
||||
width: 160,
|
||||
render: (l) => <Timestamp value={l.createdAt} />,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.pageToolbar}>
|
||||
@@ -547,7 +549,22 @@ function RunDetail() {
|
||||
{run.logs.length > 0 && (
|
||||
<div className={styles.stepsSection}>
|
||||
<div className={styles.sectionHeadingRow}>
|
||||
<h2 className={styles.sectionHeading}>{t('runs.logs_heading')}</h2>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<h2 className={styles.sectionHeading} style={{ margin: 0 }}>
|
||||
{t('runs.logs_heading')}
|
||||
</h2>
|
||||
{logsHaveLargeData && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
aria-expanded={logDataExpanded}
|
||||
onClick={() => setLogDataExpanded((v) => !v)}
|
||||
>
|
||||
{logDataExpanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
|
||||
{logDataExpanded ? t('runs.logs_collapse_data') : t('runs.logs_expand_data')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
|
||||
<Search
|
||||
value={logSearch}
|
||||
@@ -558,23 +575,27 @@ function RunDetail() {
|
||||
<Download size={14} />
|
||||
{t('runs.action_download_logs')}
|
||||
</Button>
|
||||
<Button variant="secondary" size="sm" onClick={handleCopyLogs}>
|
||||
<Copy size={14} />
|
||||
{t('runs.action_copy_logs')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Table
|
||||
columns={logColumns}
|
||||
data={run.logs.slice((logPage - 1) * LOG_PAGE_SIZE, logPage * LOG_PAGE_SIZE)}
|
||||
rowKey={(l) => l.id}
|
||||
loading={false}
|
||||
<LogOutput
|
||||
startTime={run.createdAt}
|
||||
maxHeight={480}
|
||||
entries={logEntries}
|
||||
dataLimits={logDataLimits}
|
||||
dataExpanded={logDataExpanded}
|
||||
showDataLabel={({ bytes, lines }) =>
|
||||
t('runs.logs_show_data', {
|
||||
size: bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`,
|
||||
count: lines,
|
||||
})
|
||||
}
|
||||
hideDataLabel={t('runs.logs_hide_data')}
|
||||
emptyMessage=""
|
||||
/>
|
||||
{run.logs.length > LOG_PAGE_SIZE && (
|
||||
<Pagination
|
||||
page={logPage}
|
||||
pageSize={LOG_PAGE_SIZE}
|
||||
total={run.logs.length}
|
||||
onPageChange={setLogPage}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -587,7 +608,23 @@ function RunDetail() {
|
||||
rowKey={(f) => f.id}
|
||||
columns={
|
||||
[
|
||||
{ key: 'name', header: t('files.name'), render: (f) => f.name },
|
||||
{
|
||||
key: 'name',
|
||||
header: t('files.name'),
|
||||
// Served inline, so the browser shows what it can (images, text, PDF).
|
||||
render: (f) =>
|
||||
isFileExpired(f) ? (
|
||||
f.name
|
||||
) : (
|
||||
<a
|
||||
href={runFiles.contentUrl(id!, runId!, f.id)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{f.name}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'mimeType',
|
||||
header: t('files.mimeType'),
|
||||
|
||||
@@ -6,6 +6,7 @@ import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import { CodeHelpButton } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateStepPage() {
|
||||
@@ -77,7 +78,10 @@ export function CreateStepPage() {
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<div className={styles.labelRow}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeHelpButton />
|
||||
</div>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
|
||||
@@ -6,6 +6,7 @@ import { X, Save, ClipboardList } from 'lucide-react';
|
||||
import { scenarios, steps } from '../../api';
|
||||
import type { Scenario, ScenarioStep } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import { CodeHelpButton } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditStepPage() {
|
||||
@@ -89,7 +90,10 @@ export function EditStepPage() {
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
/>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<div className={styles.labelRow}>
|
||||
<label className={styles.fieldLabel}>{t('steps.form_exec_code')}</label>
|
||||
<CodeHelpButton />
|
||||
</div>
|
||||
<CodeEditor value={execCode} onChange={setExecCode} rows={6} />
|
||||
</div>
|
||||
<Input
|
||||
|
||||
@@ -229,12 +229,13 @@ export function ScenarioDetailPage() {
|
||||
includeEnvironment,
|
||||
credentialIds: credIds,
|
||||
snippetIds: Array.from(includedSnippetIds),
|
||||
version: scenario.version,
|
||||
});
|
||||
const blob = new Blob([yamlContent], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${scenario.name}.yaml`;
|
||||
a.download = `${scenario.name}-v${scenario.version}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
setExportModalOpen(false);
|
||||
@@ -503,7 +504,10 @@ export function ScenarioDetailPage() {
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
handleFileDownload(scenarios.exportE2eTestUrl(id!), `${scenario.name}-e2e-test.zip`)
|
||||
handleFileDownload(
|
||||
scenarios.exportE2eTestUrl(id!, scenario.version),
|
||||
`${scenario.name}-v${scenario.version}-e2e-test.zip`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<FileArchive size={14} />
|
||||
@@ -761,7 +765,19 @@ export function ScenarioDetailPage() {
|
||||
{
|
||||
key: 'name',
|
||||
header: t('files.name'),
|
||||
render: (f) => f.name,
|
||||
// Served inline, so the browser shows what it can (images, text, PDF).
|
||||
render: (f) =>
|
||||
isFileExpired(f) ? (
|
||||
f.name
|
||||
) : (
|
||||
<a
|
||||
href={scenarioFiles.contentUrl(id!, f.id)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
{f.name}
|
||||
</a>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'mimeType',
|
||||
|
||||
@@ -5,6 +5,7 @@ import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import { CodeHelpButton } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function CreateSnippetPage() {
|
||||
@@ -107,10 +108,13 @@ export function CreateSnippetPage() {
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<div className={styles.labelRow}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<CodeHelpButton />
|
||||
</div>
|
||||
<CodeEditor
|
||||
value={code}
|
||||
onChange={(v) => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { X, Save, Braces } from 'lucide-react';
|
||||
import { snippets } from '../../api';
|
||||
import type { Snippet } from '../../api';
|
||||
import { Breadcrumbs, Button, Card, Input, CodeEditor, useToast } from '../../ui';
|
||||
import { CodeHelpButton } from '../../components/modals';
|
||||
import styles from '../Page.module.css';
|
||||
|
||||
export function EditSnippetPage() {
|
||||
@@ -134,10 +135,13 @@ export function EditSnippetPage() {
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.formField}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<div className={styles.labelRow}>
|
||||
<label className={styles.fieldLabel}>
|
||||
{t('snippets.form_code')}
|
||||
<span className={styles.requiredMark}> *</span>
|
||||
</label>
|
||||
<CodeHelpButton />
|
||||
</div>
|
||||
<CodeEditor
|
||||
value={code}
|
||||
onChange={(v) => {
|
||||
|
||||
@@ -51,12 +51,12 @@ export function SnippetDetailPage() {
|
||||
|
||||
const handleExport = async () => {
|
||||
if (!snippet) return;
|
||||
const data = await snippets.exportSnippet(snippet.id);
|
||||
const data = await snippets.exportSnippet(snippet.id, snippet.version);
|
||||
const blob = new Blob([yamlStringify(data)], { type: 'application/yaml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `snippet-${snippet.alias}.yaml`;
|
||||
a.download = `snippet-${snippet.alias}-v${snippet.version}.yaml`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
@@ -88,3 +88,9 @@
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.spinner {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--color-bg-subtle);
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
overflow: auto;
|
||||
font-family: var(--font-mono, ui-monospace, 'Cascadia Code', 'Fira Code', monospace);
|
||||
font-size: var(--font-size-xs);
|
||||
/* Where the context/message column starts: timestamp + level + their gaps */
|
||||
--log-body-offset: calc(7em + 4.5em + 2 * var(--space-2));
|
||||
}
|
||||
|
||||
.empty {
|
||||
padding: var(--space-4);
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.line {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-1) var(--space-3);
|
||||
border-left: 3px solid transparent;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.line:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.lineHeader {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.data {
|
||||
margin: 0 0 var(--space-1) var(--log-body-offset);
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-bg);
|
||||
max-width: 100%;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.data > * {
|
||||
margin: 0;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
flex: 0 0 auto;
|
||||
min-width: 7em;
|
||||
text-align: right;
|
||||
color: var(--color-text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.level {
|
||||
flex: 0 0 auto;
|
||||
width: 4.5em;
|
||||
text-transform: uppercase;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.context {
|
||||
flex: 0 0 auto;
|
||||
color: var(--color-secondary-fg);
|
||||
}
|
||||
|
||||
.context::before {
|
||||
content: '[';
|
||||
}
|
||||
|
||||
.context::after {
|
||||
content: ']';
|
||||
}
|
||||
|
||||
.message {
|
||||
flex: 1 1 320px;
|
||||
color: var(--color-text);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.debug {
|
||||
border-left-color: var(--color-border);
|
||||
}
|
||||
|
||||
.debug .level,
|
||||
.debug .message,
|
||||
.debug .timestamp,
|
||||
.debug .context {
|
||||
color: var(--color-text-faint);
|
||||
}
|
||||
|
||||
.log {
|
||||
border-left-color: var(--color-border);
|
||||
}
|
||||
|
||||
.log .level {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.warn {
|
||||
border-left-color: var(--color-warning-fg);
|
||||
background: var(--color-warning-bg);
|
||||
}
|
||||
|
||||
.warn .level {
|
||||
color: var(--color-warning-fg);
|
||||
}
|
||||
|
||||
.error {
|
||||
border-left-color: var(--color-error-fg);
|
||||
background: var(--color-error-bg);
|
||||
}
|
||||
|
||||
.error .level {
|
||||
color: var(--color-error-fg);
|
||||
}
|
||||
|
||||
.dataToggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
align-self: flex-start;
|
||||
margin-left: var(--log-body-offset);
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
font: inherit;
|
||||
color: var(--color-text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dataToggle svg {
|
||||
flex: 0 0 auto;
|
||||
color: var(--color-primary-text);
|
||||
}
|
||||
|
||||
.dataToggle:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react';
|
||||
import { CodeBlock } from '../CodeBlock/CodeBlock';
|
||||
import {
|
||||
DEFAULT_LOG_DATA_LIMITS,
|
||||
exceedsLimits,
|
||||
formatElapsed,
|
||||
measureData,
|
||||
prettyData,
|
||||
type LogDataLimits,
|
||||
} from './logText';
|
||||
import styles from './LogOutput.module.css';
|
||||
|
||||
export type LogOutputLevel = 'debug' | 'log' | 'warn' | 'error';
|
||||
|
||||
export interface LogOutputEntry {
|
||||
id: string | number;
|
||||
level: LogOutputLevel;
|
||||
/** Where the message was generated, e.g. "step:2", "snippet:login", "assertion:pass". */
|
||||
context?: string | null;
|
||||
message: string;
|
||||
/** JSON payload attached to the message, as a raw string; rendered pretty-printed, separately from the message. */
|
||||
data?: string | null;
|
||||
createdAt: string | number | Date;
|
||||
}
|
||||
|
||||
export interface LogOutputProps {
|
||||
entries: LogOutputEntry[];
|
||||
/** Reference point for the elapsed-time column; defaults to the first entry's timestamp. */
|
||||
startTime?: string | number | Date;
|
||||
/** Caps the block's height (e.g. "400px"), scrolling once entries overflow it. */
|
||||
maxHeight?: string | number;
|
||||
emptyMessage?: string;
|
||||
className?: string;
|
||||
/** Data blocks whose pretty-printed JSON exceeds either limit start collapsed behind a toggle. */
|
||||
dataLimits?: LogDataLimits;
|
||||
/**
|
||||
* Expands (true) or collapses (false) every large data block. Changing it
|
||||
* discards the per-entry toggles made since the last change.
|
||||
*/
|
||||
dataExpanded?: boolean;
|
||||
/** Label of a collapsed data block's toggle, e.g. "Show data (1.2 KB, 40 lines)". */
|
||||
showDataLabel?: (size: { bytes: number; lines: number }) => string;
|
||||
hideDataLabel?: string;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
|
||||
}
|
||||
|
||||
const defaultShowDataLabel = ({ bytes, lines }: { bytes: number; lines: number }) =>
|
||||
`Show data (${formatBytes(bytes)}, ${lines} ${lines === 1 ? 'line' : 'lines'})`;
|
||||
|
||||
/** Terminal-style log viewer: one line per entry, color-coded by level. */
|
||||
export function LogOutput({
|
||||
entries,
|
||||
startTime,
|
||||
maxHeight,
|
||||
emptyMessage = 'No logs.',
|
||||
className,
|
||||
dataLimits = DEFAULT_LOG_DATA_LIMITS,
|
||||
dataExpanded = false,
|
||||
showDataLabel = defaultShowDataLabel,
|
||||
hideDataLabel = 'Hide data',
|
||||
}: LogOutputProps) {
|
||||
// Per-entry toggles, reset whenever dataExpanded changes
|
||||
const [toggled, setToggled] = useState<Set<LogOutputEntry['id']>>(() => new Set());
|
||||
const [prevDataExpanded, setPrevDataExpanded] = useState(dataExpanded);
|
||||
if (prevDataExpanded !== dataExpanded) {
|
||||
setPrevDataExpanded(dataExpanded);
|
||||
setToggled(new Set());
|
||||
}
|
||||
|
||||
const dataBlocks = useMemo(() => {
|
||||
const blocks = new Map<
|
||||
LogOutputEntry['id'],
|
||||
{ pretty: string; bytes: number; lines: number }
|
||||
>();
|
||||
for (const entry of entries) {
|
||||
if (!entry.data) continue;
|
||||
const pretty = prettyData(entry.data);
|
||||
blocks.set(entry.id, { pretty, ...measureData(pretty) });
|
||||
}
|
||||
return blocks;
|
||||
}, [entries]);
|
||||
|
||||
const toggle = (id: LogOutputEntry['id']) =>
|
||||
setToggled((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (!next.delete(id)) next.add(id);
|
||||
return next;
|
||||
});
|
||||
|
||||
if (entries.length === 0) {
|
||||
return <div className={styles.empty}>{emptyMessage}</div>;
|
||||
}
|
||||
|
||||
const startMs = new Date(startTime ?? entries[0].createdAt).getTime();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={[styles.root, className].filter(Boolean).join(' ')}
|
||||
style={maxHeight !== undefined ? { maxHeight } : undefined}
|
||||
role="log"
|
||||
tabIndex={0}
|
||||
>
|
||||
{entries.map((entry) => {
|
||||
const entryMs = new Date(entry.createdAt).getTime();
|
||||
const block = dataBlocks.get(entry.id);
|
||||
const large = block != null && exceedsLimits(block, dataLimits);
|
||||
const open = !large || dataExpanded !== toggled.has(entry.id);
|
||||
return (
|
||||
<div key={entry.id} className={[styles.line, styles[entry.level]].join(' ')}>
|
||||
<div className={styles.lineHeader}>
|
||||
<span className={styles.timestamp} title={new Date(entryMs).toISOString()}>
|
||||
{formatElapsed(entryMs - startMs)}
|
||||
</span>
|
||||
<span className={styles.level}>{entry.level}</span>
|
||||
{entry.context && <span className={styles.context}>{entry.context}</span>}
|
||||
<span className={styles.message}>{entry.message}</span>
|
||||
</div>
|
||||
{block && large && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.dataToggle}
|
||||
aria-expanded={open}
|
||||
onClick={() => toggle(entry.id)}
|
||||
>
|
||||
{open ? (
|
||||
<ChevronDown size={14} strokeWidth={3} aria-hidden="true" />
|
||||
) : (
|
||||
<ChevronRight size={14} strokeWidth={3} aria-hidden="true" />
|
||||
)}
|
||||
{open ? hideDataLabel : showDataLabel(block)}
|
||||
</button>
|
||||
)}
|
||||
{block && open && (
|
||||
<div className={styles.data}>
|
||||
<CodeBlock code={block.pretty} language="json" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { LogOutputEntry } from './LogOutput';
|
||||
|
||||
/** Data blocks above either limit start collapsed. */
|
||||
export interface LogDataLimits {
|
||||
/** UTF-8 byte size of the pretty-printed data. */
|
||||
bytes: number;
|
||||
/** Line count of the pretty-printed data. */
|
||||
lines: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_LOG_DATA_LIMITS: LogDataLimits = { bytes: 256, lines: 5 };
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
/**
|
||||
* "+12s" (or "-" if before startTime, e.g. clock skew). Log timestamps are
|
||||
* stored with second resolution, so fractions would be noise.
|
||||
*/
|
||||
export function formatElapsed(deltaMs: number): string {
|
||||
const sign = deltaMs < 0 ? '-' : '+';
|
||||
return `${sign}${Math.round(Math.abs(deltaMs) / 1000)}s`;
|
||||
}
|
||||
|
||||
/** Pretty-prints `data` if it's valid JSON, otherwise returns it as-is. */
|
||||
export function prettyData(data: string): string {
|
||||
try {
|
||||
return JSON.stringify(JSON.parse(data), null, 2);
|
||||
} catch {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
/** Byte size and line count of an already pretty-printed data block. */
|
||||
export function measureData(pretty: string): { bytes: number; lines: number } {
|
||||
return { bytes: encoder.encode(pretty).length, lines: pretty.split('\n').length };
|
||||
}
|
||||
|
||||
export function exceedsLimits(size: { bytes: number; lines: number }, limits: LogDataLimits) {
|
||||
return size.bytes > limits.bytes || size.lines > limits.lines;
|
||||
}
|
||||
|
||||
/** True if any entry's data block exceeds the limits (i.e. renders collapsed by default). */
|
||||
export function hasLargeData(
|
||||
entries: Pick<LogOutputEntry, 'data'>[],
|
||||
limits: LogDataLimits = DEFAULT_LOG_DATA_LIMITS,
|
||||
): boolean {
|
||||
return entries.some((e) => e.data && exceedsLimits(measureData(prettyData(e.data)), limits));
|
||||
}
|
||||
|
||||
/**
|
||||
* Plain-text rendering of the log, one entry per line with every data block
|
||||
* pretty-printed and indented below its line (e.g. for copying to the clipboard).
|
||||
*/
|
||||
export function formatLogText(
|
||||
entries: LogOutputEntry[],
|
||||
startTime?: string | number | Date,
|
||||
): string {
|
||||
if (entries.length === 0) return '';
|
||||
const startMs = new Date(startTime ?? entries[0].createdAt).getTime();
|
||||
return entries
|
||||
.map((entry) => {
|
||||
const elapsed = formatElapsed(new Date(entry.createdAt).getTime() - startMs);
|
||||
const context = entry.context ? ` [${entry.context}]` : '';
|
||||
const header = `${elapsed.padStart(6)} ${entry.level.toUpperCase().padEnd(5)}${context} ${entry.message}`;
|
||||
if (!entry.data) return header;
|
||||
const data = prettyData(entry.data)
|
||||
.split('\n')
|
||||
.map((line) => ` ${line}`)
|
||||
.join('\n');
|
||||
return `${header}\n${data}`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
@@ -16,6 +16,13 @@
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: 0 20px 48px color-mix(in srgb, #000 28%, transparent);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 100%;
|
||||
}
|
||||
|
||||
.lg {
|
||||
width: min(880px, 100%);
|
||||
}
|
||||
|
||||
.header {
|
||||
@@ -31,6 +38,7 @@
|
||||
.body {
|
||||
padding: var(--space-2) var(--space-5) var(--space-4);
|
||||
color: var(--color-text-muted);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.footer {
|
||||
|
||||
@@ -7,9 +7,11 @@ export interface ModalProps {
|
||||
children?: React.ReactNode;
|
||||
onClose: () => void;
|
||||
footer?: React.ReactNode;
|
||||
/** `lg` widens the dialog for long, document-like content. */
|
||||
size?: 'md' | 'lg';
|
||||
}
|
||||
|
||||
export function Modal({ open, title, children, onClose, footer }: ModalProps) {
|
||||
export function Modal({ open, title, children, onClose, footer, size = 'md' }: ModalProps) {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
@@ -24,7 +26,7 @@ export function Modal({ open, title, children, onClose, footer }: ModalProps) {
|
||||
return (
|
||||
<div className={styles.overlay} role="presentation" onClick={onClose}>
|
||||
<div
|
||||
className={styles.dialog}
|
||||
className={size === 'lg' ? `${styles.dialog} ${styles.lg}` : styles.dialog}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={title}
|
||||
@@ -33,7 +35,10 @@ export function Modal({ open, title, children, onClose, footer }: ModalProps) {
|
||||
<div className={styles.header}>
|
||||
<h3 className={styles.title}>{title}</h3>
|
||||
</div>
|
||||
<div className={styles.body}>{children}</div>
|
||||
{/* Long (lg) content scrolls; make it focusable so the keyboard can scroll it. */}
|
||||
<div className={styles.body} tabIndex={size === 'lg' ? 0 : undefined}>
|
||||
{children}
|
||||
</div>
|
||||
{footer && <div className={styles.footer}>{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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}
|
||||
aria-expanded={!collapsed}
|
||||
>
|
||||
<div className={styles.inner}>
|
||||
<div className={styles.inner} aria-hidden={collapsed} inert={collapsed}>
|
||||
{header && <div className={styles.header}>{header}</div>}
|
||||
<div className={styles.content}>{children}</div>
|
||||
</div>
|
||||
|
||||
@@ -26,6 +26,8 @@ export { Breadcrumbs } from './Breadcrumbs/Breadcrumbs';
|
||||
export type { BreadcrumbsProps, BreadcrumbItem } from './Breadcrumbs/Breadcrumbs';
|
||||
|
||||
export { ThemeSwitcher } from './ThemeSwitcher/ThemeSwitcher';
|
||||
export { NotificationToggle } from './NotificationToggle/NotificationToggle';
|
||||
export type { NotificationToggleState } from './NotificationToggle/NotificationToggle';
|
||||
|
||||
export { ToastProvider } from './Toast/ToastProvider';
|
||||
export type { ToastProviderProps } from './Toast/ToastProvider';
|
||||
@@ -69,3 +71,8 @@ export type { TableProps, TableColumn, SortDirection } from './Table/Table';
|
||||
|
||||
export { UuidBadge } from './UuidBadge/UuidBadge';
|
||||
export type { UuidBadgeProps } from './UuidBadge/UuidBadge';
|
||||
|
||||
export { LogOutput } from './LogOutput/LogOutput';
|
||||
export type { LogOutputProps, LogOutputEntry, LogOutputLevel } from './LogOutput/LogOutput';
|
||||
export { DEFAULT_LOG_DATA_LIMITS, formatLogText, hasLargeData } from './LogOutput/logText';
|
||||
export type { LogDataLimits } from './LogOutput/logText';
|
||||
@@ -46,6 +46,7 @@
|
||||
|
||||
--color-text: #2D3339;
|
||||
--color-text-muted: #634DBD; /* Kimberly, a touch darker for 4.5:1 on bg-subtle */
|
||||
--color-text-faint: #5C6063; /* desaturated grey, ~4.5:1 on bg-subtle - as washed out as WCAG AA allows */
|
||||
--color-border: #AFBFB9; /* Powder Ash */
|
||||
--color-bg: #E6EDEA; /* Powder Ash tint */
|
||||
--color-bg-subtle: #D8E2DE; /* Powder Ash tint, 1 step darker */
|
||||
@@ -158,6 +159,7 @@ a:hover {
|
||||
|
||||
--color-text: #E2EAE6;
|
||||
--color-text-muted: #A9A3C9; /* lightened Kimberly */
|
||||
--color-text-faint: #9A9A9A; /* desaturated grey, ~4.5:1 on dark bg-subtle - as washed out as WCAG AA allows */
|
||||
--color-border: #3D4850;
|
||||
--color-bg: #1A1F24; /* deeper than Outer Space */
|
||||
--color-bg-subtle: #2D3339; /* Outer Space */
|
||||
|
||||
+13
-2
@@ -11,6 +11,7 @@
|
||||
│ Routes / built client (ServeStaticModule) │
|
||||
│ /api/v1 REST API /docs Swagger UI │
|
||||
│ /mcp MCP tools /health health check │
|
||||
│ /manifest.json public client configuration │
|
||||
│ │
|
||||
│ McpService MCP tools → services below │
|
||||
│ ScenarioService scenarios, steps, versions, runs │
|
||||
@@ -34,6 +35,12 @@
|
||||
|
||||
Everything runs in one container built from the root `Dockerfile`: the server serves the API, MCP and Swagger, and also the built client. See [development.md](development.md) for running it.
|
||||
|
||||
## Optional authentication boundary
|
||||
|
||||
Account authentication is off unless `AUTH_ENABLED=true`. When enabled, the global guard protects REST and MCP controller routes and the run-events stream. The public routes are `GET /health`, `GET /healthz`, `GET /manifest.json` and `POST /api/v1/auth/login`; the manifest reports the auth-enabled flag so the client can choose its login flow. UI assets and the Swagger UI remain reachable, but API operations require authentication. Protected requests accept a bearer token or the `AUTH_COOKIE_NAME` cookie (`liqa_auth` by default). Browser login sets an HttpOnly, SameSite=Strict cookie and logout revokes the presented token and expires the cookie; HTTPS requests also get the Secure attribute. See [development.md](development.md#enabling-authentication) for operator setup and lifecycle details.
|
||||
|
||||
The authentication service stores users and hashed revoked-token identifiers in SQLite. Revocation records are retained through token expiry, then removed at startup and by the `AUTH_REVOKED_TOKEN_CLEANUP_CRON` job (`0 3 * * *` by default); no cleanup job is registered while auth is disabled. Authentication checks that the token is not revoked and that its account still exists, so deleting an account invalidates its outstanding tokens at the next request.
|
||||
|
||||
## Server components (`server/src/`)
|
||||
|
||||
- **McpService** (`mcp/`) registers the MCP tools and delegates to the services below. Each request gets a fresh MCP server over the Streamable HTTP transport.
|
||||
@@ -72,8 +79,12 @@ See [scenario.md](scenario.md) for versioning, runs and import/export rules.
|
||||
|
||||
A React 19 + TypeScript SPA. During development it's served by the Vite dev server; in the Docker image the server serves the built client from the same origin as the API.
|
||||
|
||||
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` and `/health` 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 (injected from the workspace root `package.json` at build time).
|
||||
Pages: scenarios (with steps, versions, credentials, used snippets and files), runs, snippets, credentials, environments, sessions, and the central import page. The sidebar footer contains the theme switcher, the browser notifications toggle and the app version.
|
||||
|
||||
`GET /manifest.json` is the server's public configuration for the client: the app `name` and `version`, and settings the UI needs (currently `runLogs.dataLimits`, from `RUN_LOG_DATA_COLLAPSE_BYTES` / `RUN_LOG_DATA_COLLAPSE_LINES`). The client reads it through `client/src/lib/manifest.ts` and the `useManifest()` hook, stale-while-revalidate: the copy cached in `localStorage` (or built-in defaults on first visit) is used right away, and the manifest is refetched once per page load and when the tab becomes visible again after 5 minutes. The server sends it with `Cache-Control: no-cache` and an ETag, so an unchanged manifest costs a 304. Add new client-facing settings to the manifest (`server/src/manifest/`) rather than as build-time Vite variables.
|
||||
|
||||
Run notifications: `RunEventsService` (`scenario/`) is an in-process rxjs subject. The scheduler emits `run.started` and `run.finished` (once per run, from the run's single exit points rather than each pass/fail transition), and `GET /api/v1/scenarios/runs/events` streams them as SSE. The `useRunNotifications` hook opens an `EventSource` to it, only while the user has enabled notifications and the browser permission is granted, and shows a `Notification` per event. See [scenario.md](scenario.md#run-events-and-browser-notifications).
|
||||
|
||||
See [development.md](development.md) for the full client tech stack and directory layout.
|
||||
+100
-4
@@ -30,6 +30,7 @@ All settings are validated at startup by `server/src/config/app.config.ts`.
|
||||
| `NODE_ENV` | `development` | `production` in the Docker image. Shown in the startup log, and selects the default CORS origins |
|
||||
| `CORS_ORIGINS` | *(empty)* | Comma-separated origins allowed to call the API cross-origin. When empty: the Vite dev server (`http://localhost:5173`, `http://127.0.0.1:5173`) unless `NODE_ENV=production`, then the compose port (`http://localhost:13000`, `http://127.0.0.1:13000`) |
|
||||
| `PORT` | `3000` | HTTP port |
|
||||
| `LOG_MODE` | `console` | `console` preserves the default server output; `debug` routes application diagnostics through the `debug` package and only emits namespaces enabled by `DEBUG` (for example, `DEBUG=liqa:*`). |
|
||||
| `DB_PATH` | `data/liqa.db` | SQLite database file |
|
||||
| `FILES_DIR` | `data/files` | Where scenario files and run artifacts are stored |
|
||||
| `FILE_RUN_EXPIRATION_DAYS` | `7` | How long run artifacts (downloads, failure dumps, traces) are kept |
|
||||
@@ -37,8 +38,15 @@ All settings are validated at startup by `server/src/config/app.config.ts`.
|
||||
| `SESSION_IDLE_TIMEOUT_MINUTES` | `30` | Idle timeout before open sessions are closed |
|
||||
| `SESSION_DELETE_CLOSED_DAYS` | `7` | Retention period for closed sessions |
|
||||
| `PLAYWRIGHT_TRACE_MODE` | `off` | Default Playwright trace mode for runs: `on`, `retain-on-failure` or `off` (see [scenario.md](scenario.md)) |
|
||||
| `RUN_LOG_DATA_COLLAPSE_BYTES` | `256` | Run log `data` blocks whose pretty-printed JSON is over this many bytes start collapsed in the UI (exposed via `/manifest.json`) |
|
||||
| `RUN_LOG_DATA_COLLAPSE_LINES` | `5` | Same, for the number of lines |
|
||||
| `CLIENT_DIR` | *(empty)* | Directory with the built client to serve at `/` (the Docker image sets it to `client`); empty means the server doesn't serve the UI |
|
||||
| `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` | _(Playwright default)_ | Path to a Chromium binary to use instead of Playwright's own. Not set in Docker: the image ships Playwright's `chromium-headless-shell` (matching the Playwright version) under `PLAYWRIGHT_BROWSERS_PATH=/ms-playwright`. |
|
||||
| `AUTH_ENABLED` | `false` | Opt-in account authentication. With the default `false`, the existing UI, REST API and MCP remain available without accounts. |
|
||||
| `AUTH_JWT_SECRET` | *(empty)* | Required and non-empty when `AUTH_ENABLED=true`. Keep it private and stable across restarts; changing it invalidates existing tokens. |
|
||||
| `AUTH_COOKIE_NAME` | `liqa_auth` | Name of the browser's HttpOnly session cookie. |
|
||||
| `AUTH_JWT_EXPIRES_IN` | `24h` | Default lifetime for browser sessions and CLI-issued tokens. Positive durations use `s`, `m`, `h` or `d`. |
|
||||
| `AUTH_REVOKED_TOKEN_CLEANUP_CRON` | `0 3 * * *` | When expired logout revocations are cleaned. Cleanup also runs once at startup and is disabled when auth is off. |
|
||||
|
||||
---
|
||||
|
||||
@@ -101,6 +109,54 @@ The SQLite schema is managed by TypeORM migrations in `server/src/database/migra
|
||||
|
||||
The scripts run from `server/`, so `DB_PATH` (default `data/liqa.db`) is relative to it, and they read `server/.env` if present, like the server does.
|
||||
|
||||
### Enabling authentication
|
||||
|
||||
Authentication is disabled by default, so a fresh install needs no auth settings. For Docker Compose, set these in the project `.env` (keep it out of version control):
|
||||
|
||||
```dotenv
|
||||
AUTH_ENABLED=true
|
||||
AUTH_JWT_SECRET=<private-random-secret>
|
||||
```
|
||||
|
||||
Use a long, randomly generated secret from your secret manager; do not use the placeholder literally or commit a real value. `AUTH_ENABLED` accepts only `true` or `false`. When enabled, startup fails if the signing secret is blank or the configured token lifetime/cleanup schedule is invalid. Rebuild/restart the container after changing its configuration. Compose applies pending migrations before starting the server. For local development, export the same variables in the server process environment (or put them in `server/.env`); run `npm -w server run build` and `npm -w server run migration:run` before account commands or server startup. Migrations add the user and revoked-token tables and are required even when authentication is disabled.
|
||||
|
||||
When auth is enabled, REST and MCP controller routes require a valid bearer token or browser cookie except `GET /health`, `GET /healthz`, `GET /manifest.json`, and `POST /api/v1/auth/login`. Login is public so a browser can establish its session. The manifest exposes whether auth is enabled; health endpoints return service status. The UI assets and Swagger UI at `/docs` remain reachable, while API operations invoked from Swagger require authentication. MCP at `/mcp` and the run-events stream are protected. When auth is disabled, the guard allows existing requests through.
|
||||
|
||||
## Operator account commands
|
||||
|
||||
Authentication is opt-in. To manage accounts or issue tokens, set `AUTH_ENABLED=true` and `AUTH_JWT_SECRET` in the same environment used by the server. Apply database migrations before using the commands. Passwords are entered interactively without terminal echo; they are never accepted as command-line arguments. The CLI uses the same `DB_PATH` as the server; locally it resolves the default `data/liqa.db` relative to `server/`, while inside the container it uses the configured path (normally `/app/data/liqa.db`, persisted by the `./data:/app/data` volume).
|
||||
|
||||
Build the server and apply migrations locally, then run commands from the server workspace:
|
||||
|
||||
```bash
|
||||
npm -w server run build
|
||||
npm -w server run migration:run
|
||||
npm -w server run cli -- user:create
|
||||
npm -w server run cli -- user:get alice
|
||||
npm -w server run cli -- user:token alice # uses AUTH_JWT_EXPIRES_IN (default 24h)
|
||||
npm -w server run cli -- user:token alice 30m # optional lifetime
|
||||
npm -w server run cli -- user:delete alice
|
||||
```
|
||||
|
||||
The container image does not include npm or npx. Run the built CLI with Node inside the running service; it uses that container's configured `DB_PATH` and exits without starting the web server or schedulers:
|
||||
|
||||
```bash
|
||||
docker compose exec liqa node dist/cli.js user:create
|
||||
docker compose exec liqa node dist/cli.js user:get alice
|
||||
docker compose exec liqa node dist/cli.js user:token alice 30m
|
||||
docker compose exec liqa node dist/cli.js user:delete alice
|
||||
```
|
||||
|
||||
`user:create` asks for a username and two matching passwords; password entry is hidden and requires an interactive terminal. A duplicate username, blank username/password, mismatch or invalid input fails with a nonzero exit. The other commands require an existing username; lookup output contains only the account id, username and timestamps. Unknown usernames fail with `No account found for that username.` and a nonzero exit. A token duration must be a positive number followed by `s`, `m`, `h` or `d` (for example `30m`, `1h`, `7d`); omitted duration uses `AUTH_JWT_EXPIRES_IN` (`24h` by default). Token output is a bearer credential: handle it as a secret and do not paste it into logs or shared history. User deletion removes the account, so the server rejects that user's previously issued tokens on their next authentication. General CLI failures print a concise hint to check auth settings, `DB_PATH` and migrations.
|
||||
|
||||
### Browser sessions, logout and development origins
|
||||
|
||||
With auth enabled, the UI asks for credentials at `/login`. `POST /api/v1/auth/login` sets a signed session in an HttpOnly, `SameSite=Strict` cookie (default name `liqa_auth`) whose expiry matches the JWT lifetime. The cookie gets the `Secure` attribute when the request is HTTPS, including when the server sees `X-Forwarded-Proto: https`; serve production traffic over HTTPS and configure trusted proxy headers accordingly. JavaScript cannot read the token. `POST /api/v1/auth/logout` revokes the presented token and clears the cookie. Revoked tokens remain rejected until their expiration; deleted accounts also cause their tokens to be rejected on the next authentication.
|
||||
|
||||
Expired revocation rows are removed at startup and by `AUTH_REVOKED_TOKEN_CLEANUP_CRON` (default `0 3 * * *`, daily at 03:00 server time). The cleanup is not scheduled when authentication is disabled. Browser run notifications use the authenticated `GET /api/v1/scenarios/runs/events` event stream.
|
||||
|
||||
For local Vite development, the server's default CORS origins are `http://localhost:5173` and `http://127.0.0.1:5173` outside production. Vite has no API proxy: set `VITE_API_URL=http://localhost:3000/api/v1` when using a local server, or use `npm -w client run dev:compose-api` to target `http://localhost:13000`. The API's default CORS list also permits the compose origins `http://localhost:13000` and `http://127.0.0.1:13000` in production. Keep the UI and API on the same host name (`localhost` with `localhost`, or `127.0.0.1` with `127.0.0.1`) so the strict cookie remains same-site. For a different origin, set `CORS_ORIGINS` to the exact comma-separated UI origins; use HTTPS in deployed environments.
|
||||
|
||||
**Changing the schema** (adding or changing an entity):
|
||||
|
||||
1. Change the entity and build (`npm -w server run build`).
|
||||
@@ -136,7 +192,7 @@ Watch mode:
|
||||
npm -w server run test:watch
|
||||
```
|
||||
|
||||
Print the NestJS logs of the test app (they're silenced by default; `DEBUG=test`):
|
||||
Server application logs use debug output during tests. They remain quiet unless the `test` namespace is enabled. To see NestJS and application logs:
|
||||
|
||||
```bash
|
||||
npm -w server run test:debug
|
||||
@@ -204,6 +260,8 @@ The root `Dockerfile` builds a single image with the whole application: it build
|
||||
|
||||
The runtime image uses Playwright's headless-only Chromium build (`chromium-headless-shell`) with just the shared libraries it links against, plus DejaVu and Liberation fonts (Liberation is metric-compatible with Arial/Times, so pages lay out as they would with those fonts). All browser launches are headless, so the full desktop Chromium isn't installed. If a new Playwright version needs another library, `ldd` on the `chrome-headless-shell` binary in the image lists what's missing.
|
||||
|
||||
To keep the image small, production dependencies and the browser are installed in a separate `runtime-deps` stage, which drops what nothing loads at runtime (source maps, TypeScript sources and declarations, docs, TypeORM's browser build, better-sqlite3's C sources, and Playwright's ffmpeg, which is only used for video recording). The runtime stage is plain `debian:bookworm-slim` with only the `node` binary copied in, so the image has no `npm`, `npx`, `yarn` or `corepack`. If a package starts failing in the image only, check whether it reads one of the deleted file types at runtime.
|
||||
|
||||
```bash
|
||||
docker compose build
|
||||
```
|
||||
@@ -216,6 +274,44 @@ docker compose build --no-cache
|
||||
|
||||
---
|
||||
|
||||
## Licenses
|
||||
|
||||
The project is MIT-licensed ([LICENSE](../LICENSE)); the `license` field in all three `package.json` files says the same.
|
||||
|
||||
The image ships third-party code: the server's production dependencies, the client's production dependencies (bundled into its build), the Node.js binary, Chromium and Debian packages. Their notices are in the image as follows:
|
||||
|
||||
- **npm packages and Node.js**: the `licenses` stage of the Dockerfile runs `scripts/third-party-licenses.mjs`, which writes the project's LICENSE followed by every production dependency of both workspaces with its license files (or, for the few packages that ship none, the declared license, author and source). Node.js's LICENSE for the exact version in the image is fetched from GitHub and appended. The result is `/app/client/licenses.txt`, which the app serves at `/licenses.txt`. The build fails if a package has no license information at all.
|
||||
- **Server packages' own license files** stay in `node_modules`: the slimming step deletes Markdown files except `LICENSE*`, `NOTICE*` and `COPYING*`.
|
||||
- **Chromium**: `LICENSE.headless_shell` next to the binary under `/ms-playwright`.
|
||||
- **Debian packages**: `/usr/share/doc/*/copyright`.
|
||||
|
||||
The image also has the OCI labels `org.opencontainers.image.licenses=MIT`, `source`, `title` and `version` (CI passes the version as the `VERSION` build arg).
|
||||
|
||||
To check the notices locally, or to review a new dependency's license, run from the repository root:
|
||||
|
||||
```bash
|
||||
node scripts/third-party-licenses.mjs > /tmp/licenses.txt
|
||||
```
|
||||
|
||||
Before adding a dependency, check its license is compatible with MIT distribution (permissive licenses such as MIT, ISC, BSD, Apache-2.0 are; copyleft ones such as GPL or AGPL need a closer look).
|
||||
|
||||
---
|
||||
|
||||
## CI (Gitea Actions)
|
||||
|
||||
`.gitea/workflows/ci.yml` runs on pushes to `master`, on pull requests and on release tags (`vX.Y.Z`):
|
||||
|
||||
- **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; always runs on tags): lint (no warnings allowed), type-check, tests, build.
|
||||
- **client** (skipped if nothing under `client/` changed; always runs on tags): lint (no warnings allowed), build, Storybook tests in headless Chromium.
|
||||
- **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.
|
||||
|
||||
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).
|
||||
|
||||
Jobs clone the repository from the address the runner was registered with. If that's an internal hostname (such as `http://gitea:3000` from Gitea's compose network), job containers can't resolve it: either register the runner with the public URL, or set `container.network` in the act_runner config to Gitea's Docker network so jobs join it.
|
||||
|
||||
---
|
||||
|
||||
## Running with Docker Compose
|
||||
|
||||
Start (detached):
|
||||
@@ -230,7 +326,7 @@ Build and start in one step:
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Everything is served by the single `liqa` container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs` and health at `/health`. Unknown paths outside those routes get the client's `index.html`, so client-side routes survive a page refresh.
|
||||
Everything is served by the single `liqa` container at **http://localhost:13000**: the UI at `/`, the REST API at `/api/v1`, MCP at `/mcp`, Swagger at `/docs`, health at `/health` and the client's public configuration at `/manifest.json`. Unknown paths outside those routes get the client's `index.html`, so client-side routes survive a page refresh.
|
||||
|
||||
When switching from the old two-container setup (`server` + `client`), remove the old containers with `docker compose up -d --build --remove-orphans`.
|
||||
|
||||
@@ -278,7 +374,7 @@ client/
|
||||
src/
|
||||
api/ API client (client.ts) and types (types.ts)
|
||||
components/ modals/ - run, export, export logs and delete confirmation modals
|
||||
hooks/ useTheme, usePageTitle, useRunDefaults, useImportFile
|
||||
hooks/ useTheme, usePageTitle, useRunDefaults, useImportFile, useRunNotifications
|
||||
i18n/ i18next bootstrap + locales/en.json
|
||||
lib/ highlight.js setup, API error toast events
|
||||
pages/ scenario/, run/, snippet/, credential/, environment/, session/, import/
|
||||
@@ -305,4 +401,4 @@ client/
|
||||
|
||||
Light/dark theme is toggled by the `ThemeSwitcher` button in the sidebar footer. The selection is persisted to `localStorage` and applied as `data-theme` on `<html>` before React mounts (anti-FOUC inline script in `index.html`).
|
||||
|
||||
The sidebar footer also shows the app version read from the workspace root `package.json` and injected via Vite `define`.
|
||||
The sidebar footer also shows the server's app version from `/manifest.json` (see [architecture.md](architecture.md#client-client)), falling back to the client build's version (read from the workspace root `package.json` and injected via Vite `define`). If the two differ, the version's tooltip suggests reloading the page.
|
||||
+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.
|
||||
|
||||
Authentication is disabled by default. When `AUTH_ENABLED=true`, MCP requests must include a valid bearer token from the operator CLI (`user:token`); browser cookies are accepted by the HTTP API, but MCP clients should use the bearer header. For an MCP client that supports custom HTTP headers, configure the endpoint and header like this (replace the synthetic token with a privately issued token):
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://liqa.example/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer <synthetic-token>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Keep the token secret and renew it when it expires. See [development.md](development.md#operator-account-commands) for provisioning and token issuance. With auth disabled, omit the authorization header.
|
||||
|
||||
The server registers the following tools. All entity IDs are UUIDs; list tools are paginated (`page`, `limit`, and where noted `orderBy` / `orderDir`). Errors are returned as MCP tool errors (`isError: true`) with the message as text.
|
||||
|
||||
## Sessions
|
||||
@@ -61,7 +74,7 @@ The server registers the following tools. All entity IDs are UUIDs; list tools a
|
||||
| `export_scenario` | Export one scenario version (optional `version`, defaults to the latest) |
|
||||
| `import_scenario` | Import one scenario version; `version` is required (see "Versioning" in [scenario.md](scenario.md)) |
|
||||
| `import_yaml` | Import any mix of environments, credentials, snippets and scenarios from YAML (see "Import" in [scenario.md](scenario.md)) |
|
||||
| `export_e2e_test` | Export a scenario as a standalone Playwright test project (zip, base64) |
|
||||
| `export_e2e_test` | Export one scenario version as a standalone Playwright test project (zip, base64; optional `version`, defaults to the latest) |
|
||||
|
||||
Changes to scenario content (fields and steps) create a new scenario version; credential assignments and files are not versioned.
|
||||
|
||||
|
||||
+40
-5
@@ -32,22 +32,37 @@ Available on `context`:
|
||||
- `context.env`: shallow copy of the environment's key/value map
|
||||
- `context.getEnv(key)`: environment value lookup (throws if missing)
|
||||
- `context.getCredential(alias)`: payload of the credential assigned to the scenario under `alias` (parsed JSON when the data is JSON; throws if missing)
|
||||
- `context.getStepOutput(order)`: output of a previous step by absolute order (`1`, `2`, ...) or relative (`-1` = previous step); `null` if there is none
|
||||
- `context.getStepOutput(order)`: async (`await` it); output of a previous step by absolute order (`1`, `2`, ...) or relative (`-1` = previous step); `null` if there is none
|
||||
- `context.dumpDom(selector?)`: simplified DOM snapshot of the page (or of one element)
|
||||
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`: run log entries
|
||||
- `context.assert(() => boolean, description)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw
|
||||
- `context.log(...args)`, `context.warn(...args)`, `context.error(...args)`, `context.debug(...args)`: run log entries
|
||||
- `context.assert(() => boolean, description, details?)`: runs the arrow function and requires it to return `true`. Logs `description` (as a `log` entry on success, as an `error` entry on failure or exception), then throws to stop the step if the function returned anything other than `true` or threw. On failure, the log entry's data holds `details` (if given) and the exception message (as `error`, if the function threw)
|
||||
- `context.runSnippet(name, ...args)`: runs stored snippet code with the same context; the snippet receives the extra arguments as `...args`. `name` is the snippet alias for its latest version, or `alias@<version>` (e.g. `login@3`) to pin a specific version. Snippet start/finish/failure is logged
|
||||
- `context.getScenarioFiles(opts?)`: list files uploaded to the scenario (`limit`, `offset`), including their path on disk
|
||||
- `context.downloadFile(url, opts?)`: fetch `url` and save the result as a run file (requires a real scenario run — throws when invoked ad hoc, e.g. via the `exec_code` MCP tool). `opts` may include `method`, `headers`, `body`, `filename`. `url` also accepts a `data:` URI (`data:<mediaType>;base64,<data>` or `data:<mediaType>,<percent-encoded data>`) to save content generated in-script (e.g. a credential JWT) directly, without an actual network fetch.
|
||||
|
||||
Also in scope:
|
||||
|
||||
- `console`: proxied to run logs (`log`, `warn`, `error`, etc.)
|
||||
- `console`: proxied to run logs (`log`/`info` → `log`, `warn`, `error`, `debug`)
|
||||
- `expect`: Playwright's `expect` (e.g. `await expect(context.page.locator("h1")).toHaveText("Done")`)
|
||||
|
||||
Code is syntax-checked before it runs, and executes in the server process: it's trusted code, not sandboxed.
|
||||
|
||||
Step run logs also include automatic "Step N started / passed / failed" entries.
|
||||
The step and snippet editors have a (?) button next to the Code label that opens a reference of this runtime in the UI. Its content is [client/src/components/modals/code-help.md](../client/src/components/modals/code-help.md): keep it in sync with this section when the `context` API changes.
|
||||
|
||||
## Run logs
|
||||
|
||||
Each run log entry (`level`, `message`, `createdAt`) also carries a `context`: where the message was generated. Contexts:
|
||||
|
||||
- `step:<N>`: the step a log entry belongs to, including the automatic "Step N started / passed / failed" entries ("Step N passed" carries the step's return value as `data`; "Step N failed" for an assertion failure names only the assertion, whose details are in the `assertion:fail` entry)
|
||||
- `snippet:<alias>`: entries logged while `context.runSnippet(alias, ...)` is running, including its own automatic "started"/"finished"/"failed" entries. A snippet calling another snippet tags entries with the innermost running snippet's alias
|
||||
- `assertion:pass` / `assertion:fail`: `context.assert()`'s own log entry
|
||||
- `run`: run-level entries not tied to a step (e.g. a scenario timeout, or the Playwright trace upload notice)
|
||||
|
||||
`context.log`/`warn`/`error` (and `console.log`/etc.) split their arguments: strings/numbers/booleans are joined into `message`, while object/array arguments are kept out of it and stored as `data` (JSON), so `message` stays a stable string regardless of an object's shape. With one object argument `data` is that object; with more than one, `data` is an array of them. E.g. `context.log("Saved credential as run file:", fileMeta)` logs `message: "Saved credential as run file:"` with `fileMeta` as `data`, shown pretty-printed and separately from the message in the UI.
|
||||
|
||||
On the run page, a `data` block whose pretty-printed JSON is over 256 bytes or 5 lines starts collapsed behind a "Show data" toggle (set by `RUN_LOG_DATA_COLLAPSE_BYTES` / `RUN_LOG_DATA_COLLAPSE_LINES` and passed to the UI via `/manifest.json`). The "Expand data" / "Collapse data" button next to the Logs heading opens or closes all of them. "Copy logs" copies the currently filtered logs to the clipboard as plain text, with every `data` block expanded.
|
||||
|
||||
`GET /scenarios/:id/runs/:runId?q=...` and the exported CSV/Markdown logs (`GET /scenarios/:id/runs/:runId/export`) match `q` against both `message` and `context`.
|
||||
|
||||
## Versioning
|
||||
|
||||
@@ -99,6 +114,10 @@ steps:
|
||||
execCode: await context.page.goto(context.getEnv("base_url"));
|
||||
```
|
||||
|
||||
### E2e test export
|
||||
|
||||
`GET /scenarios/:id/export-e2e` (the "Export e2e test" button, the `export_e2e_test` MCP tool) exports one scenario version as a standalone Playwright test project, zipped as `<scenario>-v<N>-e2e-test.zip`. It takes an optional `version` (default: the latest). Snippets are bundled the same way as in the scenario export: the latest version for plain `runSnippet("alias")` calls, plus each version pinned with `alias@N`. The environment, credentials and files are the scenario's current ones; they are not versioned.
|
||||
|
||||
## Playwright traces
|
||||
|
||||
A run can record a [Playwright trace](https://playwright.dev/docs/trace-viewer) of its browser context (screenshots and DOM snapshots). When the run finishes, the trace is uploaded to the run's files as `trace.zip`. Download it from the run detail page, then open it with `npx playwright show-trace trace.zip` or at https://trace.playwright.dev.
|
||||
@@ -113,6 +132,20 @@ Traces are off by default because they often reach ~10 MB per run.
|
||||
|
||||
Traces are run artifacts, so they expire after `FILE_RUN_EXPIRATION_DAYS` like other run files.
|
||||
|
||||
## Run events and browser notifications
|
||||
|
||||
The server publishes run lifecycle events on a server-sent events (SSE) stream, `GET /api/v1/scenarios/runs/events`, regardless of how the run was started (UI, REST API, MCP or the scheduler). Each message is named after its `type` and carries a JSON body:
|
||||
|
||||
```json
|
||||
{ "type": "run.finished", "runId": "...", "scenarioId": "...", "scenarioName": "Login", "status": "pass", "at": "2026-01-01T12:00:00.000Z" }
|
||||
```
|
||||
|
||||
- `run.started` is sent when a run becomes `in_progress` (`status` is `in_progress`).
|
||||
- `run.finished` is sent exactly once per run, with the final `status` (`pass` or `fail`), including runs that fail during setup, time out, or are failed on server restart.
|
||||
- A `ping` event is sent every 25 s to keep idle connections open through proxies.
|
||||
|
||||
The UI uses this stream for opt-in browser notifications: the bell button in the side panel footer asks for the notification permission (granting it from the browser's own prompt or site settings works too) and then shows "Run started / passed / failed: <scenario>" notifications while the UI is open in a tab; clicking one opens the run. The bell is highlighted while notifications are on; turning them off is stored in the browser's `localStorage`. Browsers only offer notifications in a secure context (HTTPS or `localhost`), so over plain HTTP on another host the bell has no effect. When the permission is blocked, the button is disabled; re-allow it in the browser's site settings. Finished runs also refresh the runs lists immediately.
|
||||
|
||||
## Statuses
|
||||
|
||||
Run status:
|
||||
@@ -140,3 +173,5 @@ Run-step status:
|
||||
5. Assign credentials to scenario aliases when needed
|
||||
6. Run scenario
|
||||
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
+119
-608
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "liqa",
|
||||
"version": "1.22.0",
|
||||
"version": "1.26.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "liqa",
|
||||
"version": "1.22.0",
|
||||
"version": "1.26.0",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"server",
|
||||
"client"
|
||||
@@ -17,6 +18,7 @@
|
||||
},
|
||||
"client": {
|
||||
"name": "liqa-client",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"@tanstack/react-query": "^5.99.0",
|
||||
@@ -1021,9 +1023,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
"integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
"integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@@ -1038,9 +1040,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
|
||||
"integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
|
||||
"integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -1055,9 +1057,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1072,9 +1074,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/android-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1089,9 +1091,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1106,9 +1108,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1123,9 +1125,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1140,9 +1142,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1157,9 +1159,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
|
||||
"integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
|
||||
"integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -1174,9 +1176,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1191,9 +1193,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
|
||||
"integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
|
||||
"integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
@@ -1208,9 +1210,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
|
||||
"integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
|
||||
"integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
@@ -1225,9 +1227,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
|
||||
"integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
|
||||
"integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
@@ -1242,9 +1244,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
|
||||
"integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
|
||||
"integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@@ -1259,9 +1261,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
|
||||
"integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
|
||||
"integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
@@ -1276,9 +1278,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
|
||||
"integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
|
||||
"integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
@@ -1293,9 +1295,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1310,9 +1312,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1327,9 +1329,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1344,9 +1346,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1361,9 +1363,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1378,9 +1380,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/openharmony-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1395,9 +1397,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -1412,9 +1414,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
|
||||
"integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -1429,9 +1431,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
|
||||
"integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
|
||||
"integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
@@ -1446,9 +1448,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
|
||||
"integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -5400,13 +5402,6 @@
|
||||
"undici-types": ">=7.24.0 <7.24.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node/node_modules/undici-types": {
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/qs": {
|
||||
"version": "6.15.1",
|
||||
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz",
|
||||
@@ -8761,9 +8756,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
|
||||
"integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
|
||||
"integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
@@ -8774,32 +8769,32 @@
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.28.2",
|
||||
"@esbuild/android-arm": "0.28.2",
|
||||
"@esbuild/android-arm64": "0.28.2",
|
||||
"@esbuild/android-x64": "0.28.2",
|
||||
"@esbuild/darwin-arm64": "0.28.2",
|
||||
"@esbuild/darwin-x64": "0.28.2",
|
||||
"@esbuild/freebsd-arm64": "0.28.2",
|
||||
"@esbuild/freebsd-x64": "0.28.2",
|
||||
"@esbuild/linux-arm": "0.28.2",
|
||||
"@esbuild/linux-arm64": "0.28.2",
|
||||
"@esbuild/linux-ia32": "0.28.2",
|
||||
"@esbuild/linux-loong64": "0.28.2",
|
||||
"@esbuild/linux-mips64el": "0.28.2",
|
||||
"@esbuild/linux-ppc64": "0.28.2",
|
||||
"@esbuild/linux-riscv64": "0.28.2",
|
||||
"@esbuild/linux-s390x": "0.28.2",
|
||||
"@esbuild/linux-x64": "0.28.2",
|
||||
"@esbuild/netbsd-arm64": "0.28.2",
|
||||
"@esbuild/netbsd-x64": "0.28.2",
|
||||
"@esbuild/openbsd-arm64": "0.28.2",
|
||||
"@esbuild/openbsd-x64": "0.28.2",
|
||||
"@esbuild/openharmony-arm64": "0.28.2",
|
||||
"@esbuild/sunos-x64": "0.28.2",
|
||||
"@esbuild/win32-arm64": "0.28.2",
|
||||
"@esbuild/win32-ia32": "0.28.2",
|
||||
"@esbuild/win32-x64": "0.28.2"
|
||||
"@esbuild/aix-ppc64": "0.25.12",
|
||||
"@esbuild/android-arm": "0.25.12",
|
||||
"@esbuild/android-arm64": "0.25.12",
|
||||
"@esbuild/android-x64": "0.25.12",
|
||||
"@esbuild/darwin-arm64": "0.25.12",
|
||||
"@esbuild/darwin-x64": "0.25.12",
|
||||
"@esbuild/freebsd-arm64": "0.25.12",
|
||||
"@esbuild/freebsd-x64": "0.25.12",
|
||||
"@esbuild/linux-arm": "0.25.12",
|
||||
"@esbuild/linux-arm64": "0.25.12",
|
||||
"@esbuild/linux-ia32": "0.25.12",
|
||||
"@esbuild/linux-loong64": "0.25.12",
|
||||
"@esbuild/linux-mips64el": "0.25.12",
|
||||
"@esbuild/linux-ppc64": "0.25.12",
|
||||
"@esbuild/linux-riscv64": "0.25.12",
|
||||
"@esbuild/linux-s390x": "0.25.12",
|
||||
"@esbuild/linux-x64": "0.25.12",
|
||||
"@esbuild/netbsd-arm64": "0.25.12",
|
||||
"@esbuild/netbsd-x64": "0.25.12",
|
||||
"@esbuild/openbsd-arm64": "0.25.12",
|
||||
"@esbuild/openbsd-x64": "0.25.12",
|
||||
"@esbuild/openharmony-arm64": "0.25.12",
|
||||
"@esbuild/sunos-x64": "0.25.12",
|
||||
"@esbuild/win32-arm64": "0.25.12",
|
||||
"@esbuild/win32-ia32": "0.25.12",
|
||||
"@esbuild/win32-x64": "0.25.12"
|
||||
}
|
||||
},
|
||||
"node_modules/escalade": {
|
||||
@@ -16449,9 +16444,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "7.30.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.30.0.tgz",
|
||||
"integrity": "sha512-7QjA5O+GhM27do7Id6hQZpnYEd7WzHbs7/XIS9A1k+Gat/ZVF7Jmpzt68zL/205f65FYwDNLSjQemHPS8ReM/A==",
|
||||
"version": "7.24.6",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
|
||||
"integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
@@ -16820,490 +16815,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||
"integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"aix"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/android-arm": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
|
||||
"integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/android-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/android-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/darwin-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/darwin-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/freebsd-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/freebsd-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-arm": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
|
||||
"integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-ia32": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
|
||||
"integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-loong64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
|
||||
"integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-mips64el": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
|
||||
"integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
|
||||
"cpu": [
|
||||
"mips64el"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-ppc64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
|
||||
"integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-riscv64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
|
||||
"integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-s390x": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
|
||||
"integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/linux-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/netbsd-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/netbsd-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"netbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/openbsd-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/openbsd-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openbsd"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/openharmony-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"openharmony"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/sunos-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"sunos"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/win32-arm64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
|
||||
"integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/win32-ia32": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
|
||||
"integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/@esbuild/win32-x64": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
|
||||
"integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/vite/node_modules/esbuild": {
|
||||
"version": "0.25.12",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
|
||||
"integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"esbuild": "bin/esbuild"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@esbuild/aix-ppc64": "0.25.12",
|
||||
"@esbuild/android-arm": "0.25.12",
|
||||
"@esbuild/android-arm64": "0.25.12",
|
||||
"@esbuild/android-x64": "0.25.12",
|
||||
"@esbuild/darwin-arm64": "0.25.12",
|
||||
"@esbuild/darwin-x64": "0.25.12",
|
||||
"@esbuild/freebsd-arm64": "0.25.12",
|
||||
"@esbuild/freebsd-x64": "0.25.12",
|
||||
"@esbuild/linux-arm": "0.25.12",
|
||||
"@esbuild/linux-arm64": "0.25.12",
|
||||
"@esbuild/linux-ia32": "0.25.12",
|
||||
"@esbuild/linux-loong64": "0.25.12",
|
||||
"@esbuild/linux-mips64el": "0.25.12",
|
||||
"@esbuild/linux-ppc64": "0.25.12",
|
||||
"@esbuild/linux-riscv64": "0.25.12",
|
||||
"@esbuild/linux-s390x": "0.25.12",
|
||||
"@esbuild/linux-x64": "0.25.12",
|
||||
"@esbuild/netbsd-arm64": "0.25.12",
|
||||
"@esbuild/netbsd-x64": "0.25.12",
|
||||
"@esbuild/openbsd-arm64": "0.25.12",
|
||||
"@esbuild/openbsd-x64": "0.25.12",
|
||||
"@esbuild/openharmony-arm64": "0.25.12",
|
||||
"@esbuild/sunos-x64": "0.25.12",
|
||||
"@esbuild/win32-arm64": "0.25.12",
|
||||
"@esbuild/win32-ia32": "0.25.12",
|
||||
"@esbuild/win32-x64": "0.25.12"
|
||||
}
|
||||
},
|
||||
"node_modules/vitest": {
|
||||
"version": "4.1.11",
|
||||
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
|
||||
@@ -17413,9 +16924,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vitest/node_modules/chai": {
|
||||
"version": "6.2.2",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
|
||||
"integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
|
||||
"version": "6.3.0",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
|
||||
"integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -17935,7 +17446,7 @@
|
||||
},
|
||||
"server": {
|
||||
"name": "liqa-server",
|
||||
"license": "ISC",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
@@ -17953,6 +17464,7 @@
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"debug": "^4.4.3",
|
||||
"effect": "^3.21.0",
|
||||
"jsdom": "^29.0.2",
|
||||
"playwright": "^1.59.1",
|
||||
@@ -17976,7 +17488,6 @@
|
||||
"@types/mozilla__readability": "^0.4.2",
|
||||
"@types/node": "^25.5.2",
|
||||
"@types/supertest": "^7.2.0",
|
||||
"debug": "^4.4.3",
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"jest": "^30.3.0",
|
||||
|
||||
+3
-1
@@ -1,7 +1,9 @@
|
||||
{
|
||||
"name": "liqa",
|
||||
"version": "1.22.0",
|
||||
"version": "1.26.0",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
"author": "Andrii Arsenin",
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
},
|
||||
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installs liqa into a target directory: writes a compose.yaml pulling the
|
||||
# published image (git.hq.ars9.space/ars9/liqa) and creates ./data for the
|
||||
# SQLite database, so the install directory needs no copy of this repo.
|
||||
set -euo pipefail
|
||||
|
||||
REGISTRY_IMAGE="git.hq.ars9.space/ars9/liqa"
|
||||
|
||||
# Prompt on the terminal, not stdin: under `curl ... | bash` stdin is the
|
||||
# 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}"
|
||||
}
|
||||
|
||||
install_dir="$(ask "Install directory" "./liqa")"
|
||||
port="$(ask "Port to expose" "13000")"
|
||||
version="$(ask "Version to install" "latest")"
|
||||
|
||||
mkdir -p "$install_dir/data"
|
||||
|
||||
compose_file="$install_dir/compose.yaml"
|
||||
cat > "$compose_file" <<EOF
|
||||
services:
|
||||
liqa:
|
||||
image: ${REGISTRY_IMAGE}:${version}
|
||||
ports:
|
||||
- "${port}:3000"
|
||||
env_file:
|
||||
- path: .env
|
||||
required: false
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
restart: unless-stopped
|
||||
EOF
|
||||
|
||||
echo "Wrote $compose_file"
|
||||
echo "Created $install_dir/data"
|
||||
echo
|
||||
|
||||
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)."
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env node
|
||||
// Writes the license notices for everything the app ships to stdout: the
|
||||
// project's own LICENSE, then every production dependency of the client and
|
||||
// server workspaces with its license text, as installed in node_modules.
|
||||
//
|
||||
// node scripts/third-party-licenses.mjs > licenses.txt
|
||||
//
|
||||
// Run it from the repository root after `npm ci` (dev dependencies may be
|
||||
// installed too; only production dependencies are listed). Exits non-zero
|
||||
// when a package's license can't be determined.
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
const ROOT = process.cwd();
|
||||
const LICENSE_FILE = /^(licen[cs]e|copying|notice)(\.|-|$)/i;
|
||||
|
||||
const tree = JSON.parse(
|
||||
execFileSync("npm", ["ls", "--omit=dev", "--all", "--long", "--json"], {
|
||||
cwd: ROOT,
|
||||
encoding: "utf8",
|
||||
maxBuffer: 256 * 1024 * 1024,
|
||||
// npm ls exits non-zero on unmet optional peers; the JSON is still complete
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
}).toString() || "{}",
|
||||
);
|
||||
|
||||
const workspaces = new Set(
|
||||
(
|
||||
JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"))
|
||||
.workspaces ?? []
|
||||
).map((w) => path.resolve(ROOT, w)),
|
||||
);
|
||||
|
||||
/** name@version → { name, version, license, dir } */
|
||||
const packages = new Map();
|
||||
const walk = (node) => {
|
||||
for (const [name, dep] of Object.entries(node.dependencies ?? {})) {
|
||||
// Unmet optional peers have no path
|
||||
if (!dep.path) continue;
|
||||
// Workspace packages are our own code: list only their dependencies
|
||||
if (!workspaces.has(fs.realpathSync(dep.path))) {
|
||||
const key = `${name}@${dep.version}`;
|
||||
if (packages.has(key)) continue;
|
||||
packages.set(key, { name, version: dep.version, dir: dep.path });
|
||||
}
|
||||
walk(dep);
|
||||
}
|
||||
};
|
||||
walk(tree);
|
||||
|
||||
const manifestOf = (pkg) =>
|
||||
JSON.parse(fs.readFileSync(path.join(pkg.dir, "package.json"), "utf8"));
|
||||
|
||||
const licenseOf = (pkg) => {
|
||||
const manifest = manifestOf(pkg);
|
||||
const field = manifest.license ?? manifest.licenses;
|
||||
if (typeof field === "string") return field;
|
||||
if (Array.isArray(field)) return field.map((l) => l.type ?? l).join(" OR ");
|
||||
if (field?.type) return field.type;
|
||||
return null;
|
||||
};
|
||||
|
||||
const licenseTexts = (pkg) =>
|
||||
fs
|
||||
.readdirSync(pkg.dir)
|
||||
.filter(
|
||||
(f) =>
|
||||
LICENSE_FILE.test(f) && fs.statSync(path.join(pkg.dir, f)).isFile(),
|
||||
)
|
||||
.sort()
|
||||
.map((f) => fs.readFileSync(path.join(pkg.dir, f), "utf8").trim());
|
||||
|
||||
// For packages that ship no license file, record who to attribute and where
|
||||
// the full terms are
|
||||
const withoutLicenseFile = (pkg, license) => {
|
||||
const { author, repository, homepage } = manifestOf(pkg);
|
||||
const authorName = typeof author === "string" ? author : author?.name;
|
||||
const repo = typeof repository === "string" ? repository : repository?.url;
|
||||
return [
|
||||
`The package ships no license file; its package.json declares ${license}.`,
|
||||
authorName && `Author: ${authorName}`,
|
||||
(repo || homepage) && `Source: ${repo || homepage}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
};
|
||||
|
||||
const missing = [];
|
||||
const sections = [...packages.values()]
|
||||
.sort(
|
||||
(a, b) =>
|
||||
a.name.localeCompare(b.name) || a.version.localeCompare(b.version),
|
||||
)
|
||||
.map((pkg) => {
|
||||
const license = licenseOf(pkg);
|
||||
const texts = licenseTexts(pkg);
|
||||
if (!license && texts.length === 0)
|
||||
missing.push(`${pkg.name}@${pkg.version}`);
|
||||
const body =
|
||||
texts.length > 0 ? texts.join("\n\n") : withoutLicenseFile(pkg, license);
|
||||
return `${pkg.name}@${pkg.version}\nLicense: ${license ?? "see below"}\n\n${body}`;
|
||||
});
|
||||
|
||||
if (missing.length > 0) {
|
||||
console.error(`No license information for: ${missing.join(", ")}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const rule = "-".repeat(79);
|
||||
process.stdout.write(
|
||||
[
|
||||
fs.readFileSync(path.join(ROOT, "LICENSE"), "utf8").trim(),
|
||||
`${"=".repeat(79)}\n\nThird-party software\n\nThis application includes the following third-party packages (${sections.length}),\nunder their own licenses:`,
|
||||
...sections,
|
||||
].join(`\n\n${rule}\n\n`) + "\n",
|
||||
);
|
||||
@@ -6,10 +6,15 @@ module.exports = {
|
||||
transform: {
|
||||
'^.+\\.ts$': ['ts-jest', { tsconfig: 'test/tsconfig.json' }],
|
||||
},
|
||||
setupFiles: ['<rootDir>/test/logging.setup.js'],
|
||||
moduleNameMapper: {
|
||||
'^jsdom$': '<rootDir>/test/__mocks__/jsdom.ts',
|
||||
'^playwright$': '<rootDir>/test/__mocks__/playwright.ts',
|
||||
'^@mozilla/readability$': '<rootDir>/test/__mocks__/readability.ts',
|
||||
},
|
||||
testEnvironment: 'node',
|
||||
// Each suite builds a full Nest app in beforeAll. That takes well under a
|
||||
// second on an idle machine, but several seconds when every suite starts at
|
||||
// once on a busy CI runner, past Jest's default 5 s.
|
||||
testTimeout: 30_000,
|
||||
};
|
||||
+4
-3
@@ -10,6 +10,7 @@
|
||||
"migration:run": "node dist/database/migrate",
|
||||
"migration:show": "typeorm migration:show -d dist/database/data-source.js",
|
||||
"migration:generate": "typeorm migration:generate -d dist/database/data-source.js",
|
||||
"cli": "node dist/cli.js",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
"lint:fix": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||
@@ -18,8 +19,8 @@
|
||||
"test:watch": "jest --watch"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"author": "Andrii Arsenin",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.29.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
@@ -37,6 +38,7 @@
|
||||
"better-sqlite3": "^12.8.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.4",
|
||||
"debug": "^4.4.3",
|
||||
"effect": "^3.21.0",
|
||||
"jsdom": "^29.0.2",
|
||||
"playwright": "^1.59.1",
|
||||
@@ -60,7 +62,6 @@
|
||||
"@types/mozilla__readability": "^0.4.2",
|
||||
"@types/node": "^25.5.2",
|
||||
"@types/supertest": "^7.2.0",
|
||||
"debug": "^4.4.3",
|
||||
"eslint": "^10.2.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"jest": "^30.3.0",
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ScheduleModule } from "@nestjs/schedule";
|
||||
import { ServeStaticModule } from "@nestjs/serve-static";
|
||||
import { TypeOrmModule } from "@nestjs/typeorm";
|
||||
import { BrowserModule } from "./browser/browser.module";
|
||||
import { AuthModule } from "./auth/auth.module";
|
||||
import { clientStaticOptions } from "./common/client-static";
|
||||
import { dataSourceOptions } from "./database/data-source";
|
||||
import { AppConfig, validateAppConfig } from "./config/app.config";
|
||||
@@ -12,6 +13,7 @@ import { EnvironmentModule } from "./environment/environment.module";
|
||||
import { FileModule } from "./file/file.module";
|
||||
import { HealthModule } from "./health/health.module";
|
||||
import { ImportModule } from "./import/import.module";
|
||||
import { ManifestModule } from "./manifest/manifest.module";
|
||||
import { McpModule } from "./mcp/mcp.module";
|
||||
import { ScenarioModule } from "./scenario/scenario.module";
|
||||
import { SnippetModule } from "./snippet/snippet.module";
|
||||
@@ -35,6 +37,7 @@ import { SnippetModule } from "./snippet/snippet.module";
|
||||
dataSourceOptions(config.get("DB_PATH")),
|
||||
}),
|
||||
BrowserModule,
|
||||
AuthModule,
|
||||
EnvironmentModule,
|
||||
CredentialModule,
|
||||
ScenarioModule,
|
||||
@@ -43,6 +46,7 @@ import { SnippetModule } from "./snippet/snippet.module";
|
||||
ImportModule,
|
||||
McpModule,
|
||||
HealthModule,
|
||||
ManifestModule,
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -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 { ApiOperation, ApiResponse, ApiTags } from "@nestjs/swagger";
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
ApiTags,
|
||||
} from "@nestjs/swagger";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import { CredentialService } from "../credential/credential.service";
|
||||
import { EnvironmentService } from "../environment/environment.service";
|
||||
@@ -8,6 +13,7 @@ import { ExecDto } from "./dto/exec.dto";
|
||||
import { OpenDto } from "./dto/open.dto";
|
||||
|
||||
@ApiTags("browser")
|
||||
@ApiBearerAuth()
|
||||
@Controller()
|
||||
export class BrowserController {
|
||||
constructor(
|
||||
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
ScriptLogger,
|
||||
} from "../code-executor/code-executor.service";
|
||||
import { CodeExecutorService } from "../code-executor/code-executor.service";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import { createAppLogger } from "../common/app-logger";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import { SessionContextService } from "../session/session-context.service";
|
||||
import { SessionService } from "../session/session.service";
|
||||
@@ -28,7 +28,7 @@ export interface OpenResult {
|
||||
|
||||
@Injectable()
|
||||
export class BrowserService {
|
||||
private readonly logger = new TraceLogger(BrowserService.name);
|
||||
private readonly logger = createAppLogger(BrowserService.name);
|
||||
|
||||
constructor(
|
||||
private readonly sessionContextService: SessionContextService,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import "reflect-metadata";
|
||||
import dataSource from "./database/data-source";
|
||||
import { validateAppConfig } from "./config/app.config";
|
||||
import { PasswordService } from "./auth/password.service";
|
||||
import {
|
||||
OperatorCliError,
|
||||
createTerminalInput,
|
||||
runOperatorCommand,
|
||||
} from "./operator-cli/operator-cli";
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const config = validateAppConfig(process.env);
|
||||
if (!config.AUTH_ENABLED) {
|
||||
throw new OperatorCliError(
|
||||
"Operator account commands require AUTH_ENABLED=true.",
|
||||
);
|
||||
}
|
||||
|
||||
await dataSource.initialize();
|
||||
try {
|
||||
await runOperatorCommand(process.argv.slice(2), {
|
||||
dataSource,
|
||||
config,
|
||||
passwords: new PasswordService(),
|
||||
input: createTerminalInput(),
|
||||
output: { write: (message) => process.stdout.write(message) },
|
||||
});
|
||||
} finally {
|
||||
await dataSource.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
if (error instanceof OperatorCliError) {
|
||||
console.error(error.message);
|
||||
} else if (
|
||||
error instanceof Error &&
|
||||
error.message === "This command requires an interactive terminal."
|
||||
) {
|
||||
console.error(error.message);
|
||||
} else {
|
||||
console.error(
|
||||
"Operator command failed. Check AUTH_ENABLED, DB_PATH, and that database migrations are up to date.",
|
||||
);
|
||||
}
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -8,7 +8,7 @@ import { parse } from "acorn";
|
||||
import type { BrowserContext, Page } from "playwright";
|
||||
import { URL } from "node:url";
|
||||
import { downloadFile as downloadFileImpl } from "../common/file-downloader";
|
||||
import { TraceLogger } from "../common/trace-logger";
|
||||
import { createAppLogger } from "../common/app-logger";
|
||||
import type { EnvironmentData } from "../environment/environment.entity";
|
||||
import type { FileStorageService } from "../file/file-storage.service";
|
||||
import type { DomNode } from "./dom-helpers";
|
||||
@@ -18,9 +18,38 @@ export interface ExecResult {
|
||||
result: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown by `context.assert`. Its `message` includes the failure reason;
|
||||
* `summary` doesn't, so failure reports that follow the `assertion:fail` log
|
||||
* entry (which already holds the details) can stay short.
|
||||
*/
|
||||
export class AssertionFailedError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly summary: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "AssertionFailedError";
|
||||
}
|
||||
}
|
||||
|
||||
/** The `AssertionFailedError` behind `err` (directly or via `cause`), if any. */
|
||||
export function findAssertionFailure(
|
||||
err: unknown,
|
||||
): AssertionFailedError | null {
|
||||
for (let e = err; e instanceof Error; e = (e as { cause?: unknown }).cause) {
|
||||
if (e instanceof AssertionFailedError) return e;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export type ScriptLogger = (
|
||||
level: "log" | "warn" | "error",
|
||||
level: "debug" | "log" | "warn" | "error",
|
||||
message: string,
|
||||
/** Where the message was generated, e.g. "step:2", "snippet:login", "assertion:pass". */
|
||||
context?: string | null,
|
||||
/** Structured payload attached to the message (e.g. a created file's metadata). */
|
||||
data?: unknown,
|
||||
) => void;
|
||||
|
||||
/** The `context` object available inside user scripts as the sole argument. */
|
||||
@@ -42,14 +71,17 @@ export interface ScriptContext {
|
||||
log: (...args: unknown[]) => void;
|
||||
warn: (...args: unknown[]) => void;
|
||||
error: (...args: unknown[]) => void;
|
||||
debug: (...args: unknown[]) => void;
|
||||
/**
|
||||
* Runs `fn` and requires it to return `true`. Logs the outcome under
|
||||
* `description`, then throws if `fn` returned anything other than `true`
|
||||
* or threw an exception.
|
||||
* or threw an exception. On failure, `details` (and the exception message,
|
||||
* if any) are stored as the log entry's data.
|
||||
*/
|
||||
assert: (
|
||||
fn: () => boolean | Promise<boolean>,
|
||||
description: string,
|
||||
details?: unknown,
|
||||
) => Promise<void>;
|
||||
/** Runs a named snippet with the same context, plus any extra positional args. */
|
||||
runSnippet: (alias: string, ...args: unknown[]) => Promise<unknown>;
|
||||
@@ -70,6 +102,8 @@ export interface ExecContext {
|
||||
browser: BrowserContext;
|
||||
code: string;
|
||||
log?: ScriptLogger;
|
||||
/** Base log context for this execution, e.g. "step:2". */
|
||||
logContext?: string | null;
|
||||
getStepOutput?: (order: number) => Promise<unknown>;
|
||||
credentials?: Record<string, unknown>;
|
||||
environment?: EnvironmentData | null;
|
||||
@@ -81,7 +115,7 @@ export interface ExecContext {
|
||||
|
||||
@Injectable()
|
||||
export class CodeExecutorService {
|
||||
private readonly logger = new TraceLogger(CodeExecutorService.name);
|
||||
private readonly logger = createAppLogger(CodeExecutorService.name);
|
||||
|
||||
/**
|
||||
* Validates `code` by wrapping it in an async function body and attempting
|
||||
@@ -110,6 +144,7 @@ export class CodeExecutorService {
|
||||
browser,
|
||||
code,
|
||||
log,
|
||||
logContext,
|
||||
getStepOutput,
|
||||
credentials,
|
||||
environment,
|
||||
@@ -120,10 +155,44 @@ export class CodeExecutorService {
|
||||
} = ctx;
|
||||
const scriptLog: ScriptLogger =
|
||||
log ?? ((level, msg) => this.logger[level](msg));
|
||||
const toStr = (args: unknown[]) =>
|
||||
args
|
||||
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
|
||||
.join(" ");
|
||||
|
||||
// Splits console/log args into a plain-text message (strings, numbers, ...)
|
||||
// and a structured data payload (objects/arrays), logged separately so the
|
||||
// message stays a stable string regardless of the object's shape.
|
||||
const splitLogArgs = (
|
||||
args: unknown[],
|
||||
): { message: string; data: unknown } => {
|
||||
const strings: string[] = [];
|
||||
const objects: unknown[] = [];
|
||||
for (const a of args) {
|
||||
if (a !== null && typeof a === "object") {
|
||||
objects.push(a);
|
||||
} else {
|
||||
strings.push(String(a));
|
||||
}
|
||||
}
|
||||
return {
|
||||
message: strings.join(" "),
|
||||
data: objects.length === 0 ? null : objects.length === 1 ? objects[0] : objects,
|
||||
};
|
||||
};
|
||||
|
||||
// Innermost running snippet (if any) tags log entries; falls back to
|
||||
// logContext (e.g. the current step) outside of any runSnippet call.
|
||||
const contextStack: string[] = logContext ? [logContext] : [];
|
||||
const currentContext = (): string | null =>
|
||||
contextStack.length > 0 ? contextStack[contextStack.length - 1] : null;
|
||||
const emit = (
|
||||
level: "debug" | "log" | "warn" | "error",
|
||||
message: string,
|
||||
contextOverride?: string,
|
||||
data?: unknown,
|
||||
): void =>
|
||||
scriptLog(level, message, contextOverride ?? currentContext(), data);
|
||||
const emitArgs = (level: "debug" | "log" | "warn" | "error", args: unknown[]): void => {
|
||||
const { message, data } = splitLogArgs(args);
|
||||
emit(level, message, undefined, data);
|
||||
};
|
||||
|
||||
const credMap: Record<string, unknown> = credentials ?? {};
|
||||
const envData: EnvironmentData = environment ?? {};
|
||||
@@ -133,11 +202,11 @@ export class CodeExecutorService {
|
||||
let scriptContext: ScriptContext;
|
||||
|
||||
const fakeConsole = {
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
|
||||
info: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
debug: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
log: (...args: unknown[]) => emitArgs("log", args),
|
||||
warn: (...args: unknown[]) => emitArgs("warn", args),
|
||||
error: (...args: unknown[]) => emitArgs("error", args),
|
||||
info: (...args: unknown[]) => emitArgs("log", args),
|
||||
debug: (...args: unknown[]) => emitArgs("debug", args),
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -145,12 +214,14 @@ export class CodeExecutorService {
|
||||
page,
|
||||
browser,
|
||||
dumpDom: (selector?: string) => dumpDom(page, selector),
|
||||
log: (...args: unknown[]) => scriptLog("log", toStr(args)),
|
||||
warn: (...args: unknown[]) => scriptLog("warn", toStr(args)),
|
||||
error: (...args: unknown[]) => scriptLog("error", toStr(args)),
|
||||
log: (...args: unknown[]) => emitArgs("log", args),
|
||||
warn: (...args: unknown[]) => emitArgs("warn", args),
|
||||
error: (...args: unknown[]) => emitArgs("error", args),
|
||||
debug: (...args: unknown[]) => emitArgs("debug", args),
|
||||
assert: async (
|
||||
fn: () => boolean | Promise<boolean>,
|
||||
description: string,
|
||||
details?: unknown,
|
||||
): Promise<void> => {
|
||||
let passed: boolean;
|
||||
let failureReason: string | undefined;
|
||||
@@ -161,14 +232,24 @@ export class CodeExecutorService {
|
||||
failureReason = (err as Error).message;
|
||||
}
|
||||
if (passed) {
|
||||
scriptLog("log", `Assertion passed: ${description}`);
|
||||
emit("log", description, "assertion:pass");
|
||||
return;
|
||||
}
|
||||
const message = failureReason
|
||||
? `Assertion failed: ${description} (${failureReason})`
|
||||
: `Assertion failed: ${description}`;
|
||||
scriptLog("error", message);
|
||||
throw new Error(message);
|
||||
const failureData =
|
||||
failureReason !== undefined || details !== undefined
|
||||
? {
|
||||
...(failureReason !== undefined && { error: failureReason }),
|
||||
...(details !== undefined && { details }),
|
||||
}
|
||||
: undefined;
|
||||
emit("error", message, "assertion:fail", failureData);
|
||||
throw new AssertionFailedError(
|
||||
message,
|
||||
`Assertion failed: ${description}`,
|
||||
);
|
||||
},
|
||||
getStepOutput: getStepOutput ?? (() => Promise.resolve(null)),
|
||||
getCredential: (alias: string): unknown => {
|
||||
@@ -197,7 +278,9 @@ export class CodeExecutorService {
|
||||
if (snippetCode == null) {
|
||||
throw new Error(`Snippet alias "${alias}" not found`);
|
||||
}
|
||||
scriptLog("log", `Snippet "${alias}" started`);
|
||||
const snippetContext = `snippet:${alias}`;
|
||||
contextStack.push(snippetContext);
|
||||
emit("log", `Snippet "${alias}" started`, snippetContext);
|
||||
const snippetFn = new Function(
|
||||
"context",
|
||||
"console",
|
||||
@@ -212,14 +295,17 @@ export class CodeExecutorService {
|
||||
args,
|
||||
playwrightExpect,
|
||||
);
|
||||
scriptLog("log", `Snippet "${alias}" finished`);
|
||||
emit("log", `Snippet "${alias}" finished`, snippetContext);
|
||||
return snippetResult;
|
||||
} catch (err) {
|
||||
scriptLog(
|
||||
emit(
|
||||
"error",
|
||||
`Snippet "${alias}" failed: ${(err as Error).message}`,
|
||||
`Snippet "${alias}" failed: ${findAssertionFailure(err)?.summary ?? (err as Error).message}`,
|
||||
snippetContext,
|
||||
);
|
||||
throw err;
|
||||
} finally {
|
||||
contextStack.pop();
|
||||
}
|
||||
},
|
||||
getScenarioFiles: async (opts?: { limit?: number; offset?: number }) => {
|
||||
|
||||
@@ -26,6 +26,11 @@ export class ExecContextBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
logContext(logContext: string): this {
|
||||
this.ctx.logContext = logContext;
|
||||
return this;
|
||||
}
|
||||
|
||||
getStepOutput(fn: (order: number) => Promise<unknown>): this {
|
||||
this.ctx.getStepOutput = fn;
|
||||
return this;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ const SERVER_ROUTES = [
|
||||
"/docs{*path}",
|
||||
"/health",
|
||||
"/healthz",
|
||||
"/manifest.json",
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 { getTraceId } from "./trace-context";
|
||||
|
||||
/** Runtime console logger. Output is always written using Nest's console behavior. */
|
||||
export class TraceLogger extends ConsoleLogger {
|
||||
constructor(context?: string, options: ConsoleLoggerOptions = {}) {
|
||||
super(context as string, options);
|
||||
@@ -10,6 +11,11 @@ export class TraceLogger extends ConsoleLogger {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
protected override formatContext(context: string): string {
|
||||
const traceId = getTraceId();
|
||||
return super.formatContext(traceId ? `${context}:${traceId}` : context);
|
||||
}
|
||||
|
||||
protected override formatMessage(
|
||||
logLevel: LogLevel,
|
||||
message: unknown,
|
||||
@@ -22,10 +28,4 @@ export class TraceLogger extends ConsoleLogger {
|
||||
const level = this.colorize(logLevel.toUpperCase(), logLevel);
|
||||
return `${this.getTimestamp()} ${level} ${contextMessage}${output}${timestampDiff}\n`;
|
||||
}
|
||||
|
||||
protected override formatContext(context: string): string {
|
||||
const traceId = getTraceId();
|
||||
const traced = traceId ? `${context}:${traceId}` : context;
|
||||
return super.formatContext(traced);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import "reflect-metadata";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import {
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsString,
|
||||
@@ -10,12 +12,19 @@ import {
|
||||
|
||||
import { appPackage } from "../common/app-package";
|
||||
|
||||
import { durationSeconds } from "../common/interval";
|
||||
|
||||
export enum TraceMode {
|
||||
On = "on",
|
||||
RetainOnFailure = "retain-on-failure",
|
||||
Off = "off",
|
||||
}
|
||||
|
||||
export enum LogMode {
|
||||
Console = "console",
|
||||
Debug = "debug",
|
||||
}
|
||||
|
||||
export class AppConfig {
|
||||
/** `production` in the Docker image; also selects the default CORS origins. */
|
||||
@IsString()
|
||||
@@ -36,6 +45,10 @@ export class AppConfig {
|
||||
@IsString()
|
||||
APP_VERSION: string = appPackage().version;
|
||||
|
||||
/** Route application diagnostics through `debug` instead of the console. */
|
||||
@IsEnum(LogMode)
|
||||
LOG_MODE: LogMode = LogMode.Console;
|
||||
|
||||
@IsString()
|
||||
DB_PATH: string = "data/liqa.db";
|
||||
|
||||
@@ -64,15 +77,76 @@ export class AppConfig {
|
||||
@IsEnum(TraceMode)
|
||||
// Off by default: traces with screenshots and snapshots easily reach ~10 MB per run
|
||||
PLAYWRIGHT_TRACE_MODE: TraceMode = TraceMode.Off;
|
||||
|
||||
/** Run log data blocks over this many bytes (pretty-printed) start collapsed in the UI. */
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
RUN_LOG_DATA_COLLAPSE_BYTES: number = 256;
|
||||
|
||||
/** Run log data blocks over this many lines (pretty-printed) start collapsed in the UI. */
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
RUN_LOG_DATA_COLLAPSE_LINES: number = 5;
|
||||
|
||||
/** Authentication is opt-in so existing deployments remain unchanged. */
|
||||
@IsBoolean()
|
||||
AUTH_ENABLED: boolean = false;
|
||||
|
||||
/** Required only when AUTH_ENABLED is true. */
|
||||
@IsString()
|
||||
AUTH_JWT_SECRET: string = "";
|
||||
|
||||
/** Cookie name used for browser sessions. */
|
||||
@IsString()
|
||||
AUTH_COOKIE_NAME: string = "liqa_auth";
|
||||
|
||||
@IsString()
|
||||
AUTH_JWT_EXPIRES_IN: string = "24h";
|
||||
|
||||
@IsString()
|
||||
AUTH_REVOKED_TOKEN_CLEANUP_CRON: string = "0 3 * * *";
|
||||
}
|
||||
|
||||
export function validateAppConfig(config: Record<string, unknown>): AppConfig {
|
||||
const validated = plainToInstance(AppConfig, config, {
|
||||
const authEnabled = config.AUTH_ENABLED;
|
||||
if (
|
||||
authEnabled !== undefined &&
|
||||
authEnabled !== true &&
|
||||
authEnabled !== false &&
|
||||
authEnabled !== "true" &&
|
||||
authEnabled !== "false"
|
||||
) {
|
||||
throw new Error("AUTH_ENABLED must be either true or false.");
|
||||
}
|
||||
const normalized = {
|
||||
...config,
|
||||
AUTH_ENABLED: authEnabled === true || authEnabled === "true",
|
||||
};
|
||||
const validated = plainToInstance(AppConfig, normalized, {
|
||||
enableImplicitConversion: true,
|
||||
});
|
||||
const errors = validateSync(validated, { skipMissingProperties: false });
|
||||
if (errors.length > 0) {
|
||||
throw new Error(errors.toString());
|
||||
}
|
||||
if (validated.AUTH_ENABLED && !validated.AUTH_JWT_SECRET.trim()) {
|
||||
throw new Error("AUTH_JWT_SECRET must be set when AUTH_ENABLED=true.");
|
||||
}
|
||||
if (
|
||||
validated.AUTH_ENABLED &&
|
||||
durationSeconds(validated.AUTH_JWT_EXPIRES_IN) === null
|
||||
) {
|
||||
throw new Error(
|
||||
"AUTH_JWT_EXPIRES_IN must be a positive duration such as 30m, 1h, or 24h.",
|
||||
);
|
||||
}
|
||||
if (
|
||||
validated.AUTH_ENABLED &&
|
||||
!validated.AUTH_REVOKED_TOKEN_CLEANUP_CRON.trim()
|
||||
) {
|
||||
throw new Error(
|
||||
"AUTH_REVOKED_TOKEN_CLEANUP_CRON must be set when AUTH_ENABLED=true.",
|
||||
);
|
||||
}
|
||||
return validated;
|
||||
}
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user