Compare commits

...

17 Commits

Author SHA1 Message Date
claude code agent 227
e99c00a9ee test(review): pin full-transcript history past 50 rows + changelog (PR #202)
Address the PR #202 review (approve-with-comments). The only actionable
non-blocking item was the test-coverage suggestion: the source switch in
AiChatService.handle from findRecent(chatId, ws, 50) to findAllByChat(chatId,
ws) was not pinned by a test. handle() is a streaming method the project marks
as not unit-testable, so cover the behavioral guarantee it now relies on at the
repo/integration level — seed a chat of 60 messages and assert the default
findAllByChat (exactly how handle calls it) returns the FULL transcript in
chronological order, including the first turn the old 50-window would have
dropped.

Also document the behavior change under CHANGELOG [Unreleased] -> Changed.

The two stability items (token-budget trim before streamText; O(N) history
rebuild per turn) are deferred: the reviewer flagged both as non-blocking
conscious trade-offs aligned with the PR's stated goal, and the trim is a
larger architecture change out of scope for this follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 20:39:30 +03:00
claude_code
1f459d8d26 feat(ai-chat): load full transcript for model history (drop 50-msg window)
The per-turn model conversation was rebuilt via findRecent(chatId, ws, 50),
a sliding window that dropped the beginning of any chat longer than ~50 stored
rows. Switch streamChat to the existing findAllByChat, which loads the full
non-deleted transcript chronologically with a 5000-row memory-safety backstop
(keeps the newest rows + logs a warning on overflow) — a safety net, not a
conversational limit. Remove the now-unused findRecent method and update the
comments/log text that referenced it (findAllByChat now feeds both the Markdown
export and the model history).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 20:39:30 +03:00
claude_code
fad1aa0501 fix(db): move share-aliases migration spec out of migrations/
The #205 share-aliases feature placed share-aliases.migration.spec.ts
inside src/database/migrations/. Kysely's FileMigrationProvider loads
EVERY file in that folder as a migration, so `migration:latest` imported
the test file and crashed with "ReferenceError: describe is not defined"
(no Jest globals under tsx). That broke the migration step shared by the
e2e-server, e2e-mcp and integration-test (test/test) jobs.

Move the spec one level up to src/database/ (matching the existing
src/database/jsonb-bind.spec.ts convention) so the migration runner no
longer sees it, and fix its relative imports
(./migrations/... and ./types/...). Jest still picks it up via the
src/**/*.spec.ts test glob. Verified locally: 3 passed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 20:14:31 +03:00
claude_code
8bb4224a20 Merge branch 'develop' of https://gitea.vvzvlad.xyz/vvzvlad/gitmost into develop 2026-06-26 20:02:51 +03:00
13589b3973 Merge pull request 'feat(share): custom /l/:alias pretty links (share_aliases table) (#205)' (#214) from feat/205-share-aliases into develop
Reviewed-on: #214
2026-06-26 20:00:50 +03:00
claude_code
69fcccd6e8 docs(release): clarify tagging and merge flow
Update the release documentation to emphasize tagging on develop before merging to main, detail steps for pushing tags to both gitea and github, and explain the back‑merge and remote tag considerations.
2026-06-26 19:57:49 +03:00
claude_code
0db48f1706 chore(gitignore): add .claude/tmp/ to ignore list 2026-06-26 19:57:43 +03:00
claude_code
2e72a24d13 test(e2e): silence ts-jest allowJs warnings for editor-ext .js
The e2e transform matches .js (required so ESM-only node_modules like
nanoid/@sindresorhus get transpiled), which also sweeps in editor-ext's
prebuilt CommonJS dist/*.js. ts-jest then warns "Got a .js file to
compile while allowJs is not set to true" for each footnote file. The
.js match cannot be dropped without reintroducing the ESM load errors, so
enable allowJs for ts-jest via an inline tsconfig override (merged with
apps/server/tsconfig.json — decorators/paths/module stay intact).

Verified locally: 0 allowJs warnings, app still compiles and boots to the
Redis connection (no DI/metadata regressions).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:45:37 +03:00
claude_code
aad0a37cfd 0.94.1
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:33:57 +03:00
claude_code
50d3e7b476 style(editor): align footnote marker and center task checkbox
Remove top margin from the first paragraph in footnote definitions so the
marker aligns with the first line of text. Adjust the task‑list label to use
the editor line‑height variable for its height and center the checkbox
vertically, keeping it in line with the item’s first text line.
2026-06-26 19:24:13 +03:00
claude_code
bd62d906bb test(e2e): anchor top-level mcp comment on existing page text
With the image fix in place, the mcp e2e ran through every section and
failed only at the last one (comments): create_comment was hardened to
require an inline "selection" (exact text to anchor on) for a top-level
comment, but the test created one without a selection ("an inline
'selection' ... is required for a top-level comment").

Pass an inline selection ("Добавленный абзац.", a plain paragraph
re-imported in section 5 and still present at the comments stage). The
reply is unchanged: it carries a parentCommentId, so it is a reply and
needs no selection.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:16:55 +03:00
claude_code
e4b46ddbfc test(e2e): make server e2e actually boot (ESM chain + Fastify adapter)
The previous jest-config fix let the module graph load further and exposed
two more reasons the server e2e never passed since it was added:

1. ESM transform chain: AppModule pulls in editor-ext -> @tiptap ->
   @sindresorhus/slugify -> @sindresorhus/transliterate / escape-string-regexp,
   plus p-limit -> yocto-queue — all ESM-only. Extend the e2e
   transformIgnorePatterns whitelist to transform them (scoped packages need
   both the pnpm `@scope+name` and nested `@scope/name` path forms, hence
   `@sindresorhus[+/][a-z0-9-]+`). Verified locally: the graph now fully
   transforms and resolves.

2. Wrong HTTP adapter: Docmost runs on Fastify (main.ts uses FastifyAdapter)
   and does not depend on @nestjs/platform-express, but the scaffold test used
   the default createNestApplication() (Express) and died with
   "@nestjs/platform-express package is missing". Switch the test to
   FastifyAdapter + getInstance().ready(), close in afterEach. Verified locally:
   createNestApplication + app.init() now proceed to the live Redis/Postgres
   connection (the infra CI provides via services + migrations).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:13:22 +03:00
claude_code
deeec50b5f test(e2e): fix remaining server config and mcp image failures
Follow-up to the first e2e fix: with nanoid/editRes.edits resolved, the
suites failed one layer deeper. Both layers were never green since the
e2e jobs were added (non-blocking in CI), so the failures had stacked up.

server e2e (jest-e2e.json) — align module resolution/transform with the
working unit/integration jest configs so AppModule's full import graph
loads:
- moduleFileExtensions: add "tsx" (React-Email .tsx templates are pulled
  in via the auth controller chain).
- transform: ^.+\.(t|j)s$ -> ^.+\.(t|j)sx?$ so .tsx is transformed.
- moduleNameMapper: add ^src/(.*)$ -> <rootDir>/../src/$1 (code imports
  via the absolute 'src/...' alias). Verified locally: the module graph
  now fully resolves (only env vars, supplied by CI, remain).

mcp e2e (test-e2e.mjs) — insert_image/replace_image accept only http(s)
URLs the server fetches; the test passed local file paths and died with
"Invalid image URL". Serve the PNG bytes over a throwaway 127.0.0.1 HTTP
server (the Docmost server runs on the same CI host) and pass URLs. The
featPng negative test is untouched: replaceImage checks the attachmentId
and throws before fetching, so its local path is never validated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:54:42 +03:00
claude_code
7eefdad512 test(e2e): fix failing server and mcp e2e suites
Two unrelated CI failures on the 0.94.0 release PR:

- server e2e: jest-e2e.json lacked transformIgnorePatterns, so the
  ESM-only nanoid@5 package was loaded as CommonJS and crashed with
  "Cannot use import statement outside a module". Add the same
  node_modules whitelist already present in the unit and integration
  jest configs (nanoid|uuid|image-dimensions|marked|happy-dom|lib0).

- mcp e2e: test-e2e.mjs read editRes.edits, but editPageText() returns
  the per-edit results under `applied` (not `edits`), so editRes.edits
  was undefined and .every() threw. Read editRes.applied instead.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:34:56 +03:00
claude code agent 227
0643cd1d82 test(share): exercise 70-char title-slug clamp in alias redirect
The controller's buildPageSlug truncates the page title via
`title?.substring(0, 70)` before slugifying, but no test drove that
branch (the only titled case was 16 chars). Add a resolvable-alias
case with a 119-char title whose 70-char boundary falls mid-word and
assert the 302 target's slug reflects only the first 70 characters.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 18:05:21 +03:00
claude code agent 227
1043fe3b51 test(share): cover alias controllers; address PR #214 review
Add the two blocking test-coverage specs requested in the PR #214 review and
clear the cheap non-blocking items.

Must-fix:
- share-alias-redirect.controller.spec.ts: routing/leak guard for the public
  GET /l/:alias resolver (modeled on share-seo.controller.routing.spec). Pins
  302-to-canonical on a hit; SPA index without a 302 for unknown/dangling/
  unreadable aliases and a null workspace (no name-existence leak); defensive
  percent-decoding treated as unknown; self-hosted findFirst vs subdomain
  findByHostname workspace resolution; 404 when no built client index exists.
- share-alias.controller.spec.ts: authz gates with mocked PageRepo/ShareService/
  ShareAliasService/PageAccessService. Covers cross-workspace/nonexistent page
  -> NotFoundException, validateCanEdit, resolveReadableSharePage null ->
  BadRequestException, isSharingAllowed false -> ForbiddenException, set happy
  path delegation, remove() of a dangling alias (pageId null) skipping
  validateCanEdit but still deleting, and for-page validateCanView.

Cheap review items:
- Remove dead Logger import/field from ShareAliasRedirectController.
- Remove dead PagePermissionRepo import/dependency from ShareAliasController.
- Register the new share-alias UI strings in en-US and ru-RU catalogs.
- Add an [Unreleased]/Added CHANGELOG entry for /l/:alias (#205).
- Drop the tautological boilerplate assertions from the migration spec
  (exports up/down; runtime checks of typed entity literals).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 17:22:29 +03:00
claude code agent 227
fdeede003b feat(share): custom /l/:alias pretty links (share_aliases table) (#205)
Add a retargetable, human-readable vanity link namespace /l/<alias> that
sits alongside the untouched /share/... routes.

- New share_aliases table (workspace-scoped, UNIQUE(workspace_id, alias),
  page_id nullable ON DELETE SET NULL so the address outlives its target).
- ShareAliasRepo + ShareAliasService (create / no-op / 409 reassign guard /
  availability / request-time readable-target resolution through the single
  existing share boundary).
- Public ShareAliasRedirectController (GET /l/:alias) issues a 302 (never 301,
  the target is mutable) to the canonical /share/:key/p/:slug page; unknown /
  dangling / no-longer-readable aliases serve the SPA index with no leak.
  'l/:alias' excluded from the global /api prefix.
- Authenticated ShareAliasController (set/remove/availability/for-page).
- Shared ASCII-only normalize/validate util (server + client copies).
- Client: Custom address block in the share modal (live normalize + debounced
  availability + copy + reassign confirmation dialog).
- Unit tests: util, repo SQL-shape, service semantics, migration/entity sanity
  (server jest) + client alias util (vitest).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 06:28:26 +03:00
42 changed files with 2367 additions and 91 deletions

1
.gitignore vendored
View File

@@ -42,6 +42,7 @@ lerna-debug.log*
.nx/installation
.nx/cache
.claude/worktrees/
.claude/tmp/
# TypeScript incremental build artifacts
*.tsbuildinfo

View File

@@ -283,37 +283,46 @@ Vite SPA. Code is organized by feature under `apps/client/src/features/*` (mirro
### Cutting a release
The git tag is the source of truth for the displayed version (UI reads `git describe --tags`); the `package.json` bump is metadata only. Steps:
The git tag is the source of truth for the displayed version (the client UI reads `git describe --tags` via `vite.config.ts`); the `package.json` bump is metadata that backs the server `/version` endpoint (`version.service.ts`).
1. Make sure `main` is clean and pushed (`git status`, `git push`).
**Golden rule — tag on `develop` first, merge to `main` afterwards.** Cut the version-bump commit on `develop`, put the tag on *that* commit, and push it. Merge `develop` into `main` later (it does not block the tag or the release). Because the tag is in `develop`'s ancestry from the moment it is created, `git describe` on `develop` — and the `ghcr.io/vvzvlad/gitmost:develop` image — reports the new version immediately, with **no back-merge dance**. Do **not** tag `main`'s merge commit; that is the mistake described in the pitfall below (we hit it twice).
Steps:
1. Make sure `develop` is up to date, clean, and pushed to **both** remotes (`git status`; `git push gitea develop && git push github develop`).
2. Pick `vX.Y.Z` (SemVer): **minor** bump for a batch of features, **patch** for fixes only. Review what landed with `git log <last-tag>..HEAD --no-merges`.
3. Bump `"version"` to `X.Y.Z` in the **root** `package.json`, `apps/client/package.json`, and `apps/server/package.json` (keep all three in sync). Leave `packages/mcp` alone — it is versioned independently. Commit with the bare version as the subject, e.g. `0.91.0` (matches past bump commits).
4. Update `CHANGELOG.md` (Keep a Changelog format): add a `## [X.Y.Z] - YYYY-MM-DD` section summarising `git log vPREV..HEAD --no-merges` grouped by type (Breaking / Added / Changed / Fixed / Removed), and add the `compare/vPREV...vX.Y.Z` link at the bottom. Fold the bump + changelog into the release commit.
5. Tag the release commit with a **lightweight** tag (existing release tags are lightweight): `git tag vX.Y.Z`.
6. Push commit and tag: `git push origin main && git push origin vX.Y.Z`. Pushing the `v*` tag triggers `release.yml` (multi-arch GHCR images + a draft GitHub Release).
7. **Back-merge the release into `develop`** so develop builds report the new version: `git checkout develop && git merge --no-ff main && git push origin develop` (push to Gitea as well if that is the canonical remote).
3. Bump `"version"` to `X.Y.Z` in the **root** `package.json`, `apps/client/package.json`, and `apps/server/package.json` (keep all three in sync). Leave `packages/mcp` alone — it is versioned independently. Commit **on `develop`** with the bare version as the subject, e.g. `0.94.1` (matches past bump commits).
4. For a real release (skip for a bare hotfix tag), update `CHANGELOG.md` (Keep a Changelog format): add a `## [X.Y.Z] - YYYY-MM-DD` section summarising `git log vPREV..HEAD --no-merges` grouped by type (Breaking / Added / Changed / Fixed / Removed), and the `compare/vPREV...vX.Y.Z` link at the bottom. Fold it into the bump commit.
5. Tag that develop commit with a **lightweight** tag (existing release tags are lightweight): `git tag vX.Y.Z`.
6. Push the branch **and** the tag to **both** writable remotes — `git push <branch>` does **not** push tags, and tags are per-remote:
```bash
git push gitea develop && git push gitea vX.Y.Z
git push github develop && git push github vX.Y.Z
```
Pushing the `v*` tag to `github` triggers `release.yml` (multi-arch GHCR images + a draft GitHub Release). The tag *must* exist on `github`, because the `:develop` and release images are built there by GitHub Actions and `git describe` on the runner only sees the tags present on `github` (not your local clone or `gitea`).
7. Merge `develop` into `main` when ready (commonly later — this does not gate the release):
```bash
git checkout main
git merge --ff-only develop # or a merge commit if fast-forward is not possible
git push gitea main && git push github main
```
The tag is already reachable from `main` (it lives in the `develop` history that `main` now contains), so `main` reports `vX.Y.Z` too — no extra tagging needed.
#### Why develop keeps showing the *previous* version (and why step 7 matters)
#### Pitfall: tagging `main` instead of `develop` (the mistake to avoid)
The UI version is `git describe --tags --always` (see `vite.config.ts`), which walks **backwards from the current commit** and picks the **nearest tag reachable in that commit's ancestry**, then appends `-<commits-since-tag>-g<short-hash>`.
`git describe --tags --always` (see `vite.config.ts`) walks **backwards from the current commit** and picks the **nearest tag reachable in that commit's ancestry**, then appends `-<commits-since-tag>-g<short-hash>`.
The release tag (`vX.Y.Z`) is created on **`main`'s release merge commit**, and that commit is **not** in `develop`'s history. So until the release is back-merged, `git describe` on `develop` cannot see the new tag and falls back to the *previous* reachable tag. Result: every develop build — and the `ghcr.io/vvzvlad/gitmost:develop` image — keeps reporting e.g. `v0.91.0-NNN-g<hash>` even though `main` is already tagged `v0.93.0`. This is the classic git-flow pitfall: the version on `develop` does **not** advance just because a release was tagged on `main`.
The wrong flow we fell into twice: merge `develop` into `main` *first*, then tag `main`'s **release merge commit**. That merge commit is **not** in `develop`'s history, so `git describe` on `develop` cannot see the new tag and falls back to the *previous* reachable one. Result: every develop build — and the `ghcr.io/vvzvlad/gitmost:develop` image — keeps reporting e.g. `v0.93.0-NNN-g<hash>` even though a release was "cut". Tagging on `develop` (the golden rule above) avoids this entirely: the tag is in `develop`'s ancestry from the start, and `main` still gets it once `develop` is merged in.
Back-merging `main → develop` (step 7) pulls the tagged release commit into `develop`'s ancestry, after which develop builds correctly show `vX.Y.Z-NNN-g<hash>`. If `develop` already drifted (release tagged but never back-merged), just run step 7 now — no new tag is needed.
Second gotcha — the tag must exist on the remote CI builds from. `git describe` names a tag **ref**, not just a commit. The `:develop` and release images are built by GitHub Actions (`develop.yml` / `release.yml`, `actions/checkout` with `fetch-depth: 0`), so the version they print depends on which tags exist **on the `github` remote** — not on your local clone or on `gitea`. `git push <branch>` does **not** push tags; push them explicitly to **each** remote (`gitea` and `github`). A tag that only lives on `gitea` is invisible to the GitHub build.
##### The tag must also exist on the remote that CI builds from (multi-remote gotcha)
If you already tagged `main` (or `develop` still shows the old version), recover without re-tagging:
`git describe` names a tag **ref**, not just a commit — so the back-merge is *necessary but not sufficient*. The develop image is built by GitHub Actions (`develop.yml`, `actions/checkout` with `fetch-depth: 0`, then `git describe --tags --always`), so the version it prints depends on which tags exist **on the `github` remote**, not on your local clone or on `gitea`.
1. Make the tagged commit reachable from `develop` — either back-merge `main → develop` (`git checkout develop && git merge --no-ff main`), or confirm the tagged commit is already an ancestor of `develop`.
2. Make sure the tag exists on `github`: compare `git ls-remote --tags github` with `gitea`, and push the missing one (`git push github vX.Y.Z` / `git push gitea vX.Y.Z`). Pushing a `v*` tag to `github` also fires `release.yml` — expected, just be aware.
3. Re-run the develop build (`gh workflow run Develop`, or push any commit to `develop`) so `git describe` re-resolves with the tag now in scope.
This repo has two writable remotes — `gitea` (canonical, where commits land) and `github` (where the `:develop` and release images are built) — plus `upstream` (docmost, never push). **`git push <branch>` does NOT push tags**; tags must be pushed explicitly and *to each remote separately*. A release tag that only lives on `gitea` is invisible to the GitHub Actions build: even with the tagged commit fully in `develop`'s history (step 7 done), `git describe` on the GitHub runner falls back to the previous tag it *does* have, so the develop image keeps showing e.g. `v0.91.0-NNN` while `git describe` locally already says `v0.93.0-NN`.
Fix / checklist when develop still shows the old version after a back-merge:
1. Confirm the tag is missing on github: `git ls-remote --tags github` (compare with `gitea`).
2. Push it there: `git push github vX.Y.Z` (and `git push gitea vX.Y.Z` if it is missing on gitea too). Note: pushing a `v*` tag to `github` also triggers `release.yml` (multi-arch GHCR images + draft Release) — expected, but be aware.
3. Re-run the develop build (`gh workflow run Develop`, or push any commit to `develop`) so `git describe` re-resolves with the tag now present.
(The `git push origin ...` in steps 6–7 above is shorthand — there is no `origin` remote here; substitute `gitea` **and** `github` as appropriate, and always push release tags to both.)
(There is no `origin` remote here — push to `gitea` **and** `github` explicitly, and always push release tags to both.)
## Planning docs

View File

@@ -22,6 +22,16 @@ per-workspace rolling-day token budget.
### Added
- **Custom pretty-links for shared pages (`/l/:alias`).** A page editor can give
any publicly shared page a short, memorable, workspace-scoped vanity address
backed by a new `share_aliases` table. Hitting `/l/<alias>` issues a `302`
(never `301`, since the target is retargetable) to the canonical
`/share/<key>/p/<slug>` page; an unknown, dangling, or no-longer-readable alias
serves the plain SPA index so that the existence of a name never leaks. An
alias can be moved to another page (with a confirm-reassign guard) and the
foreign key is `ON DELETE SET NULL`, so deleting the target leaves a dangling
alias any workspace member can reclaim. (#205)
- **Persistent AI-chat history as the source of truth + server-side export.**
An assistant turn is now persisted to the database step by step: the row is
inserted upfront as `streaming` and updated as each agent step finishes, then
@@ -65,6 +75,15 @@ per-workspace rolling-day token budget.
### Changed
- **AI chat now feeds the model the full stored transcript.** The per-turn model
conversation was rebuilt from a sliding window of the 50 most recent stored
rows, which silently dropped the beginning of any longer chat. It is now
rebuilt from the complete non-deleted transcript in chronological order, so
the model sees every turn (a 5000-row backstop guards process memory — a
safety net far above any realistic chat, not a conversational limit). On a
very long chat this can eventually reach the model's context window; the
client already surfaces that as "start a new chat". (#202)
- **AI chat default provider is now `openai-compatible` (reasoning surfaced).**
For the `openai` driver the chat provider defaults to the openai-compatible
implementation, so a workspace pointing at z.ai/GLM/DeepSeek now streams the

View File

@@ -1,7 +1,7 @@
{
"name": "client",
"private": true,
"version": "0.94.0",
"version": "0.94.1",
"scripts": {
"dev": "node scripts/copy-vad-assets.mjs && vite",
"build": "node scripts/copy-vad-assets.mjs && tsc && vite build",

View File

@@ -1318,5 +1318,15 @@
"Protocol": "Protocol",
"How chat requests are sent and how reasoning is surfaced": "How chat requests are sent and how reasoning is surfaced",
"OpenAI-compatible (surfaces reasoning)": "OpenAI-compatible (surfaces reasoning)",
"OpenAI (official)": "OpenAI (official)"
"OpenAI (official)": "OpenAI (official)",
"Custom address": "Custom address",
"A short, memorable link you can point at any shared page.": "A short, memorable link you can point at any shared page.",
"Use 2-60 lowercase letters, digits and hyphens": "Use 2-60 lowercase letters, digits and hyphens",
"This address is already in use": "This address is already in use",
"Move custom address?": "Move custom address?",
"Move here": "Move here",
"The address \"{{alias}}\" currently points to \"{{title}}\". Move it to this page?": "The address \"{{alias}}\" currently points to \"{{title}}\". Move it to this page?",
"The address \"{{alias}}\" is already in use. Move it to this page?": "The address \"{{alias}}\" is already in use. Move it to this page?",
"Failed to set custom address": "Failed to set custom address",
"Failed to remove custom address": "Failed to remove custom address"
}

View File

@@ -1175,5 +1175,15 @@
"Protocol": "Протокол",
"How chat requests are sent and how reasoning is surfaced": "Как отправляются запросы чата и как показывается reasoning",
"OpenAI-compatible (surfaces reasoning)": "OpenAI-совместимый (показывает reasoning)",
"OpenAI (official)": "OpenAI (официальный)"
"OpenAI (official)": "OpenAI (официальный)",
"Custom address": "Пользовательский адрес",
"A short, memorable link you can point at any shared page.": "Короткая запоминающаяся ссылка, которую можно направить на любую опубликованную страницу.",
"Use 2-60 lowercase letters, digits and hyphens": "Используйте 2–60 строчных букв, цифр и дефисов",
"This address is already in use": "Этот адрес уже занят",
"Move custom address?": "Переместить пользовательский адрес?",
"Move here": "Переместить сюда",
"The address \"{{alias}}\" currently points to \"{{title}}\". Move it to this page?": "Адрес «{{alias}}» сейчас указывает на «{{title}}». Переместить его на эту страницу?",
"The address \"{{alias}}\" is already in use. Move it to this page?": "Адрес «{{alias}}» уже используется. Переместить его на эту страницу?",
"Failed to set custom address": "Не удалось задать пользовательский адрес",
"Failed to remove custom address": "Не удалось удалить пользовательский адрес"
}

View File

@@ -104,6 +104,19 @@
min-width: 0;
}
/* The inner editable paragraph inherits `.ProseMirror p { margin: 0.5em 0 }`,
which pushes the first text line ~0.5em below the "N." marker (aligned to
flex-start), making the number float above the text. Drop the outer margins
so the marker and the first line share the same top edge — same approach
used for callouts in core.css. */
.definitionContent > :first-child {
margin-top: 0;
}
.definitionContent > :last-child {
margin-bottom: 0;
}
.backLink {
flex: 0 0 auto;
cursor: pointer;

View File

@@ -10,9 +10,15 @@ ul[data-type="taskList"] {
display: flex;
> label {
padding-top: 0.2rem;
/* Box exactly one text-line tall and center the checkbox in it, so the
checkbox lines up with the first line of the item's text. This tracks
the editor line-height (--mantine-line-height-xl) instead of a magic
padding-top that drifts from the real line box. */
flex: 0 0 auto;
margin-right: 0.5rem;
height: calc(var(--mantine-line-height-xl, 1.65) * 1em);
display: inline-flex;
align-items: center;
user-select: none;
}

View File

@@ -0,0 +1,237 @@
import {
ActionIcon,
Button,
Group,
Modal,
Text,
TextInput,
} from "@mantine/core";
import { IconExternalLink } from "@tabler/icons-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import CopyTextButton from "@/components/common/copy.tsx";
import { getAppUrl } from "@/lib/config.ts";
import {
useRemoveShareAliasMutation,
useSetShareAliasMutation,
useShareAliasForPageQuery,
} from "@/features/share/queries/share-query.ts";
import { checkShareAliasAvailability } from "@/features/share/services/share-service.ts";
import {
isValidShareAlias,
normalizeShareAlias,
} from "@/features/share/share-alias.util.ts";
interface ShareAliasSectionProps {
pageId: string;
readOnly: boolean;
}
// The prefix label shown next to the slug input, e.g. "docs.example.com/l/".
function aliasPrefixLabel(): string {
const url = getAppUrl();
const host = url.replace(/^https?:\/\//, "").replace(/\/+$/, "");
return `${host}/l/`;
}
export default function ShareAliasSection({
pageId,
readOnly,
}: ShareAliasSectionProps) {
const { t } = useTranslation();
const { data: currentAlias } = useShareAliasForPageQuery(pageId);
const setAliasMutation = useSetShareAliasMutation();
const removeAliasMutation = useRemoveShareAliasMutation();
const [value, setValue] = useState("");
const [availability, setAvailability] = useState<{
valid: boolean;
available: boolean;
currentPageId: string | null;
} | null>(null);
const [reassign, setReassign] = useState<{
alias: string;
currentPageTitle: string | null;
} | null>(null);
// Seed the input from the page's current alias (if any).
useEffect(() => {
setValue(currentAlias?.alias ?? "");
}, [currentAlias?.alias, pageId]);
const normalized = useMemo(() => normalizeShareAlias(value), [value]);
const isValid = isValidShareAlias(normalized);
const unchanged = currentAlias?.alias === normalized;
// Debounced availability probe (skips when invalid or unchanged).
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => {
setAvailability(null);
if (!isValid || unchanged) return;
debounceRef.current && clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(async () => {
try {
const res = await checkShareAliasAvailability(normalized);
setAvailability({
valid: res.valid,
available: res.available,
currentPageId: res.currentPageId,
});
} catch {
setAvailability(null);
}
}, 400);
return () => {
debounceRef.current && clearTimeout(debounceRef.current);
};
}, [normalized, isValid, unchanged]);
const prettyLink = currentAlias?.alias
? `${getAppUrl()}/l/${currentAlias.alias}`
: null;
const handleSave = async (confirmReassign = false) => {
try {
await setAliasMutation.mutateAsync({
pageId,
alias: normalized,
confirmReassign,
});
setReassign(null);
} catch (error: any) {
// The address already points at another page: prompt to move it here.
if (error?.status === 409 || error?.response?.status === 409) {
const data = error?.response?.data;
if (data?.code === "ALIAS_REASSIGN_REQUIRED") {
setReassign({
alias: normalized,
currentPageTitle: data?.currentPageTitle ?? null,
});
}
}
}
};
const handleRemove = async () => {
if (!currentAlias?.id) return;
await removeAliasMutation.mutateAsync(currentAlias.id);
setValue("");
};
const showInvalid = normalized.length > 0 && !isValid;
const showTaken =
isValid && !unchanged && availability && !availability.available;
return (
<>
<Text size="sm" fw={500} mt="md">
{t("Custom address")}
</Text>
<Text size="xs" c="dimmed" mb={4}>
{t("A short, memorable link you can point at any shared page.")}
</Text>
{prettyLink && (
<Group my="xs" gap={4} wrap="nowrap">
<TextInput
variant="filled"
value={prettyLink}
readOnly
rightSection={<CopyTextButton text={prettyLink} />}
style={{ width: "100%" }}
/>
<ActionIcon
component="a"
variant="default"
target="_blank"
href={prettyLink}
size="sm"
>
<IconExternalLink size={16} />
</ActionIcon>
</Group>
)}
<TextInput
value={value}
onChange={(e) => setValue(e.currentTarget.value)}
// Show the canonical form once the user pauses so what they type maps
// visibly to what gets stored.
onBlur={() => setValue(normalized)}
leftSection={
<Text size="xs" c="dimmed" pl={4} style={{ whiteSpace: "nowrap" }}>
{aliasPrefixLabel()}
</Text>
}
leftSectionWidth={Math.min(aliasPrefixLabel().length * 7 + 12, 180)}
placeholder={t("my-page")}
disabled={readOnly}
error={
showInvalid
? t("Use 2-60 lowercase letters, digits and hyphens")
: showTaken
? t("This address is already in use")
: undefined
}
/>
<Group mt="xs" gap="xs">
<Button
size="compact-sm"
onClick={() => handleSave(false)}
loading={setAliasMutation.isPending}
disabled={readOnly || !isValid || unchanged}
>
{t("Save")}
</Button>
{currentAlias?.id && (
<Button
size="compact-sm"
variant="default"
color="red"
onClick={handleRemove}
loading={removeAliasMutation.isPending}
disabled={readOnly}
>
{t("Remove")}
</Button>
)}
</Group>
<Modal
opened={!!reassign}
onClose={() => setReassign(null)}
title={t("Move custom address?")}
centered
size="sm"
>
<Text size="sm">
{reassign?.currentPageTitle
? t(
'The address "{{alias}}" currently points to "{{title}}". Move it to this page?',
{
alias: reassign?.alias,
title: reassign?.currentPageTitle,
},
)
: t(
'The address "{{alias}}" is already in use. Move it to this page?',
{ alias: reassign?.alias },
)}
</Text>
<Group justify="flex-end" mt="md">
<Button variant="default" onClick={() => setReassign(null)}>
{t("Cancel")}
</Button>
<Button
color="red"
onClick={() => handleSave(true)}
loading={setAliasMutation.isPending}
>
{t("Move here")}
</Button>
</Group>
</Modal>
</>
);
}

View File

@@ -25,6 +25,7 @@ import CopyTextButton from "@/components/common/copy.tsx";
import { getAppUrl } from "@/lib/config.ts";
import { buildPageUrl } from "@/features/page/page.utils.ts";
import classes from "@/features/share/components/share.module.css";
import ShareAliasSection from "@/features/share/components/share-alias-section.tsx";
import { useAtom } from "jotai";
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
import { useSpaceQuery } from "@/features/space/queries/space-query.ts";
@@ -253,6 +254,9 @@ export default function ShareModal({ readOnly }: ShareModalProps) {
disabled={readOnly}
/>
</Group>
{pageId && (
<ShareAliasSection pageId={pageId} readOnly={readOnly} />
)}
</>
)}
</>

View File

@@ -10,6 +10,8 @@ import { useTranslation } from "react-i18next";
import {
ICreateShare,
IShare,
IShareAlias,
ISetShareAlias,
ISharedItem,
ISharedPage,
ISharedPageTree,
@@ -20,11 +22,14 @@ import {
import {
createShare,
deleteShare,
getShareAliasForPage,
getSharedPageTree,
getShareForPage,
getShareInfo,
getSharePageInfo,
getShares,
removeShareAlias,
setShareAlias,
updateShare,
} from "@/features/share/services/share-service.ts";
import { IPagination, QueryParams } from "@/lib/types.ts";
@@ -170,6 +175,72 @@ export function useDeleteShareMutation() {
});
}
export function useShareAliasForPageQuery(
pageId: string,
): UseQueryResult<IShareAlias | null, Error> {
return useQuery({
// The endpoint resolves to null when the page has no alias; normalize the
// absence so React Query never sees `undefined`.
queryKey: ["share-alias-for-page", pageId],
queryFn: async () => (await getShareAliasForPage(pageId)) ?? null,
enabled: !!pageId,
staleTime: 60 * 1000,
retry: false,
});
}
export function useSetShareAliasMutation() {
const { t } = useTranslation();
const queryClient = useQueryClient();
return useMutation<IShareAlias, Error, ISetShareAlias>({
mutationFn: (data) => setShareAlias(data),
onSuccess: () => {
queryClient.invalidateQueries({
predicate: (item) =>
["share-alias-for-page", "share-list"].includes(
item.queryKey[0] as string,
),
});
},
onError: (error) => {
// A 409 reassign-required is handled inline by the modal (it shows the
// "move address here?" confirmation), so don't surface a generic toast.
if (error?.["status"] === 409) return;
notifications.show({
message:
error?.["response"]?.data?.message || t("Failed to set custom address"),
color: "red",
});
},
});
}
export function useRemoveShareAliasMutation() {
const { t } = useTranslation();
const queryClient = useQueryClient();
return useMutation<void, Error, string>({
mutationFn: (aliasId) => removeShareAlias(aliasId),
onSuccess: () => {
queryClient.invalidateQueries({
predicate: (item) =>
["share-alias-for-page", "share-list"].includes(
item.queryKey[0] as string,
),
});
},
onError: (error) => {
notifications.show({
message:
error?.["response"]?.data?.message ||
t("Failed to remove custom address"),
color: "red",
});
},
});
}
export function useGetSharedPageTreeQuery(
shareId: string,
): UseQueryResult<ISharedPageTree, Error> {

View File

@@ -4,6 +4,9 @@ import { IPage } from "@/features/page/types/page.types";
import {
ICreateShare,
IShare,
IShareAlias,
IShareAliasAvailability,
ISetShareAlias,
ISharedItem,
ISharedPage,
ISharedPageTree,
@@ -57,3 +60,33 @@ export async function getSharedPageTree(
const req = await api.post<ISharedPageTree>("/shares/tree", { shareId });
return req.data;
}
export async function getShareAliasForPage(
pageId: string,
): Promise<IShareAlias | null> {
const req = await api.post<IShareAlias | null>("/share-aliases/for-page", {
pageId,
});
return req.data;
}
export async function setShareAlias(
data: ISetShareAlias,
): Promise<IShareAlias> {
const req = await api.post<IShareAlias>("/share-aliases/set", data);
return req.data;
}
export async function removeShareAlias(aliasId: string): Promise<void> {
await api.post("/share-aliases/remove", { aliasId });
}
export async function checkShareAliasAvailability(
alias: string,
): Promise<IShareAliasAvailability> {
const req = await api.post<IShareAliasAvailability>(
"/share-aliases/availability",
{ alias },
);
return req.data;
}

View File

@@ -0,0 +1,32 @@
import { describe, it, expect } from "vitest";
import {
isValidShareAlias,
normalizeShareAlias,
} from "@/features/share/share-alias.util.ts";
// Mirrors the server-side util so the modal's live feedback matches what the
// server will accept/store.
describe("normalizeShareAlias", () => {
it("lowercases, trims and maps separators to single hyphens", () => {
expect(normalizeShareAlias(" My Cool_Page ")).toBe("my-cool-page");
});
it("collapses repeated hyphens and trims edges", () => {
expect(normalizeShareAlias("--a---b--")).toBe("a-b");
});
});
describe("isValidShareAlias", () => {
it("accepts ascii hyphen-separated slugs of length 2..60", () => {
expect(isValidShareAlias("hello-world")).toBe(true);
expect(isValidShareAlias("a".repeat(60))).toBe(true);
});
it("rejects too short, edge/double hyphens, uppercase and non-ascii", () => {
expect(isValidShareAlias("a")).toBe(false);
expect(isValidShareAlias("-a")).toBe(false);
expect(isValidShareAlias("a--b")).toBe(false);
expect(isValidShareAlias("Hello")).toBe(false);
expect(isValidShareAlias("привет")).toBe(false);
});
});

View File

@@ -0,0 +1,26 @@
/**
* Client copy of the vanity share-alias helpers. Kept in sync with the server
* (`apps/server/src/core/share/share-alias.util.ts`) so live input feedback
* matches what the server will store/accept. ASCII-only, lowercase, hyphen
* separated, length 2..60.
*/
// Normalize a user-provided vanity alias into canonical ASCII storage form.
export function normalizeShareAlias(raw: string): string {
return (raw ?? "")
.trim()
.toLowerCase()
.replace(/[\s_]+/g, "-")
.replace(/-{2,}/g, "-")
.replace(/^-+|-+$/g, "");
}
const ALIAS_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
export function isValidShareAlias(alias: string): boolean {
return (
typeof alias === "string" &&
alias.length >= 2 &&
alias.length <= 60 &&
ALIAS_RE.test(alias)
);
}

View File

@@ -75,6 +75,30 @@ export interface IShareInfoInput {
pageId: string;
}
// Vanity /l/:alias pointer.
export interface IShareAlias {
id: string;
workspaceId: string;
alias: string;
pageId: string | null;
creatorId: string | null;
createdAt: string;
updatedAt: string;
}
export interface ISetShareAlias {
pageId: string;
alias: string;
confirmReassign?: boolean;
}
export interface IShareAliasAvailability {
alias: string;
valid: boolean;
available: boolean;
currentPageId: string | null;
}
export interface ISharedPageTree {
share: IShare;
pageTree: Partial<IPage[]>;

View File

@@ -1,6 +1,6 @@
{
"name": "server",
"version": "0.94.0",
"version": "0.94.1",
"description": "",
"author": "",
"private": true,

View File

@@ -240,7 +240,7 @@ describe('prepareAgentStep', () => {
* write path. It runs identically for the upfront insert (empty steps,
* 'streaming'), every per-step update, and the terminal finalize — so a future
* background worker can call the same function. These tests pin the four status
* shapes and the `metadata.parts` shape that rowToUiMessage/findRecent depend on
* shapes and the `metadata.parts` shape that rowToUiMessage/findAllByChat depend on
* (per-step text + tool parts via assistantParts, in-progress text appended).
*/
describe('flushAssistant', () => {

View File

@@ -322,12 +322,14 @@ export class AiChatService implements OnModuleInit {
// Rebuild the conversation from persisted history (not the client payload),
// so the model always sees the authoritative server-side transcript. Load
// the most RECENT tail (oldest -> newest) so chats longer than one page do
// not drop recent turns (incl. the user message just inserted above).
const history = await this.aiChatMessageRepo.findRecent(
// the FULL history in chronological order (oldest -> newest, incl. the user
// message just inserted above) so NO turns are dropped — there is no
// recent-tail window anymore. `findAllByChat` keeps a 5000-row memory-safety
// backstop (on overflow it keeps the NEWEST rows and logs a warning); that
// is a safety net far above any realistic chat, not a conversational limit.
const history = await this.aiChatMessageRepo.findAllByChat(
chatId,
workspace.id,
50,
);
const uiMessages = history.map(rowToUiMessage);
// convertToModelMessages is async in ai@6.0.134 (returns Promise<ModelMessage[]>).
@@ -1215,7 +1217,7 @@ export async function applyFinalize(
*
* `metadata.parts` is built by assistantParts over the finished steps, then the
* in-progress text appended as a trailing text part, so rowToUiMessage /
* findRecent keep replaying the turn unchanged. `metadata.finishReason`,
* findAllByChat keep replaying the turn unchanged. `metadata.finishReason`,
* `metadata.error`, `metadata.usage`, `metadata.contextTokens` and
* `metadata.maxContextTokens` are attached only when provided/relevant, matching
* the pre-#183 onFinish/onError records.

View File

@@ -0,0 +1,44 @@
import {
IsBoolean,
IsNotEmpty,
IsOptional,
IsString,
} from 'class-validator';
/**
* Create/retarget a vanity alias for a page. `confirmReassign` is the
* two-step guard for the "address already points at another page" case: the
* first call without it gets a 409 carrying the current target, the client
* confirms, and retries with `confirmReassign: true`.
*/
export class SetShareAliasDto {
@IsString()
@IsNotEmpty()
pageId: string;
@IsString()
@IsNotEmpty()
alias: string;
@IsBoolean()
@IsOptional()
confirmReassign?: boolean;
}
export class RemoveShareAliasDto {
@IsString()
@IsNotEmpty()
aliasId: string;
}
export class ShareAliasAvailabilityDto {
@IsString()
@IsNotEmpty()
alias: string;
}
export class ShareAliasForPageDto {
@IsString()
@IsNotEmpty()
pageId: string;
}

View File

@@ -0,0 +1,252 @@
import * as fs from 'node:fs';
// `@sindresorhus/slugify` is ESM-only and not in jest's transformIgnorePatterns,
// so the real module fails to parse under ts-jest. Stub it with a minimal,
// deterministic slugifier — this spec asserts the controller's slug *assembly*
// (`<title-slug>-<slugId>`, 70-char clamp, `untitled` fallback), not the upstream
// slug algorithm. The factory keeps the real ESM module from ever being loaded.
jest.mock('@sindresorhus/slugify', () => ({
__esModule: true,
default: (input: string) =>
String(input)
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, ''),
}));
import { ShareAliasRedirectController } from './share-alias-redirect.controller';
/**
* Routing/leak guard for the PUBLIC `GET /l/:alias` resolver.
*
* This is the most security-sensitive surface of the alias feature: an
* unauthenticated route that MUST serve the plain SPA index (exactly like any
* unknown path) for an unknown / dangling / no-longer-readable alias so that the
* existence of a name never leaks. Only a resolvable, still-readable alias may
* 302 to the canonical `/share/<key>/p/<title-slug>-<slugId>` page (302 — never
* 301 — because the target is retargetable). These tests pin that routing and
* the defensive percent-decoding, mirroring `share-seo.controller.routing.spec`.
*/
const STREAM_SENTINEL = { __isStream: true } as unknown as fs.ReadStream;
// Stub fs at CALL time (jest.spyOn), NOT module load (jest.mock): the controller
// transitively pulls bcrypt, whose native module is located by node-gyp-build
// reading the filesystem at import time — a module-level fs mock breaks that.
beforeEach(() => {
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
jest.spyOn(fs, 'createReadStream').mockReturnValue(STREAM_SENTINEL);
});
afterEach(() => jest.restoreAllMocks());
function makeRes() {
const res: any = {
sent: undefined as unknown,
statusCode: undefined as number | undefined,
redirectUrl: undefined as string | undefined,
type: jest.fn(() => res),
status: jest.fn((code: number) => {
res.statusCode = code;
return res;
}),
send: jest.fn((v: unknown) => {
res.sent = v;
return res;
}),
redirect: jest.fn((url: string, code: number) => {
res.redirectUrl = url;
res.statusCode = code;
return res;
}),
};
return res;
}
function makeController(opts: {
resolved?: { share: any; page: any } | null;
selfHosted?: boolean;
}) {
const shareAliasService = {
resolveReadableTarget: jest.fn(async () => opts.resolved ?? null),
};
const workspaceRepo = {
findFirst: jest.fn(async () => ({ id: 'ws-self' })),
findByHostname: jest.fn(async (sub: string) =>
sub === 'acme' ? { id: 'ws-acme' } : null,
),
};
const environmentService = {
isSelfHosted: jest.fn(() => opts.selfHosted ?? true),
};
const controller = new ShareAliasRedirectController(
shareAliasService as any,
workspaceRepo as any,
environmentService as any,
);
return { controller, shareAliasService, workspaceRepo, environmentService };
}
const selfReq: any = { raw: { headers: { host: 'self' } } };
describe('ShareAliasRedirectController.resolve', () => {
it('302-redirects a resolvable alias to the canonical share page', async () => {
const { controller, shareAliasService } = makeController({
resolved: {
share: { key: 'SHAREKEY' },
page: { slugId: 'abc123', title: 'Quarterly Report' },
},
});
const res = makeRes();
await controller.resolve('promo', selfReq, res);
expect(shareAliasService.resolveReadableTarget).toHaveBeenCalledWith(
'promo',
'ws-self',
);
expect(res.redirect).toHaveBeenCalledWith(
'/share/SHAREKEY/p/quarterly-report-abc123',
302,
);
// No index stream was served on a hit.
expect(res.sent).toBeUndefined();
});
it('falls back to "untitled" in the slug when the target has no title', async () => {
const { controller } = makeController({
resolved: { share: { key: 'K' }, page: { slugId: 'sid', title: '' } },
});
const res = makeRes();
await controller.resolve('promo', selfReq, res);
expect(res.redirect).toHaveBeenCalledWith('/share/K/p/untitled-sid', 302);
});
it('clamps the title-slug to the first 70 characters of the page title', async () => {
// 119-char title; only the first 70 chars must reach the slug. The 70-char
// boundary deliberately falls mid-word ("Entire" -> "entir") so the clamp is
// unambiguous: anything past char 70 ("...e Fiscal Year...") must be dropped.
const longTitle =
'The Comprehensive Quarterly Financial Performance Report For The Entire Fiscal Year Two Thousand Twenty Five And Beyond';
const { controller } = makeController({
resolved: {
share: { key: 'K' },
page: { slugId: 'sid', title: longTitle },
},
});
const res = makeRes();
await controller.resolve('promo', selfReq, res);
expect(res.redirect).toHaveBeenCalledWith(
'/share/K/p/the-comprehensive-quarterly-financial-performance-report-for-the-entir-sid',
302,
);
});
it('streams the SPA index WITHOUT a 302 for an unknown/dangling/unreadable alias (no leak)', async () => {
const { controller, shareAliasService } = makeController({ resolved: null });
const res = makeRes();
await controller.resolve('does-not-exist', selfReq, res);
expect(shareAliasService.resolveReadableTarget).toHaveBeenCalled();
// The plain index stream was served and no redirect leaked alias existence.
expect(res.redirect).not.toHaveBeenCalled();
expect(res.sent).toBe(STREAM_SENTINEL);
expect(res.type).toHaveBeenCalledWith('text/html');
});
it('streams the SPA index without even resolving when the workspace is null', async () => {
// Subdomain host that maps to no workspace => workspace === null.
const { controller, shareAliasService, workspaceRepo } = makeController({
selfHosted: false,
});
const res = makeRes();
const req: any = { raw: { headers: { host: 'unknown.example.com' } } };
await controller.resolve('promo', req, res);
expect(workspaceRepo.findByHostname).toHaveBeenCalledWith('unknown');
// Never even attempts to resolve (alias existence cannot leak per-host).
expect(shareAliasService.resolveReadableTarget).not.toHaveBeenCalled();
expect(res.redirect).not.toHaveBeenCalled();
expect(res.sent).toBe(STREAM_SENTINEL);
});
it('defensively decodes broken percent-encoding and treats it as unknown', async () => {
const { controller, shareAliasService } = makeController({ resolved: null });
const res = makeRes();
// '%E0%A4%A' is invalid -> decodeURIComponent throws -> raw value is used,
// and the alias resolves to nothing (no crash, served as index).
await controller.resolve('%E0%A4%A', selfReq, res);
expect(shareAliasService.resolveReadableTarget).toHaveBeenCalledWith(
'%E0%A4%A',
'ws-self',
);
expect(res.redirect).not.toHaveBeenCalled();
expect(res.sent).toBe(STREAM_SENTINEL);
});
it('decodes a valid percent-encoded alias before resolving', async () => {
const { controller, shareAliasService } = makeController({ resolved: null });
const res = makeRes();
await controller.resolve('my%2Dlink', selfReq, res);
expect(shareAliasService.resolveReadableTarget).toHaveBeenCalledWith(
'my-link',
'ws-self',
);
});
it('resolves the workspace via findFirst on the self-hosted path', async () => {
const { controller, workspaceRepo, shareAliasService } = makeController({
selfHosted: true,
resolved: null,
});
const res = makeRes();
await controller.resolve('promo', selfReq, res);
expect(workspaceRepo.findFirst).toHaveBeenCalled();
expect(workspaceRepo.findByHostname).not.toHaveBeenCalled();
expect(shareAliasService.resolveReadableTarget).toHaveBeenCalledWith(
'promo',
'ws-self',
);
});
it('resolves the workspace via findByHostname (subdomain) on the cloud path', async () => {
const { controller, workspaceRepo, shareAliasService } = makeController({
selfHosted: false,
resolved: null,
});
const res = makeRes();
const req: any = { raw: { headers: { host: 'acme.example.com' } } };
await controller.resolve('promo', req, res);
expect(workspaceRepo.findByHostname).toHaveBeenCalledWith('acme');
expect(workspaceRepo.findFirst).not.toHaveBeenCalled();
expect(shareAliasService.resolveReadableTarget).toHaveBeenCalledWith(
'promo',
'ws-acme',
);
});
it('serves a 404 when no built client index exists', async () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
const { controller } = makeController({ resolved: null });
const res = makeRes();
await controller.resolve('promo', selfReq, res);
expect(res.status).toHaveBeenCalledWith(404);
expect(res.redirect).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,95 @@
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';
import { join } from 'path';
import * as fs from 'node:fs';
import slugify from '@sindresorhus/slugify';
import { WorkspaceRepo } from '@docmost/db/repos/workspace/workspace.repo';
import { EnvironmentService } from '../../integrations/environment/environment.service';
import { Workspace } from '@docmost/db/types/entity.types';
import { ShareAliasService } from './share-alias.service';
/**
* Public resolver for vanity links `GET /l/:alias`. Excluded from the global
* `/api` prefix (see main.ts) and parallel to ShareSeoController.
*
* On a hit it issues a 302 (NEVER 301) to the canonical
* `/share/:key/p/:slug` page, so:
* - the existing share render + SSR meta is reused verbatim (crawlers follow
* the 302 and get the correct preview);
* - because the alias target is mutable, a temporary redirect is always
* re-resolved — a cached 301 would pin clients to the pre-swap page.
*
* Any unknown / dangling / no-longer-readable alias serves the plain SPA index
* (same as any unknown path) so the existence of a name never leaks.
*/
@Controller('l')
export class ShareAliasRedirectController {
constructor(
private readonly shareAliasService: ShareAliasService,
private readonly workspaceRepo: WorkspaceRepo,
private readonly environmentService: EnvironmentService,
) {}
@Get(':alias')
async resolve(
@Param('alias') rawAlias: string,
@Req() req: FastifyRequest,
@Res({ passthrough: false }) res: FastifyReply,
) {
// NestJS does not apply middlewares to paths excluded from the global /api
// prefix, so the DomainMiddleware workspace resolution is duplicated here
// (same workaround as ShareSeoController).
let workspace: Workspace = null;
if (this.environmentService.isSelfHosted()) {
workspace = await this.workspaceRepo.findFirst();
} else {
const header = req.raw.headers.host;
const subdomain = header?.split('.')[0];
workspace = subdomain
? await this.workspaceRepo.findByHostname(subdomain)
: null;
}
const clientDistPath = join(__dirname, '..', '..', '..', '..', 'client/dist');
const indexFilePath = join(clientDistPath, 'index.html');
let decoded = rawAlias;
try {
decoded = decodeURIComponent(rawAlias);
} catch {
// Malformed percent-encoding -> treat as unknown alias.
}
const resolved = workspace
? await this.shareAliasService.resolveReadableTarget(
decoded,
workspace.id,
)
: null;
if (!resolved) {
return this.sendIndex(indexFilePath, res);
}
const slug = buildPageSlug(resolved.page.slugId, resolved.page.title);
// 302, NOT 301: the alias is retargetable, so the redirect must always be
// re-resolved by clients/crawlers.
return res.redirect(`/share/${resolved.share.key}/p/${slug}`, 302);
}
private sendIndex(indexFilePath: string, res: FastifyReply) {
if (!fs.existsSync(indexFilePath)) {
// No built client (e.g. API-only dev): nothing to serve.
res.status(404).send('Not found');
return;
}
const stream = fs.createReadStream(indexFilePath);
res.type('text/html').send(stream);
}
}
/** Canonical share page slug: `<title-slug>-<slugId>` (mirrors the client). */
function buildPageSlug(slugId: string, title?: string): string {
const titleSlug = slugify(title?.substring(0, 70) || 'untitled');
return `${titleSlug}-${slugId}`;
}

View File

@@ -0,0 +1,260 @@
import {
BadRequestException,
ForbiddenException,
NotFoundException,
} from '@nestjs/common';
import { ShareAliasController } from './share-alias.controller';
/**
* Authz-gate tests for the authenticated alias management controller. The access
* decisions for creating/retargeting/removing an alias live in THIS controller
* (the service spec delegates authorization to the caller), so each gate is
* pinned here against mocked PageRepo / ShareService / ShareAliasService /
* PageAccessService. A regression that drops any gate must fail here.
*/
describe('ShareAliasController authz gates', () => {
function makeController() {
const shareAliasService = {
setAlias: jest.fn(async () => ({ id: 'alias-1' })),
removeAlias: jest.fn(async () => undefined),
getAliasById: jest.fn(),
getAliasForPage: jest.fn(),
checkAvailability: jest.fn(),
};
const shareService = {
resolveReadableSharePage: jest.fn(),
isSharingAllowed: jest.fn(),
};
const pageRepo = { findById: jest.fn() };
const pageAccessService = {
validateCanEdit: jest.fn(async () => undefined),
validateCanView: jest.fn(async () => undefined),
};
const controller = new ShareAliasController(
shareAliasService as any,
shareService as any,
pageRepo as any,
pageAccessService as any,
);
return {
controller,
shareAliasService,
shareService,
pageRepo,
pageAccessService,
};
}
const user: any = { id: 'u-1' };
const workspace: any = { id: 'ws-1' };
describe('set', () => {
it('throws NotFoundException for a nonexistent page', async () => {
const { controller, pageRepo, pageAccessService } = makeController();
pageRepo.findById.mockResolvedValue(null);
await expect(
controller.set({ pageId: 'p-x', alias: 'promo' } as any, user, workspace),
).rejects.toBeInstanceOf(NotFoundException);
expect(pageAccessService.validateCanEdit).not.toHaveBeenCalled();
});
it('throws NotFoundException for a page in another workspace', async () => {
const { controller, pageRepo } = makeController();
pageRepo.findById.mockResolvedValue({
id: 'p-1',
workspaceId: 'ws-OTHER',
});
await expect(
controller.set({ pageId: 'p-1', alias: 'promo' } as any, user, workspace),
).rejects.toBeInstanceOf(NotFoundException);
});
it('enforces validateCanEdit before setting the alias', async () => {
const { controller, pageRepo, pageAccessService, shareService } =
makeController();
pageRepo.findById.mockResolvedValue({ id: 'p-1', workspaceId: 'ws-1' });
pageAccessService.validateCanEdit.mockRejectedValue(
new ForbiddenException('no edit'),
);
await expect(
controller.set({ pageId: 'p-1', alias: 'promo' } as any, user, workspace),
).rejects.toBeInstanceOf(ForbiddenException);
// Gate short-circuits before any share resolution.
expect(shareService.resolveReadableSharePage).not.toHaveBeenCalled();
});
it('throws BadRequestException when the page is not publicly shared', async () => {
const { controller, pageRepo, shareService } = makeController();
pageRepo.findById.mockResolvedValue({ id: 'p-1', workspaceId: 'ws-1' });
shareService.resolveReadableSharePage.mockResolvedValue(null);
await expect(
controller.set({ pageId: 'p-1', alias: 'promo' } as any, user, workspace),
).rejects.toThrow('Page is not publicly shared');
await expect(
controller.set({ pageId: 'p-1', alias: 'promo' } as any, user, workspace),
).rejects.toBeInstanceOf(BadRequestException);
});
it('throws ForbiddenException when public sharing is disabled', async () => {
const { controller, pageRepo, shareService } = makeController();
pageRepo.findById.mockResolvedValue({ id: 'p-1', workspaceId: 'ws-1' });
shareService.resolveReadableSharePage.mockResolvedValue({
share: { spaceId: 'sp-1' },
});
shareService.isSharingAllowed.mockResolvedValue(false);
await expect(
controller.set({ pageId: 'p-1', alias: 'promo' } as any, user, workspace),
).rejects.toBeInstanceOf(ForbiddenException);
});
it('delegates to setAlias on the happy path with all gates passed', async () => {
const { controller, pageRepo, shareService, shareAliasService } =
makeController();
pageRepo.findById.mockResolvedValue({ id: 'p-1', workspaceId: 'ws-1' });
shareService.resolveReadableSharePage.mockResolvedValue({
share: { spaceId: 'sp-1' },
});
shareService.isSharingAllowed.mockResolvedValue(true);
const result = await controller.set(
{ pageId: 'p-1', alias: 'promo', confirmReassign: true } as any,
user,
workspace,
);
expect(shareAliasService.setAlias).toHaveBeenCalledWith({
workspaceId: 'ws-1',
pageId: 'p-1',
creatorId: 'u-1',
alias: 'promo',
confirmReassign: true,
});
expect(result).toEqual({ id: 'alias-1' });
});
});
describe('remove', () => {
it('throws NotFoundException for an unknown alias', async () => {
const { controller, shareAliasService } = makeController();
shareAliasService.getAliasById.mockResolvedValue(null);
await expect(
controller.remove({ aliasId: 'a-x' } as any, user, workspace),
).rejects.toBeInstanceOf(NotFoundException);
expect(shareAliasService.removeAlias).not.toHaveBeenCalled();
});
it('requires validateCanEdit on the current target before removing', async () => {
const { controller, shareAliasService, pageRepo, pageAccessService } =
makeController();
shareAliasService.getAliasById.mockResolvedValue({
id: 'a-1',
pageId: 'p-1',
});
pageRepo.findById.mockResolvedValue({ id: 'p-1', workspaceId: 'ws-1' });
pageAccessService.validateCanEdit.mockRejectedValue(
new ForbiddenException('no edit'),
);
await expect(
controller.remove({ aliasId: 'a-1' } as any, user, workspace),
).rejects.toBeInstanceOf(ForbiddenException);
expect(shareAliasService.removeAlias).not.toHaveBeenCalled();
});
it('removes a dangling alias (pageId null) WITHOUT an edit check', async () => {
const { controller, shareAliasService, pageRepo, pageAccessService } =
makeController();
shareAliasService.getAliasById.mockResolvedValue({
id: 'a-1',
pageId: null,
});
await controller.remove({ aliasId: 'a-1' } as any, user, workspace);
expect(pageRepo.findById).not.toHaveBeenCalled();
expect(pageAccessService.validateCanEdit).not.toHaveBeenCalled();
expect(shareAliasService.removeAlias).toHaveBeenCalledWith('a-1', 'ws-1');
});
it('removes when the editor can edit the current target', async () => {
const { controller, shareAliasService, pageRepo, pageAccessService } =
makeController();
shareAliasService.getAliasById.mockResolvedValue({
id: 'a-1',
pageId: 'p-1',
});
pageRepo.findById.mockResolvedValue({ id: 'p-1', workspaceId: 'ws-1' });
await controller.remove({ aliasId: 'a-1' } as any, user, workspace);
expect(pageAccessService.validateCanEdit).toHaveBeenCalled();
expect(shareAliasService.removeAlias).toHaveBeenCalledWith('a-1', 'ws-1');
});
it('removes even if the recorded target page no longer exists', async () => {
const { controller, shareAliasService, pageRepo, pageAccessService } =
makeController();
shareAliasService.getAliasById.mockResolvedValue({
id: 'a-1',
pageId: 'p-gone',
});
pageRepo.findById.mockResolvedValue(null);
await controller.remove({ aliasId: 'a-1' } as any, user, workspace);
expect(pageAccessService.validateCanEdit).not.toHaveBeenCalled();
expect(shareAliasService.removeAlias).toHaveBeenCalledWith('a-1', 'ws-1');
});
});
describe('forPage', () => {
it('throws NotFoundException for a cross-workspace/nonexistent page', async () => {
const { controller, pageRepo, pageAccessService } = makeController();
pageRepo.findById.mockResolvedValue({
id: 'p-1',
workspaceId: 'ws-OTHER',
});
await expect(
controller.forPage({ pageId: 'p-1' } as any, user, workspace),
).rejects.toBeInstanceOf(NotFoundException);
expect(pageAccessService.validateCanView).not.toHaveBeenCalled();
});
it('requires validateCanView and returns the alias (or null)', async () => {
const { controller, pageRepo, pageAccessService, shareAliasService } =
makeController();
pageRepo.findById.mockResolvedValue({ id: 'p-1', workspaceId: 'ws-1' });
shareAliasService.getAliasForPage.mockResolvedValue({ id: 'a-1' });
const result = await controller.forPage(
{ pageId: 'p-1' } as any,
user,
workspace,
);
expect(pageAccessService.validateCanView).toHaveBeenCalled();
expect(result).toEqual({ id: 'a-1' });
});
it('returns null when the page has no alias', async () => {
const { controller, pageRepo, shareAliasService } = makeController();
pageRepo.findById.mockResolvedValue({ id: 'p-1', workspaceId: 'ws-1' });
shareAliasService.getAliasForPage.mockResolvedValue(undefined);
const result = await controller.forPage(
{ pageId: 'p-1' } as any,
user,
workspace,
);
expect(result).toBeNull();
});
});
});

View File

@@ -0,0 +1,139 @@
import {
BadRequestException,
Body,
Controller,
ForbiddenException,
HttpCode,
HttpStatus,
NotFoundException,
Post,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { AuthUser } from '../../common/decorators/auth-user.decorator';
import { AuthWorkspace } from '../../common/decorators/auth-workspace.decorator';
import { User, Workspace } from '@docmost/db/types/entity.types';
import { PageRepo } from '@docmost/db/repos/page/page.repo';
import { PageAccessService } from '../page/page-access/page-access.service';
import { ShareService } from './share.service';
import { ShareAliasService } from './share-alias.service';
import {
RemoveShareAliasDto,
SetShareAliasDto,
ShareAliasAvailabilityDto,
ShareAliasForPageDto,
} from './dto/share-alias.dto';
/**
* Authenticated management of vanity `/l/:alias` links. The PUBLIC resolve path
* lives in `ShareAliasRedirectController` (`/l/:alias`); this controller only
* creates/retargets/removes/looks-up aliases for editors.
*/
@UseGuards(JwtAuthGuard)
@Controller('share-aliases')
export class ShareAliasController {
constructor(
private readonly shareAliasService: ShareAliasService,
private readonly shareService: ShareService,
private readonly pageRepo: PageRepo,
private readonly pageAccessService: PageAccessService,
) {}
@HttpCode(HttpStatus.OK)
@Post('set')
async set(
@Body() dto: SetShareAliasDto,
@AuthUser() user: User,
@AuthWorkspace() workspace: Workspace,
) {
const page = await this.pageRepo.findById(dto.pageId);
if (!page || page.workspaceId !== workspace.id) {
throw new NotFoundException('Page not found');
}
// Editing the page is required to point an address at it.
await this.pageAccessService.validateCanEdit(page, user);
// The page must currently be publicly readable through the share graph; an
// alias to a non-shared page would only ever 404.
const resolved = await this.shareService.resolveReadableSharePage(
undefined,
page.id,
workspace.id,
);
if (!resolved) {
throw new BadRequestException('Page is not publicly shared');
}
const sharingAllowed = await this.shareService.isSharingAllowed(
workspace.id,
resolved.share.spaceId,
);
if (!sharingAllowed) {
throw new ForbiddenException('Public sharing is disabled');
}
return this.shareAliasService.setAlias({
workspaceId: workspace.id,
pageId: page.id,
creatorId: user.id,
alias: dto.alias,
confirmReassign: dto.confirmReassign,
});
}
@HttpCode(HttpStatus.OK)
@Post('remove')
async remove(
@Body() dto: RemoveShareAliasDto,
@AuthUser() user: User,
@AuthWorkspace() workspace: Workspace,
) {
const alias = await this.shareAliasService.getAliasById(
dto.aliasId,
workspace.id,
);
if (!alias) {
throw new NotFoundException('Alias not found');
}
// Only someone who can edit the (current) target page may free the address.
// A dangling alias (page deleted) can be removed by any workspace member.
if (alias.pageId) {
const page = await this.pageRepo.findById(alias.pageId);
if (page) {
await this.pageAccessService.validateCanEdit(page, user);
}
}
await this.shareAliasService.removeAlias(alias.id, workspace.id);
}
@HttpCode(HttpStatus.OK)
@Post('availability')
async availability(
@Body() dto: ShareAliasAvailabilityDto,
@AuthWorkspace() workspace: Workspace,
) {
return this.shareAliasService.checkAvailability(dto.alias, workspace.id);
}
@HttpCode(HttpStatus.OK)
@Post('for-page')
async forPage(
@Body() dto: ShareAliasForPageDto,
@AuthUser() user: User,
@AuthWorkspace() workspace: Workspace,
) {
const page = await this.pageRepo.findById(dto.pageId);
if (!page || page.workspaceId !== workspace.id) {
throw new NotFoundException('Page not found');
}
await this.pageAccessService.validateCanView(page, user);
return (
(await this.shareAliasService.getAliasForPage(page.id, workspace.id)) ??
null
);
}
}

View File

@@ -0,0 +1,252 @@
import { BadRequestException, ConflictException } from '@nestjs/common';
import { ShareAliasService } from './share-alias.service';
/**
* Behaviour tests for the alias write/resolve semantics: create vs no-op vs the
* 409 reassign guard, uniqueness-race handling, availability probe, and the
* request-time readable-target resolution (which re-runs the share boundary).
*/
describe('ShareAliasService', () => {
function makeService() {
const shareAliasRepo = {
findByAliasAndWorkspace: jest.fn(),
findByPageId: jest.fn(),
findById: jest.fn(),
insert: jest.fn(),
updatePageId: jest.fn(),
delete: jest.fn(),
};
const pageRepo = { findById: jest.fn() };
const shareService = {
resolveReadableSharePage: jest.fn(),
isSharingAllowed: jest.fn(),
};
const service = new ShareAliasService(
shareAliasRepo as any,
pageRepo as any,
shareService as any,
);
return { service, shareAliasRepo, pageRepo, shareService };
}
describe('setAlias', () => {
it('rejects an invalid alias before touching the db', async () => {
const { service, shareAliasRepo } = makeService();
await expect(
service.setAlias({
workspaceId: 'ws-1',
pageId: 'p-1',
creatorId: 'u-1',
alias: 'A', // too short + uppercase
}),
).rejects.toBeInstanceOf(BadRequestException);
expect(shareAliasRepo.findByAliasAndWorkspace).not.toHaveBeenCalled();
});
it('normalizes then inserts a brand-new alias', async () => {
const { service, shareAliasRepo } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue(undefined);
shareAliasRepo.insert.mockResolvedValue({ id: 'a-1', alias: 'my-page' });
const res = await service.setAlias({
workspaceId: 'ws-1',
pageId: 'p-1',
creatorId: 'u-1',
alias: ' My Page ',
});
expect(shareAliasRepo.findByAliasAndWorkspace).toHaveBeenCalledWith(
'my-page',
'ws-1',
);
expect(shareAliasRepo.insert).toHaveBeenCalledWith({
workspaceId: 'ws-1',
alias: 'my-page',
pageId: 'p-1',
creatorId: 'u-1',
});
expect(res).toMatchObject({ id: 'a-1' });
});
it('is a no-op when the alias already points at the same page', async () => {
const { service, shareAliasRepo } = makeService();
const existing = { id: 'a-1', alias: 'foo', pageId: 'p-1' };
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue(existing);
const res = await service.setAlias({
workspaceId: 'ws-1',
pageId: 'p-1',
creatorId: 'u-1',
alias: 'foo',
});
expect(res).toBe(existing);
expect(shareAliasRepo.insert).not.toHaveBeenCalled();
expect(shareAliasRepo.updatePageId).not.toHaveBeenCalled();
});
it('throws 409 with current target when name is taken and not confirmed', async () => {
const { service, shareAliasRepo, pageRepo } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue({
id: 'a-1',
alias: 'foo',
pageId: 'p-other',
});
pageRepo.findById.mockResolvedValue({ id: 'p-other', title: 'Other' });
try {
await service.setAlias({
workspaceId: 'ws-1',
pageId: 'p-1',
creatorId: 'u-1',
alias: 'foo',
});
fail('expected ConflictException');
} catch (err) {
expect(err).toBeInstanceOf(ConflictException);
expect((err as ConflictException).getResponse()).toMatchObject({
code: 'ALIAS_REASSIGN_REQUIRED',
currentPageId: 'p-other',
currentPageTitle: 'Other',
});
}
expect(shareAliasRepo.updatePageId).not.toHaveBeenCalled();
});
it('retargets (UPDATE page_id) when confirmReassign is set', async () => {
const { service, shareAliasRepo } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue({
id: 'a-1',
alias: 'foo',
pageId: 'p-other',
});
shareAliasRepo.updatePageId.mockResolvedValue({ id: 'a-1', pageId: 'p-1' });
const res = await service.setAlias({
workspaceId: 'ws-1',
pageId: 'p-1',
creatorId: 'u-1',
alias: 'foo',
confirmReassign: true,
});
expect(shareAliasRepo.updatePageId).toHaveBeenCalledWith(
'a-1',
'p-1',
'ws-1',
);
expect(res).toMatchObject({ pageId: 'p-1' });
});
it('maps a unique-violation race to 409', async () => {
const { service, shareAliasRepo } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue(undefined);
shareAliasRepo.insert.mockRejectedValue({ code: '23505' });
await expect(
service.setAlias({
workspaceId: 'ws-1',
pageId: 'p-1',
creatorId: 'u-1',
alias: 'foo',
}),
).rejects.toBeInstanceOf(ConflictException);
});
});
describe('checkAvailability', () => {
it('reports invalid for a bad slug without a db hit', async () => {
const { service, shareAliasRepo } = makeService();
const res = await service.checkAvailability('Bad Slug!', 'ws-1');
expect(res).toMatchObject({ valid: false, available: false });
expect(shareAliasRepo.findByAliasAndWorkspace).not.toHaveBeenCalled();
});
it('reports available when no row exists', async () => {
const { service, shareAliasRepo } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue(undefined);
const res = await service.checkAvailability('free-name', 'ws-1');
expect(res).toMatchObject({
alias: 'free-name',
valid: true,
available: true,
currentPageId: null,
});
});
it('reports taken with the current target page', async () => {
const { service, shareAliasRepo } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue({
id: 'a-1',
pageId: 'p-9',
});
const res = await service.checkAvailability('taken', 'ws-1');
expect(res).toMatchObject({ available: false, currentPageId: 'p-9' });
});
});
describe('resolveReadableTarget', () => {
it('returns null for an invalid alias', async () => {
const { service } = makeService();
expect(await service.resolveReadableTarget('!!', 'ws-1')).toBeNull();
});
it('returns null for an unknown or dangling alias', async () => {
const { service, shareAliasRepo } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValueOnce(undefined);
expect(await service.resolveReadableTarget('foo', 'ws-1')).toBeNull();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValueOnce({
id: 'a-1',
pageId: null,
});
expect(await service.resolveReadableTarget('foo', 'ws-1')).toBeNull();
});
it('returns null when the page is no longer publicly readable', async () => {
const { service, shareAliasRepo, shareService } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue({
id: 'a-1',
pageId: 'p-1',
});
shareService.resolveReadableSharePage.mockResolvedValue(null);
expect(await service.resolveReadableTarget('foo', 'ws-1')).toBeNull();
});
it('returns null when sharing is disabled for the space', async () => {
const { service, shareAliasRepo, shareService } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue({
id: 'a-1',
pageId: 'p-1',
});
shareService.resolveReadableSharePage.mockResolvedValue({
share: { key: 'k', spaceId: 's-1' },
page: { slugId: 'sid', title: 'T' },
});
shareService.isSharingAllowed.mockResolvedValue(false);
expect(await service.resolveReadableTarget('foo', 'ws-1')).toBeNull();
});
it('returns the resolved share+page on success', async () => {
const { service, shareAliasRepo, shareService } = makeService();
shareAliasRepo.findByAliasAndWorkspace.mockResolvedValue({
id: 'a-1',
pageId: 'p-1',
});
const resolved = {
share: { key: 'k', spaceId: 's-1' },
page: { slugId: 'sid', title: 'T' },
};
shareService.resolveReadableSharePage.mockResolvedValue(resolved);
shareService.isSharingAllowed.mockResolvedValue(true);
const res = await service.resolveReadableTarget('FOO', 'ws-1');
expect(res).toBe(resolved);
// alias was normalized to lowercase before lookup
expect(shareAliasRepo.findByAliasAndWorkspace).toHaveBeenCalledWith(
'foo',
'ws-1',
);
});
});
});

View File

@@ -0,0 +1,187 @@
import {
BadRequestException,
ConflictException,
Injectable,
Logger,
} from '@nestjs/common';
import { ShareAliasRepo } from '@docmost/db/repos/share-alias/share-alias.repo';
import { PageRepo } from '@docmost/db/repos/page/page.repo';
import { ShareService } from './share.service';
import { Page, ShareAlias } from '@docmost/db/types/entity.types';
import { isValidShareAlias, normalizeShareAlias } from './share-alias.util';
/** Postgres unique_violation; the (workspace_id, alias) constraint races here. */
const PG_UNIQUE_VIOLATION = '23505';
export interface ResolvedAliasTarget {
share: NonNullable<
Awaited<ReturnType<ShareService['resolveReadableSharePage']>>
>['share'];
page: Page;
}
@Injectable()
export class ShareAliasService {
private readonly logger = new Logger(ShareAliasService.name);
constructor(
private readonly shareAliasRepo: ShareAliasRepo,
private readonly pageRepo: PageRepo,
private readonly shareService: ShareService,
) {}
/**
* Create or retarget a vanity alias. The alias is workspace-scoped:
* - no row for this name -> INSERT a new pointer
* - row already points at pageId -> no-op (idempotent)
* - row points elsewhere -> the "swap". Without confirmReassign we
* throw 409 carrying the current target so the client can confirm; with
* it we UPDATE the single row's page_id (every /l/<alias> link follows the
* 302 to the new page instantly — no stale 301 cache).
*
* Caller is responsible for authorizing the page (edit rights + public
* readability); this method owns only the alias-name semantics.
*/
async setAlias(opts: {
workspaceId: string;
pageId: string;
creatorId: string;
alias: string;
confirmReassign?: boolean;
}): Promise<ShareAlias> {
const { workspaceId, pageId, creatorId, confirmReassign } = opts;
const alias = normalizeShareAlias(opts.alias);
if (!isValidShareAlias(alias)) {
throw new BadRequestException(
'Invalid alias. Use 2-60 lowercase letters, digits and hyphens.',
);
}
const existing = await this.shareAliasRepo.findByAliasAndWorkspace(
alias,
workspaceId,
);
if (!existing) {
try {
return await this.shareAliasRepo.insert({
workspaceId,
alias,
pageId,
creatorId,
});
} catch (err: any) {
// Lost a uniqueness race: another request claimed the name first.
if (err?.code === PG_UNIQUE_VIOLATION) {
throw new ConflictException({ message: 'Alias already taken' });
}
this.logger.error(err);
throw new BadRequestException('Failed to set alias');
}
}
// Already points at this page -> nothing to do.
if (existing.pageId === pageId) {
return existing;
}
// Name occupied by a different (or dangling) target: require confirmation.
if (!confirmReassign) {
const currentPage = existing.pageId
? await this.pageRepo.findById(existing.pageId)
: null;
throw new ConflictException({
message: 'Alias already in use',
code: 'ALIAS_REASSIGN_REQUIRED',
currentPageId: existing.pageId,
currentPageTitle: currentPage?.title ?? null,
});
}
return this.shareAliasRepo.updatePageId(existing.id, pageId, workspaceId);
}
/** Free a vanity name (no history kept). */
async removeAlias(aliasId: string, workspaceId: string): Promise<void> {
await this.shareAliasRepo.delete(aliasId, workspaceId);
}
/** Debounced availability probe for the modal. */
async checkAvailability(
rawAlias: string,
workspaceId: string,
): Promise<{
alias: string;
valid: boolean;
available: boolean;
currentPageId: string | null;
}> {
const alias = normalizeShareAlias(rawAlias);
if (!isValidShareAlias(alias)) {
return { alias, valid: false, available: false, currentPageId: null };
}
const existing = await this.shareAliasRepo.findByAliasAndWorkspace(
alias,
workspaceId,
);
return {
alias,
valid: true,
available: !existing,
currentPageId: existing?.pageId ?? null,
};
}
/** A single alias row scoped to the workspace, or undefined. */
getAliasById(
aliasId: string,
workspaceId: string,
): Promise<ShareAlias | undefined> {
return this.shareAliasRepo.findById(aliasId, workspaceId);
}
/** The alias currently targeting a page (modal display), or undefined. */
getAliasForPage(
pageId: string,
workspaceId: string,
): Promise<ShareAlias | undefined> {
return this.shareAliasRepo.findByPageId(pageId, workspaceId);
}
/**
* Resolve a vanity alias to the canonical, publicly-READABLE share page, or
* null. This re-runs the authoritative share boundary at request time (so a
* later-unshared / restricted / sharing-disabled target collapses to null and
* the caller serves the generic SPA 404 — no existence leak). The alias row
* itself is just a pointer; this is where access is actually decided.
*/
async resolveReadableTarget(
rawAlias: string,
workspaceId: string,
): Promise<ResolvedAliasTarget | null> {
const alias = normalizeShareAlias(rawAlias);
if (!isValidShareAlias(alias)) return null;
const aliasRow = await this.shareAliasRepo.findByAliasAndWorkspace(
alias,
workspaceId,
);
// Unknown name or a dangling alias (target page deleted) -> not resolvable.
if (!aliasRow?.pageId) return null;
const resolved = await this.shareService.resolveReadableSharePage(
undefined,
aliasRow.pageId,
workspaceId,
);
if (!resolved) return null;
const sharingAllowed = await this.shareService.isSharingAllowed(
workspaceId,
resolved.share.spaceId,
);
if (!sharingAllowed) return null;
return resolved;
}
}

View File

@@ -0,0 +1,60 @@
import { isValidShareAlias, normalizeShareAlias } from './share-alias.util';
describe('normalizeShareAlias', () => {
it('lowercases and trims', () => {
expect(normalizeShareAlias(' HelloWorld ')).toBe('helloworld');
});
it('converts spaces and underscores to single hyphens', () => {
expect(normalizeShareAlias('my cool page')).toBe('my-cool-page');
expect(normalizeShareAlias('my_cool_page')).toBe('my-cool-page');
});
it('collapses repeated hyphens and trims edge hyphens', () => {
expect(normalizeShareAlias('--a---b--')).toBe('a-b');
});
it('handles null/undefined defensively', () => {
expect(normalizeShareAlias(undefined as unknown as string)).toBe('');
});
});
describe('isValidShareAlias', () => {
it('accepts ascii lowercase hyphen-separated slugs', () => {
expect(isValidShareAlias('hello')).toBe(true);
expect(isValidShareAlias('hello-world-2')).toBe(true);
expect(isValidShareAlias('a1')).toBe(true);
});
it('rejects too short / too long', () => {
expect(isValidShareAlias('a')).toBe(false);
expect(isValidShareAlias('a'.repeat(61))).toBe(false);
expect(isValidShareAlias('a'.repeat(60))).toBe(true);
});
it('rejects leading/trailing/double hyphens', () => {
expect(isValidShareAlias('-abc')).toBe(false);
expect(isValidShareAlias('abc-')).toBe(false);
expect(isValidShareAlias('a--b')).toBe(false);
});
it('rejects uppercase, cyrillic and other non-ascii', () => {
expect(isValidShareAlias('Hello')).toBe(false);
expect(isValidShareAlias('привет')).toBe(false);
expect(isValidShareAlias('a b')).toBe(false);
expect(isValidShareAlias('a_b')).toBe(false);
expect(isValidShareAlias('a.b')).toBe(false);
});
it('normalize + validate round-trips a messy input to a valid slug', () => {
const alias = normalizeShareAlias(' My Cool_Page!! ');
// "!!" is not stripped by normalize (only case/separators), so the result
// still fails validation — the charset gate is intentionally separate.
expect(alias).toBe('my-cool-page!!');
expect(isValidShareAlias(alias)).toBe(false);
const ok = normalizeShareAlias(' My Cool Page ');
expect(ok).toBe('my-cool-page');
expect(isValidShareAlias(ok)).toBe(true);
});
});

View File

@@ -0,0 +1,30 @@
/**
* Vanity share-alias helpers shared by the write path (set/availability) and the
* `/l/:alias` resolve path. Aliases are ASCII-only, lowercase, hyphen-separated
* slugs — deliberately no Cyrillic / transliteration: the user types the exact
* canonical form. Keep this in sync with the client copy in
* `apps/client/src/features/share/share-alias.util.ts`.
*/
// Normalize a user-provided vanity alias into canonical ASCII storage form.
// This only canonicalizes shape (case, separators); it does NOT enforce the
// charset — call isValidShareAlias afterwards to reject anything illegal.
export function normalizeShareAlias(raw: string): string {
return (raw ?? '')
.trim()
.toLowerCase()
.replace(/[\s_]+/g, '-') // spaces/underscores -> single hyphen
.replace(/-{2,}/g, '-') // collapse repeated hyphens
.replace(/^-+|-+$/g, ''); // trim leading/trailing hyphens
}
// ASCII only: lowercase letters/digits in hyphen-separated groups, length 2..60.
const ALIAS_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
export function isValidShareAlias(alias: string): boolean {
return (
typeof alias === 'string' &&
alias.length >= 2 &&
alias.length <= 60 &&
ALIAS_RE.test(alias)
);
}

View File

@@ -5,13 +5,22 @@ import { TokenModule } from '../auth/token.module';
import { ShareSeoController } from './share-seo.controller';
import { TransclusionModule } from '../page/transclusion/transclusion.module';
import { AiModule } from '../../integrations/ai/ai.module';
import { ShareAliasService } from './share-alias.service';
import { ShareAliasController } from './share-alias.controller';
import { ShareAliasRedirectController } from './share-alias-redirect.controller';
@Module({
// AiModule (AiSettingsService) is used by the page-info route to surface
// whether the anonymous public-share assistant is enabled for the workspace.
imports: [TokenModule, TransclusionModule, AiModule],
controllers: [ShareController, ShareSeoController],
providers: [ShareService],
exports: [ShareService],
controllers: [
ShareController,
ShareSeoController,
// Vanity /l/:alias: authenticated management + public 302 resolver.
ShareAliasController,
ShareAliasRedirectController,
],
providers: [ShareService, ShareAliasService],
exports: [ShareService, ShareAliasService],
})
export class ShareModule {}

View File

@@ -23,6 +23,7 @@ import { UserTokenRepo } from './repos/user-token/user-token.repo';
import { UserSessionRepo } from '@docmost/db/repos/session/user-session.repo';
import { BacklinkRepo } from '@docmost/db/repos/backlink/backlink.repo';
import { ShareRepo } from '@docmost/db/repos/share/share.repo';
import { ShareAliasRepo } from '@docmost/db/repos/share-alias/share-alias.repo';
import { NotificationRepo } from '@docmost/db/repos/notification/notification.repo';
import { WatcherRepo } from '@docmost/db/repos/watcher/watcher.repo';
import { LabelRepo } from '@docmost/db/repos/label/label.repo';
@@ -96,6 +97,7 @@ import { normalizePostgresUrl } from '../common/helpers';
UserSessionRepo,
BacklinkRepo,
ShareRepo,
ShareAliasRepo,
NotificationRepo,
WatcherRepo,
LabelRepo,
@@ -128,6 +130,7 @@ import { normalizePostgresUrl } from '../common/helpers';
UserSessionRepo,
BacklinkRepo,
ShareRepo,
ShareAliasRepo,
NotificationRepo,
WatcherRepo,
LabelRepo,

View File

@@ -0,0 +1,54 @@
import { type Kysely, sql } from 'kysely';
/**
* Vanity share aliases: a retargetable, human-readable pointer (`/l/<alias>`)
* that lives independently of any single `shares` row. The alias belongs to the
* WORKSPACE (stable address), and `page_id` is nullable with ON DELETE SET NULL
* so the address survives deletion of its current target (it 404s until
* retargeted) rather than disappearing with the page.
*/
export async function up(db: Kysely<any>): Promise<void> {
await db.schema
.createTable('share_aliases')
.addColumn('id', 'uuid', (col) =>
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
)
.addColumn('workspace_id', 'uuid', (col) =>
col.references('workspaces.id').onDelete('cascade').notNull(),
)
// Normalized ASCII, lowercase. Uniqueness is enforced per-workspace below.
.addColumn('alias', 'varchar', (col) => col.notNull())
// Nullable + SET NULL: the address outlives its target page.
.addColumn('page_id', 'uuid', (col) =>
col.references('pages.id').onDelete('set null'),
)
.addColumn('creator_id', 'uuid', (col) =>
col.references('users.id').onDelete('set null'),
)
.addColumn('created_at', 'timestamptz', (col) =>
col.notNull().defaultTo(sql`now()`),
)
.addColumn('updated_at', 'timestamptz', (col) =>
col.notNull().defaultTo(sql`now()`),
)
.execute();
// The vanity name is unique within a workspace (mirrors shares.key scoping).
await db.schema
.createIndex('share_aliases_workspace_id_alias_unique')
.on('share_aliases')
.columns(['workspace_id', 'alias'])
.unique()
.execute();
// "Which alias targets this page?" lookup for the share modal.
await db.schema
.createIndex('share_aliases_page_id_idx')
.on('share_aliases')
.column('page_id')
.execute();
}
export async function down(db: Kysely<any>): Promise<void> {
await db.schema.dropTable('share_aliases').execute();
}

View File

@@ -18,7 +18,8 @@ import { executeWithCursorPagination } from '@docmost/db/pagination/cursor-pagin
// (multi-instance deploy).
const SWEEP_STREAMING_STALE_MS = 10 * 60 * 1000; // 10 minutes
// Hard upper bound on the rows materialized by `findAllByChat` (export path).
// Hard upper bound on the rows materialized by `findAllByChat`, which now feeds
// BOTH the Markdown export and the per-turn model history.
// A generous cap so a pathologically huge chat cannot load an unbounded result
// into memory; far above any realistic transcript length.
const FIND_ALL_BY_CHAT_LIMIT = 5000;
@@ -78,14 +79,17 @@ export class AiChatMessageRepo {
}
// Load ALL (non-deleted) messages of a chat in ascending chronological order
// (oldest -> newest), unpaginated. Used by the server-side Markdown export
// (#183), where the DB is the single source of truth and the whole transcript
// must be rendered in one pass (findByChat is cursor-paginated and would only
// return the first page).
// (oldest -> newest), unpaginated. Two callers, both treating the DB as the
// single source of truth and needing the whole transcript in one pass
// (findByChat is cursor-paginated and would only return the first page):
// - the server-side Markdown export (#183);
// - the per-turn model history, rebuilt fresh on every turn so the model
// sees the full authoritative transcript.
//
// Hard-capped at FIND_ALL_BY_CHAT_LIMIT rows (a generous bound, far above any
// realistic transcript) so exporting a pathologically huge chat cannot
// materialize an unbounded result set in memory.
// realistic transcript) — a shared memory-safety backstop for BOTH paths so a
// pathologically huge chat cannot materialize an unbounded result set in
// memory. On overflow the NEWEST rows are kept and a warning is logged.
async findAllByChat(
chatId: string,
workspaceId: string,
@@ -93,9 +97,9 @@ export class AiChatMessageRepo {
limit: number = FIND_ALL_BY_CHAT_LIMIT,
): Promise<AiChatMessage[]> {
// Fetch newest-first (+1 to DETECT truncation), so on overflow we keep the
// NEWEST `limit` messages — the recent conversation matters most for an
// export — rather than silently dropping the tail (#183 review). Reverse back
// to chronological for rendering, like findRecent.
// NEWEST `limit` messages — the recent conversation matters most — rather
// than silently dropping the tail (#183 review). Then reverse back to
// chronological order (oldest -> newest) for rendering / model replay.
const rows = await this.db
.selectFrom('aiChatMessages')
.select(this.baseFields)
@@ -110,38 +114,13 @@ export class AiChatMessageRepo {
if (rows.length > limit) {
rows.length = limit; // keep the newest `limit` (rows are newest-first here)
this.logger.warn(
`Chat ${chatId} export truncated to the newest ${limit} messages ` +
`Chat ${chatId} truncated to the newest ${limit} messages ` +
`(older messages omitted).`,
);
}
return rows.reverse();
}
// Load the most RECENT `limit` messages for a chat and return them in
// ascending chronological order (oldest -> newest), as the model expects.
// `findByChat` returns the FIRST page ASC (the OLDEST messages), which loses
// recent turns once a chat grows beyond a page; this rebuilds the model
// history from the tail instead. Plain query (no cursor pagination).
async findRecent(
chatId: string,
workspaceId: string,
limit: number,
): Promise<AiChatMessage[]> {
const rows = await this.db
.selectFrom('aiChatMessages')
.select(this.baseFields)
.where('chatId', '=', chatId)
.where('workspaceId', '=', workspaceId)
.where('deletedAt', 'is', null)
.orderBy('createdAt', 'desc')
.orderBy('id', 'desc')
.limit(limit)
.execute();
// Selected newest-first for the limit; reverse to oldest-first for the model.
return rows.reverse();
}
async insert(
insertable: InsertableAiChatMessage,
trx?: KyselyTransaction,

View File

@@ -0,0 +1,120 @@
import { ShareAliasRepo } from './share-alias.repo';
import type { KyselyDB } from '../../types/kysely.types';
/**
* SQL-shape unit tests for ShareAliasRepo. A live Postgres is out of scope;
* instead we spy on the Kysely builder to assert each method pins the
* workspace scope (so a name in one workspace can never resolve another's
* page) and threads the right columns.
*/
describe('ShareAliasRepo', () => {
function makeSelectRepo(result: unknown) {
const where = jest.fn();
const builder: any = {
select: jest.fn(() => builder),
where: jest.fn((...args: unknown[]) => {
where(...args);
return builder;
}),
executeTakeFirst: jest.fn().mockResolvedValue(result),
};
const db = { selectFrom: jest.fn(() => builder) } as unknown as KyselyDB;
return { repo: new ShareAliasRepo(db), db, where, builder };
}
it('findByAliasAndWorkspace scopes by alias AND workspace', async () => {
const row = { id: 'a-1', alias: 'foo', workspaceId: 'ws-1' };
const { repo, db, where } = makeSelectRepo(row);
const res = await repo.findByAliasAndWorkspace('foo', 'ws-1');
expect(res).toBe(row);
expect(db.selectFrom).toHaveBeenCalledWith('shareAliases');
expect(where).toHaveBeenCalledWith('alias', '=', 'foo');
expect(where).toHaveBeenCalledWith('workspaceId', '=', 'ws-1');
});
it('findByPageId scopes by page AND workspace', async () => {
const { repo, where } = makeSelectRepo(undefined);
await repo.findByPageId('p-1', 'ws-1');
expect(where).toHaveBeenCalledWith('pageId', '=', 'p-1');
expect(where).toHaveBeenCalledWith('workspaceId', '=', 'ws-1');
});
it('insert writes the provided columns and returns the row', async () => {
const values = jest.fn();
const inserted = { id: 'a-1' };
const builder: any = {
values: jest.fn((v: unknown) => {
values(v);
return builder;
}),
returning: jest.fn(() => builder),
executeTakeFirst: jest.fn().mockResolvedValue(inserted),
};
const db = { insertInto: jest.fn(() => builder) } as unknown as KyselyDB;
const repo = new ShareAliasRepo(db);
const res = await repo.insert({
workspaceId: 'ws-1',
alias: 'foo',
pageId: 'p-1',
creatorId: 'u-1',
});
expect(db.insertInto).toHaveBeenCalledWith('shareAliases');
expect(values).toHaveBeenCalledWith({
workspaceId: 'ws-1',
alias: 'foo',
pageId: 'p-1',
creatorId: 'u-1',
});
expect(res).toBe(inserted);
});
it('updatePageId retargets a single row scoped by id + workspace', async () => {
const set = jest.fn();
const where = jest.fn();
const builder: any = {
set: jest.fn((s: unknown) => {
set(s);
return builder;
}),
where: jest.fn((...args: unknown[]) => {
where(...args);
return builder;
}),
returning: jest.fn(() => builder),
executeTakeFirst: jest.fn().mockResolvedValue({ id: 'a-1' }),
};
const db = { updateTable: jest.fn(() => builder) } as unknown as KyselyDB;
const repo = new ShareAliasRepo(db);
await repo.updatePageId('a-1', 'p-2', 'ws-1');
expect(db.updateTable).toHaveBeenCalledWith('shareAliases');
expect(set.mock.calls[0][0].pageId).toBe('p-2');
expect(set.mock.calls[0][0].updatedAt).toBeInstanceOf(Date);
expect(where).toHaveBeenCalledWith('id', '=', 'a-1');
expect(where).toHaveBeenCalledWith('workspaceId', '=', 'ws-1');
});
it('delete scopes by id + workspace', async () => {
const where = jest.fn();
const builder: any = {
where: jest.fn((...args: unknown[]) => {
where(...args);
return builder;
}),
execute: jest.fn().mockResolvedValue(undefined),
};
const db = { deleteFrom: jest.fn(() => builder) } as unknown as KyselyDB;
const repo = new ShareAliasRepo(db);
await repo.delete('a-1', 'ws-1');
expect(db.deleteFrom).toHaveBeenCalledWith('shareAliases');
expect(where).toHaveBeenCalledWith('id', '=', 'a-1');
expect(where).toHaveBeenCalledWith('workspaceId', '=', 'ws-1');
});
});

View File

@@ -0,0 +1,109 @@
import { Injectable } from '@nestjs/common';
import { InjectKysely } from 'nestjs-kysely';
import { KyselyDB, KyselyTransaction } from '../../types/kysely.types';
import { dbOrTx } from '../../utils';
import {
InsertableShareAlias,
ShareAlias,
} from '@docmost/db/types/entity.types';
/**
* Repository for vanity share aliases (`/l/:alias`). An alias is a long-lived,
* workspace-scoped pointer to a page; retargeting is a single UPDATE of
* `page_id`. All lookups are workspace-scoped so a name in one workspace can
* never resolve a page in another.
*/
@Injectable()
export class ShareAliasRepo {
constructor(@InjectKysely() private readonly db: KyselyDB) {}
private baseFields: Array<keyof ShareAlias> = [
'id',
'workspaceId',
'alias',
'pageId',
'creatorId',
'createdAt',
'updatedAt',
];
/** Resolve a (normalized) alias within a workspace, or undefined. */
async findByAliasAndWorkspace(
alias: string,
workspaceId: string,
trx?: KyselyTransaction,
): Promise<ShareAlias | undefined> {
return dbOrTx(this.db, trx)
.selectFrom('shareAliases')
.select(this.baseFields)
.where('alias', '=', alias)
.where('workspaceId', '=', workspaceId)
.executeTakeFirst();
}
/** The alias currently pointing at a page (for the share modal). */
async findByPageId(
pageId: string,
workspaceId: string,
trx?: KyselyTransaction,
): Promise<ShareAlias | undefined> {
return dbOrTx(this.db, trx)
.selectFrom('shareAliases')
.select(this.baseFields)
.where('pageId', '=', pageId)
.where('workspaceId', '=', workspaceId)
.executeTakeFirst();
}
async findById(
id: string,
workspaceId: string,
trx?: KyselyTransaction,
): Promise<ShareAlias | undefined> {
return dbOrTx(this.db, trx)
.selectFrom('shareAliases')
.select(this.baseFields)
.where('id', '=', id)
.where('workspaceId', '=', workspaceId)
.executeTakeFirst();
}
async insert(
insertable: InsertableShareAlias,
trx?: KyselyTransaction,
): Promise<ShareAlias> {
return dbOrTx(this.db, trx)
.insertInto('shareAliases')
.values(insertable)
.returning(this.baseFields)
.executeTakeFirst();
}
/** Retarget an existing alias to a new page (the "swap" operation). */
async updatePageId(
id: string,
pageId: string,
workspaceId: string,
trx?: KyselyTransaction,
): Promise<ShareAlias> {
return dbOrTx(this.db, trx)
.updateTable('shareAliases')
.set({ pageId, updatedAt: new Date() })
.where('id', '=', id)
.where('workspaceId', '=', workspaceId)
.returning(this.baseFields)
.executeTakeFirst();
}
async delete(
id: string,
workspaceId: string,
trx?: KyselyTransaction,
): Promise<void> {
await dbOrTx(this.db, trx)
.deleteFrom('shareAliases')
.where('id', '=', id)
.where('workspaceId', '=', workspaceId)
.execute();
}
}

View File

@@ -0,0 +1,94 @@
import * as migration from './migrations/20260626T130000-share-aliases';
import type {
InsertableShareAlias,
ShareAlias,
UpdatableShareAlias,
} from './types/entity.types';
/**
* Sanity checks for the share_aliases migration + entity types. We don't run a
* live Postgres here (that's the integration suite); instead we assert the
* migration exposes the expected up/down contract and creates the table with
* the unique (workspace_id, alias) constraint and the page_id index, and that
* the generated entity types line up with the column set.
*/
describe('share-aliases migration', () => {
it('up creates the table, the unique index and the page_id index', async () => {
const calls: string[] = [];
const tableBuilder: any = new Proxy(
{},
{
get(_t, prop: string) {
if (prop === 'execute') return async () => undefined;
// addColumn/addConstraint/etc. are chainable no-ops.
return () => tableBuilder;
},
},
);
const indexBuilder: any = new Proxy(
{},
{
get(_t, prop: string) {
if (prop === 'execute') return async () => undefined;
return () => indexBuilder;
},
},
);
const schema = {
createTable: (name: string) => {
calls.push(`createTable:${name}`);
return tableBuilder;
},
createIndex: (name: string) => {
calls.push(`createIndex:${name}`);
return indexBuilder;
},
};
await migration.up({ schema } as any);
expect(calls).toContain('createTable:share_aliases');
expect(calls).toContain(
'createIndex:share_aliases_workspace_id_alias_unique',
);
expect(calls).toContain('createIndex:share_aliases_page_id_idx');
});
it('down drops the table', async () => {
const calls: string[] = [];
const dropBuilder: any = { execute: async () => undefined };
const schema = {
dropTable: (name: string) => {
calls.push(`dropTable:${name}`);
return dropBuilder;
},
};
await migration.down({ schema } as any);
expect(calls).toContain('dropTable:share_aliases');
});
it('entity types expose the alias columns', () => {
// Compile-time only: these typed declarations fail `tsc` if the entity types
// drift (missing/renamed columns, wrong nullability). The runtime assertions
// would be tautological, so the value is purely in the type-check.
const row: ShareAlias = {
id: 'a-1',
workspaceId: 'ws-1',
alias: 'foo',
pageId: 'p-1',
creatorId: 'u-1',
createdAt: new Date(),
updatedAt: new Date(),
};
const insert: InsertableShareAlias = {
workspaceId: 'ws-1',
alias: 'foo',
};
const update: UpdatableShareAlias = { pageId: null };
expect([row, insert, update]).toHaveLength(3);
});
});

View File

@@ -305,6 +305,16 @@ export interface Pages {
ydoc: Buffer | null;
}
export interface ShareAliases {
alias: string;
createdAt: Generated<Timestamp>;
creatorId: string | null;
id: Generated<string>;
pageId: string | null;
updatedAt: Generated<Timestamp>;
workspaceId: string;
}
export interface Shares {
createdAt: Generated<Timestamp>;
creatorId: string | null;
@@ -674,6 +684,7 @@ export interface DB {
pageVerifiers: PageVerifiers;
pages: Pages;
scimTokens: ScimTokens;
shareAliases: ShareAliases;
shares: Shares;
spaceMembers: SpaceMembers;
spaces: Spaces;

View File

@@ -30,6 +30,7 @@ import {
AuthProviders,
AuthAccounts,
Shares,
ShareAliases,
Favorites,
FileTasks,
UserMfa as _UserMFA,
@@ -172,6 +173,11 @@ export type Share = Selectable<Shares>;
export type InsertableShare = Insertable<Shares>;
export type UpdatableShare = Updateable<Omit<Shares, 'id'>>;
// Share alias (vanity /l/:alias pointer)
export type ShareAlias = Selectable<ShareAliases>;
export type InsertableShareAlias = Insertable<ShareAliases>;
export type UpdatableShareAlias = Updateable<Omit<ShareAliases, 'id'>>;
// Favorite
export type Favorite = Selectable<Favorites>;
export type InsertableFavorite = Insertable<Favorites>;

View File

@@ -40,7 +40,14 @@ async function bootstrap() {
app.useLogger(app.get(PinoLogger));
app.setGlobalPrefix('api', {
exclude: ['robots.txt', 'share/:shareId/p/:pageSlug', 'mcp'],
exclude: [
'robots.txt',
'share/:shareId/p/:pageSlug',
// Vanity link resolver lives outside /api so /l/<alias> is a clean
// public URL that 302s to the canonical share page.
'l/:alias',
'mcp',
],
});
const reflector = app.get(Reflector);

View File

@@ -1,18 +1,34 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
let app: NestFastifyApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
// Docmost runs on Fastify (see src/main.ts). The default
// createNestApplication() would load @nestjs/platform-express, which is not
// a dependency of this project, so an explicit FastifyAdapter is required.
app = moduleFixture.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
await app.init();
// Fastify must finish booting before its HTTP server can serve requests.
await app.getHttpAdapter().getInstance().ready();
});
afterEach(async () => {
// Guard with optional chaining: if beforeEach throws before `app` is
// assigned, closing undefined would mask the original failure.
await app?.close();
});
it('/ (GET)', () => {

View File

@@ -267,4 +267,36 @@ describe('AiChatMessageRepo.update + sweepStreaming [integration]', () => {
const all = await repo.findAllByChat(cappedChat, workspaceId, 100);
expect(all.map((r) => r.content)).toEqual(['m1-oldest', 'm2', 'm3-newest']);
});
it('default findAllByChat returns the FULL transcript past 50 rows — no recent-tail window (#202)', async () => {
// PR #202 swapped the model-history rebuild in AiChatService.handle from
// findRecent(chatId, ws, 50) to findAllByChat(chatId, ws) WITHOUT a limit
// arg. This pins the behavioral guarantee that switch relies on: a chat
// longer than the old 50-msg window comes back in FULL (oldest -> newest),
// so no early turns are silently dropped from what the model sees. The old
// 50-cap would have returned only the last 50 of these 60 rows.
const longChat = (
await createChat(db, { workspaceId, creatorId: userId })
).id;
const base = Date.now();
const total = 60;
for (let i = 0; i < total; i++) {
await createMessage(db, {
workspaceId,
chatId: longChat,
content: `msg-${i}`,
// Strictly increasing timestamps so ordering is deterministic.
createdAt: new Date(base + i * 1000),
});
}
// Default args == exactly how handle() calls it now.
const history = await repo.findAllByChat(longChat, workspaceId);
expect(history).toHaveLength(total);
expect(history.map((r) => r.content)).toEqual(
Array.from({ length: total }, (_, i) => `msg-${i}`),
);
// The very first turn (which the old 50-window would have dropped) is present.
expect(history[0]!.content).toBe('msg-0');
});
});

View File

@@ -1,14 +1,18 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"moduleFileExtensions": ["js", "json", "ts", "tsx"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
"^.+\\.(t|j)sx?$": ["ts-jest", { "tsconfig": { "allowJs": true } }]
},
"transformIgnorePatterns": [
"/node_modules/(?!(\\.pnpm/)?(nanoid|uuid|image-dimensions|marked|happy-dom|lib0|@sindresorhus[+/][a-z0-9-]+|escape-string-regexp|p-limit|yocto-queue)(@|/))"
],
"moduleNameMapper": {
"^@docmost/db/(.*)$": "<rootDir>/../src/database/$1",
"^@docmost/transactional/(.*)$": "<rootDir>/../src/integrations/transactional/$1",
"^@docmost/ee/(.*)$": "<rootDir>/../src/ee/$1"
"^@docmost/ee/(.*)$": "<rootDir>/../src/ee/$1",
"^src/(.*)$": "<rootDir>/../src/$1"
}
}

View File

@@ -1,7 +1,7 @@
{
"name": "docmost",
"homepage": "https://docmost.com",
"version": "0.94.0",
"version": "0.94.1",
"private": true,
"scripts": {
"build": "nx run-many -t build",

View File

@@ -7,6 +7,7 @@ import { writeFileSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { deflateSync } from "node:zlib";
import { createServer } from "node:http";
const API = process.env.DOCMOST_API_URL;
if (!API || !process.env.DOCMOST_EMAIL || !process.env.DOCMOST_PASSWORD) {
@@ -104,7 +105,7 @@ async function main() {
{ find: "БУКВОЕД", replace: "КНИГОЛЮБ" },
{ find: "[1]", replace: "[42]" },
]);
check("edit_page_text: both edits applied", editRes.edits.every((e) => e.replacements === 1));
check("edit_page_text: both edits applied", editRes.applied.every((e) => e.replacements === 1));
await new Promise((r) => setTimeout(r, 16000)); // wait for server persistence
const pj2 = await client.getPageJson(pageId);
const text2 = JSON.stringify(pj2.content);
@@ -149,11 +150,24 @@ async function main() {
check("update_page_json: paragraph appended", JSON.stringify(pj4.content).includes("добавленный через update_page_json"));
check("update_page_json: custom node id preserved", lastNode.attrs?.id === "testidjsonpush", lastNode.attrs?.id);
// 6b. images: upload / insert / replace (clean src, fresh attachment on replace)
const pngA = join(tmpdir(), `mcp-e2e-img-a-${Date.now()}.png`);
const pngB = join(tmpdir(), `mcp-e2e-img-b-${Date.now()}.png`);
writeFileSync(pngA, makePng(255, 0, 0)); // red
writeFileSync(pngB, makePng(0, 0, 255)); // blue (a DIFFERENT valid PNG)
// 6b. images: upload / insert / replace (clean src, fresh attachment on replace).
// insert_image / replace_image take an http(s) URL that the SERVER fetches;
// local file paths are intentionally unsupported. The Docmost server runs on
// the same host as this test, so serve the PNG bytes over a throwaway
// localhost HTTP server it can reach.
const bytesA = makePng(255, 0, 0); // red
const bytesB = makePng(0, 0, 255); // blue (a DIFFERENT valid PNG)
const imgServer = createServer((req, res) => {
res.writeHead(200, { "Content-Type": "image/png" });
res.end(req.url === "/b.png" ? bytesB : bytesA);
});
await new Promise((resolve, reject) => {
imgServer.once("error", reject);
imgServer.listen(0, "127.0.0.1", resolve);
});
const imgPort = imgServer.address().port;
const urlA = `http://127.0.0.1:${imgPort}/a.png`;
const urlB = `http://127.0.0.1:${imgPort}/b.png`;
try {
// Independent login to fetch file bytes with the same cookie the editor uses.
const login = await axios.post(
@@ -173,7 +187,7 @@ async function main() {
});
// insert_image: append the first PNG, src must be clean (no ?v=) and fetchable.
const ins = await client.insertImage(pageId, pngA);
const ins = await client.insertImage(pageId, urlA);
check("insert_image: src has no ?v= cache-buster", !ins.src.includes("?v="), ins.src);
const fileA = await fetchFile(ins.src);
check("insert_image: file fetch returns 200", fileA.status === 200, `status=${fileA.status}`);
@@ -199,7 +213,7 @@ async function main() {
// replace_image: must create a NEW attachment with a clean, fetchable URL.
// The 200 fetch is the assertion that catches the in-place-overwrite HTTP 500 regression.
const rep = await client.replaceImage(pageId, oldAttachmentId, pngB);
const rep = await client.replaceImage(pageId, oldAttachmentId, urlB);
check("replace_image: new attachment id differs from old", rep.newAttachmentId !== oldAttachmentId, `${oldAttachmentId} -> ${rep.newAttachmentId}`);
check("replace_image: src has no ?v= cache-buster", !rep.src.includes("?v="), rep.src);
const fileB = await fetchFile(rep.src);
@@ -215,8 +229,7 @@ async function main() {
check("replace_image: page has new attachment id", !!findImage(pjImg2.content.content, rep.newAttachmentId), rep.newAttachmentId);
check("replace_image: old attachment id repointed away", !findImage(pjImg2.content.content, oldAttachmentId), oldAttachmentId);
} finally {
try { unlinkSync(pngA); } catch {}
try { unlinkSync(pngB); } catch {}
imgServer.close();
}
// 6c. rich formatting: callout type, task list, inline marks, table alignment,
@@ -441,7 +454,10 @@ async function main() {
// 9. comments: create / list / reply / update / check_new / delete
const beforeComments = new Date(Date.now() - 1000).toISOString();
const c1 = await client.createComment(pageId, "Первый **комментарий** с [ссылкой](https://example.com).");
// A top-level comment requires an inline "selection": exact contiguous text
// that exists in the persisted page to anchor on. "Добавленный абзац." is a
// plain paragraph re-imported in section 5 and still present here.
const c1 = await client.createComment(pageId, "Первый **комментарий** с [ссылкой](https://example.com).", "inline", "Добавленный абзац.");
check("create_comment: created", !!c1.data.id, c1.data.id);
check("create_comment: markdown round-trip", c1.data.content.includes("**комментарий**"), c1.data.content);
const reply = await client.createComment(pageId, "Ответ на комментарий.", "page", undefined, c1.data.id);