Compare commits

..

12 Commits

Author SHA1 Message Date
claude code agent 227
9632146d23 test(editor): cover focused-title guard and destroyed-editor early-out
Add coverage for the two untested branches in useGeneratePageTitle's
post-generation write: suppressing setContent when the live title editor
is focused (DB write + broadcast still happen, only the visible field
write is skipped), and the early return when the page editor is
destroyed (model never called).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 20:39:03 +03:00
claude code agent 227
0314416bfa Address PR #210 review: changelog, navigation guard, hook tests (#199)
- CHANGELOG: add an [Unreleased]/Added bullet documenting the
  "generate title from content" byline button (reads live editor
  content, generates via the workspace AI provider, applies through
  /pages/update, gated by settings.ai.generative, throttled per user).

- use-generate-page-title: guard the visible title write against page
  navigation during generation. The mutation awaits the model for 1-3s;
  its closure captures the editors from the starting render, but the
  global page/title atoms re-point on navigation. We now keep a live ref
  to the current editors and skip setContent unless the live page editor
  still belongs to the page the title was generated for
  (editor.storage.pageId === pageId, mirroring TitleEditor's
  activePageId guard). The DB write stays correct (keyed by the captured
  pageId) and the websocket broadcast is unchanged, so only the wrong-page
  field write is suppressed.

- Add a vitest suite for the hook: empty content, empty model response,
  happy path, the navigation guard, and 403/503/429/other onError mapping.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 20:39:03 +03:00
claude code agent 227
001ebe2e53 feat(ai): generate page title from content (#199)
Add an AI button in the page byline that generates a note's title from the
live editor content (including unsaved edits) and applies it immediately.

Server: one-shot, non-streaming POST /ai-chat/generate-page-title mirroring
the chat generateTitle path — gated by settings.ai.generative, throttled via
AI_CHAT_THROTTLER, resolves the workspace chat model and returns { title }.
The endpoint never touches the page; the client applies the title through the
existing /pages/update route (which enforces edit permission).

Client: ai-chat-service.generatePageTitle, a useGeneratePageTitle hook that
converts the editor HTML to markdown, calls the endpoint, applies the title
via updateTitle + updatePageData, reflects it in the unfocused title editor,
and broadcasts the UpdateEvent (mirroring TitleEditor.saveTitle). A sparkles
button (GenerateTitleGroup) renders next to dictation, edit-mode + flag gated.

Tests: pure cleanGeneratedTitle helper + controller gate/delegation/error-map.
i18n: en-US + ru-RU strings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 20:39:03 +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 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
40 changed files with 2951 additions and 29 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
@@ -62,6 +72,12 @@ per-workspace rolling-day token budget.
- **Footnote multi-backlinks.** A footnote referenced more than once now shows a
back-link per reference (↩ a b c …), each scrolling to its own occurrence, like
Pandoc/Wikipedia; a single-reference footnote keeps the plain ↩. (#168)
- **Generate a page title from its content.** A "sparkles" button in the page
byline reads the live editor content (including unsaved edits), generates a
title via the workspace AI provider (`POST /ai-chat/generate-page-title`), and
applies it through the existing `/pages/update` route — reflecting it in the
title field and broadcasting to other clients. Gated by the `settings.ai.generative`
flag and throttled per user. (#199)
### Changed

View File

@@ -1318,5 +1318,23 @@
"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",
"Generate title with AI": "Generate title with AI",
"Title generated": "Title generated",
"Failed to generate title": "Failed to generate title",
"The note is empty": "The note is empty",
"Could not generate a title": "Could not generate a title",
"AI title generation is disabled": "AI title generation is disabled",
"AI is not configured": "AI is not configured",
"Too many requests, please try again later": "Too many requests, please try again later"
}

View File

@@ -1175,5 +1175,23 @@
"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": "Не удалось удалить пользовательский адрес",
"Generate title with AI": "Сгенерировать название через AI",
"Title generated": "Название сгенерировано",
"Failed to generate title": "Не удалось сгенерировать название",
"The note is empty": "Заметка пустая",
"Could not generate a title": "Не удалось придумать название",
"AI title generation is disabled": "Генерация названий через AI отключена",
"AI is not configured": "AI не настроен",
"Too many requests, please try again later": "Слишком много запросов, попробуйте позже"
}

View File

@@ -68,6 +68,19 @@ export async function exportAiChat(
return req.data.markdown;
}
/**
* Generate a page title from note content (markdown). One-shot, non-streaming
* (#199): the server only summarizes the supplied text and returns a suggestion;
* it never writes the page. The caller applies the title via /pages/update.
*/
export async function generatePageTitle(content: string): Promise<string> {
const req = await api.post<{ title: string }>(
"/ai-chat/generate-page-title",
{ content },
);
return req.data.title;
}
/**
* Agent roles API (`/ai-chat/roles`). `list` is available to any workspace
* member (for the chat-creation picker); create/update/delete are admin-only

View File

@@ -0,0 +1,39 @@
import { FC } from "react";
import { ActionIcon, Tooltip } from "@mantine/core";
import { IconSparkles } from "@tabler/icons-react";
import { useTranslation } from "react-i18next";
import { useGeneratePageTitle } from "@/features/editor/hooks/use-generate-page-title.ts";
interface Props {
pageId: string;
color?: string;
iconSize?: number;
}
/**
* AI "generate title" button (#199). Reads the live editor content and applies a
* model-suggested title immediately. Rendered in the page byline, only in edit
* mode and when the workspace's generative AI flag is on.
*/
export const GenerateTitleGroup: FC<Props> = ({
pageId,
color = "gray",
iconSize = 20,
}) => {
const { t } = useTranslation();
const gen = useGeneratePageTitle(pageId);
return (
<Tooltip label={t("Generate title with AI")} withArrow openDelay={250}>
<ActionIcon
variant="subtle"
color={color}
aria-label={t("Generate title with AI")}
loading={gen.isPending}
onClick={() => gen.mutate()}
>
<IconSparkles size={iconSize} stroke={1.5} />
</ActionIcon>
</Tooltip>
);
};

View File

@@ -32,6 +32,7 @@ import {
pageEditorAtom,
} from "@/features/editor/atoms/editor-atoms.ts";
import { DictationGroup } from "@/features/editor/components/fixed-toolbar/groups/dictation-group";
import { GenerateTitleGroup } from "@/features/editor/components/fixed-toolbar/groups/generate-title-group";
const MemoizedTitleEditor = React.memo(TitleEditor);
const MemoizedPageEditor = React.memo(PageEditor);
@@ -74,6 +75,9 @@ export function FullEditor({
const [user] = useAtom(userAtom);
const workspace = useAtomValue(workspaceAtom);
const isDictationEnabled = workspace?.settings?.ai?.dictation === true;
// AI title generation reuses the generative AI flag (same gate as the on-page
// generative menu); the server enforces it too (#199).
const isTitleGenEnabled = workspace?.settings?.ai?.generative === true;
const fullPageWidth = user.settings?.preferences?.fullPageWidth;
const editorToolbarEnabled =
user.settings?.preferences?.editorToolbar ?? false;
@@ -111,11 +115,13 @@ export function FullEditor({
editable={editable}
/>
<PageByline
pageId={pageId}
creator={creator}
contributors={contributors}
editable={editable}
isEditMode={isEditMode}
isDictationEnabled={isDictationEnabled}
isTitleGenEnabled={isTitleGenEnabled}
/>
<MemoizedPageEditor
pageId={pageId}
@@ -128,19 +134,23 @@ export function FullEditor({
}
type PageBylineProps = {
pageId: string;
creator?: PageUser;
contributors?: IContributor[];
editable?: boolean;
isEditMode?: boolean;
isDictationEnabled?: boolean;
isTitleGenEnabled?: boolean;
};
function PageByline({
pageId,
creator,
contributors,
editable,
isEditMode,
isDictationEnabled,
isTitleGenEnabled,
}: PageBylineProps) {
const { t } = useTranslation();
const detailsTriggerProps = useAsideTriggerProps("details");
@@ -148,6 +158,9 @@ function PageByline({
const showDictation = Boolean(
isDictationEnabled && editable && isEditMode && editor,
);
const showTitleGen = Boolean(
isTitleGenEnabled && editable && isEditMode && editor,
);
const otherContributors = (contributors ?? []).filter(
(c) => c.id !== creator?.id,
@@ -238,6 +251,11 @@ function PageByline({
{showDictation && editor && (
<DictationGroup editor={editor} color="gray" iconSize={20} />
)}
{/* Shown only in edit mode when the workspace's generative AI flag is on,
so AI title generation stays reachable from the byline (#199). */}
{showTitleGen && (
<GenerateTitleGroup pageId={pageId} color="gray" iconSize={20} />
)}
</Group>
</Group>
);

View File

@@ -0,0 +1,294 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { renderHook, act } from "@testing-library/react";
import type { ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Provider, createStore } from "jotai";
import type { Editor } from "@tiptap/core";
import {
pageEditorAtom,
titleEditorAtom,
} from "@/features/editor/atoms/editor-atoms.ts";
// --- Mocks for the hook's collaborators ---------------------------------------
const generatePageTitleMock = vi.fn();
vi.mock("@/features/ai-chat/services/ai-chat-service.ts", () => ({
generatePageTitle: (content: string) => generatePageTitleMock(content),
}));
const updateTitleMock = vi.fn();
const updatePageDataMock = vi.fn();
vi.mock("@/features/page/queries/page-query.ts", () => ({
useUpdateTitlePageMutation: () => ({ mutateAsync: updateTitleMock }),
updatePageData: (page: unknown) => updatePageDataMock(page),
}));
const emitMock = vi.fn();
vi.mock("@/features/websocket/use-query-emit.ts", () => ({
useQueryEmit: () => emitMock,
}));
const localEmitMock = vi.fn();
vi.mock("@/lib/local-emitter.ts", () => ({
default: { emit: (...args: unknown[]) => localEmitMock(...args) },
}));
// htmlToMarkdown just echoes the editor HTML so each test controls the markdown
// purely via the fake page editor's getHTML().
vi.mock("@docmost/editor-ext", () => ({
htmlToMarkdown: (html: string) => html,
}));
const notificationsShowMock = vi.fn();
vi.mock("@mantine/notifications", () => ({
notifications: { show: (opts: unknown) => notificationsShowMock(opts) },
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
// Import after mocks are registered.
import { useGeneratePageTitle } from "./use-generate-page-title.ts";
// --- Test helpers -------------------------------------------------------------
function makePageEditor(pageId: string, html = "<p>content</p>"): Editor {
return {
isDestroyed: false,
getHTML: () => html,
storage: { pageId },
} as unknown as Editor;
}
function makeTitleEditor(): Editor & {
commands: { setContent: ReturnType<typeof vi.fn> };
} {
return {
isDestroyed: false,
isFocused: false,
commands: { setContent: vi.fn() },
} as unknown as Editor & {
commands: { setContent: ReturnType<typeof vi.fn> };
};
}
function setup(pageId: string, store = createStore()) {
const queryClient = new QueryClient({
defaultOptions: { mutations: { retry: false } },
});
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>
<Provider store={store}>{children}</Provider>
</QueryClientProvider>
);
const { result } = renderHook(() => useGeneratePageTitle(pageId), {
wrapper,
});
return { result, store };
}
const PAGE_A = {
id: "pageA",
title: "Generated Title",
spaceId: "space1",
slugId: "slugA",
parentPageId: null,
icon: null,
} as any;
beforeEach(() => {
vi.clearAllMocks();
});
describe("useGeneratePageTitle", () => {
it("shows a notice and bails when the editor content is empty", async () => {
const store = createStore();
store.set(pageEditorAtom as never, makePageEditor("pageA", " "));
store.set(titleEditorAtom as never, makeTitleEditor());
const { result } = setup("pageA", store);
await act(async () => {
await result.current.mutateAsync();
});
expect(notificationsShowMock).toHaveBeenCalledWith(
expect.objectContaining({ message: "The note is empty", color: "yellow" }),
);
expect(generatePageTitleMock).not.toHaveBeenCalled();
expect(updateTitleMock).not.toHaveBeenCalled();
});
it("leaves the title untouched when the model returns nothing usable", async () => {
const store = createStore();
store.set(pageEditorAtom as never, makePageEditor("pageA"));
store.set(titleEditorAtom as never, makeTitleEditor());
generatePageTitleMock.mockResolvedValue(" ");
const { result } = setup("pageA", store);
await act(async () => {
await result.current.mutateAsync();
});
expect(updateTitleMock).not.toHaveBeenCalled();
expect(notificationsShowMock).toHaveBeenCalledWith(
expect.objectContaining({
message: "Could not generate a title",
color: "yellow",
}),
);
});
it("happy path: applies the title, refreshes cache, writes the field, broadcasts", async () => {
const store = createStore();
const titleEditor = makeTitleEditor();
store.set(pageEditorAtom as never, makePageEditor("pageA"));
store.set(titleEditorAtom as never, titleEditor);
generatePageTitleMock.mockResolvedValue("Generated Title");
updateTitleMock.mockResolvedValue(PAGE_A);
const { result } = setup("pageA", store);
await act(async () => {
await result.current.mutateAsync();
});
expect(updateTitleMock).toHaveBeenCalledWith({
pageId: "pageA",
title: "Generated Title",
});
expect(updatePageDataMock).toHaveBeenCalledWith(PAGE_A);
expect(titleEditor.commands.setContent).toHaveBeenCalledWith(
"Generated Title",
);
expect(localEmitMock).toHaveBeenCalled();
expect(emitMock).toHaveBeenCalled();
expect(notificationsShowMock).toHaveBeenCalledWith(
expect.objectContaining({ message: "Title generated" }),
);
});
it("does NOT write the visible title field when the user navigated away during generation", async () => {
const store = createStore();
const titleEditor = makeTitleEditor(); // persistent across navigation
store.set(pageEditorAtom as never, makePageEditor("pageA"));
store.set(titleEditorAtom as never, titleEditor);
// Control when generation resolves so we can navigate mid-flight.
let resolveTitle!: (t: string) => void;
generatePageTitleMock.mockReturnValue(
new Promise<string>((res) => {
resolveTitle = res;
}),
);
updateTitleMock.mockResolvedValue(PAGE_A);
const { result } = setup("pageA", store);
let pending!: Promise<void>;
act(() => {
pending = result.current.mutateAsync();
});
// User navigates to page B: the live page editor now belongs to pageB.
act(() => {
store.set(pageEditorAtom as never, makePageEditor("pageB"));
});
await act(async () => {
resolveTitle("Generated Title");
await pending;
});
// DB write is still correct (keyed by the captured pageId)...
expect(updateTitleMock).toHaveBeenCalledWith({
pageId: "pageA",
title: "Generated Title",
});
// ...but we must NOT stamp page A's title into page B's visible field.
expect(titleEditor.commands.setContent).not.toHaveBeenCalled();
// The change is still broadcast to other clients.
expect(emitMock).toHaveBeenCalled();
});
it("does NOT write the visible title field when the title editor is focused", async () => {
const store = createStore();
const titleEditor = makeTitleEditor();
store.set(pageEditorAtom as never, makePageEditor("pageA"));
store.set(titleEditorAtom as never, titleEditor);
// Resolve generation under our control so we can mark the live title editor
// as focused before the post-generation write runs.
let resolveTitle!: (t: string) => void;
generatePageTitleMock.mockReturnValue(
new Promise<string>((res) => {
resolveTitle = res;
}),
);
updateTitleMock.mockResolvedValue(PAGE_A);
const { result } = setup("pageA", store);
let pending!: Promise<void>;
act(() => {
pending = result.current.mutateAsync();
});
// The user clicked into the title field while the model ran — overwriting it
// now would clobber what they are actively typing.
act(() => {
(titleEditor as { isFocused: boolean }).isFocused = true;
});
await act(async () => {
resolveTitle("Generated Title");
await pending;
});
// The DB write still persists the value...
expect(updateTitleMock).toHaveBeenCalledWith({
pageId: "pageA",
title: "Generated Title",
});
expect(updatePageDataMock).toHaveBeenCalledWith(PAGE_A);
// ...but the visible field is left alone while it is focused.
expect(titleEditor.commands.setContent).not.toHaveBeenCalled();
// The change is still broadcast to other clients.
expect(localEmitMock).toHaveBeenCalled();
expect(emitMock).toHaveBeenCalled();
});
it("bails before calling the model when the page editor is destroyed", async () => {
const store = createStore();
const pageEditor = makePageEditor("pageA");
(pageEditor as { isDestroyed: boolean }).isDestroyed = true;
store.set(pageEditorAtom as never, pageEditor);
store.set(titleEditorAtom as never, makeTitleEditor());
const { result } = setup("pageA", store);
await act(async () => {
await result.current.mutateAsync();
});
expect(generatePageTitleMock).not.toHaveBeenCalled();
expect(updateTitleMock).not.toHaveBeenCalled();
});
it.each([
[403, "AI title generation is disabled"],
[503, "AI is not configured"],
[429, "Too many requests, please try again later"],
[500, "Failed to generate title"],
])("maps HTTP %s onError to a friendly message", async (status, message) => {
const store = createStore();
store.set(pageEditorAtom as never, makePageEditor("pageA"));
store.set(titleEditorAtom as never, makeTitleEditor());
generatePageTitleMock.mockRejectedValue({ response: { status } });
const { result } = setup("pageA", store);
await act(async () => {
await expect(result.current.mutateAsync()).rejects.toBeTruthy();
});
expect(notificationsShowMock).toHaveBeenCalledWith(
expect.objectContaining({ message, color: "red" }),
);
});
});

View File

@@ -0,0 +1,134 @@
import { useRef } from "react";
import { useMutation } from "@tanstack/react-query";
import { useAtomValue } from "jotai";
import { notifications } from "@mantine/notifications";
import { useTranslation } from "react-i18next";
import { htmlToMarkdown } from "@docmost/editor-ext";
import {
pageEditorAtom,
titleEditorAtom,
} from "@/features/editor/atoms/editor-atoms.ts";
import {
updatePageData,
useUpdateTitlePageMutation,
} from "@/features/page/queries/page-query.ts";
import { generatePageTitle } from "@/features/ai-chat/services/ai-chat-service.ts";
import { useQueryEmit } from "@/features/websocket/use-query-emit.ts";
import { UpdateEvent } from "@/features/websocket/types";
import localEmitter from "@/lib/local-emitter.ts";
// Maximum length we send to the model. The server truncates again; this is a
// cheap client-side bound so we never ship a huge body over the wire.
const MAX_CONTENT_CHARS = 20000;
/**
* Generate a title for the given page from the LIVE editor content (#199),
* including unsaved edits, then apply it IMMEDIATELY (per product decision). The
* server endpoint only summarizes the supplied markdown — it never writes the
* page; the actual title write goes through the existing /pages/update mutation
* (which enforces edit permission), and is mirrored to the title field + other
* clients exactly like TitleEditor.saveTitle. Returns a mutation-like API so the
* button can show a loading state via `isPending`.
*/
export function useGeneratePageTitle(pageId: string) {
const { t } = useTranslation();
const pageEditor = useAtomValue(pageEditorAtom);
const titleEditor = useAtomValue(titleEditorAtom);
const { mutateAsync: updateTitle } = useUpdateTitlePageMutation();
const emit = useQueryEmit();
// The page/title editors come from GLOBAL atoms that re-point when the user
// navigates to another page. The mutation below awaits the model for 1-3s, and
// its closure captures the editors from the render that started it. Keep a live
// reference so the post-generation write targets whatever page is on screen
// *now*, not the page the generation was started from.
const editorsRef = useRef({ pageEditor, titleEditor });
editorsRef.current = { pageEditor, titleEditor };
return useMutation<void, Error, void>({
mutationFn: async () => {
if (!pageEditor || pageEditor.isDestroyed) return;
const markdown = htmlToMarkdown(pageEditor.getHTML()).trim();
if (!markdown) {
notifications.show({ message: t("The note is empty"), color: "yellow" });
return;
}
const title = (
await generatePageTitle(markdown.slice(0, MAX_CONTENT_CHARS))
).trim();
if (!title) {
// The model returned nothing usable — keep the existing title untouched.
notifications.show({
message: t("Could not generate a title"),
color: "yellow",
});
return;
}
const page = await updateTitle({ pageId, title }); // POST /pages/update
updatePageData(page); // refresh the react-query cache
// Reflect the new title in the field immediately. The button lives in the
// byline, so the title editor is not focused — setContent is safe and stays
// undoable through its History extension (Ctrl/Cmd+Z reverts the change).
//
// Guard against navigation during generation: if the user switched pages
// while the model ran, the (persistent) title editor now shows ANOTHER
// page, so writing here would drop page A's title into page B's visible
// field. page-editor.tsx stamps the live page editor with its pageId
// (`editor.storage.pageId`), mirroring TitleEditor's `activePageId !==
// pageId` guard — bail the visible write unless that live editor still
// belongs to the page this title was generated for. The DB write above is
// already correct (keyed by the captured `pageId`), and the broadcast below
// still propagates page A's change to other clients.
const livePageEditor = editorsRef.current.pageEditor;
const liveTitleEditor = editorsRef.current.titleEditor;
// `storage.pageId` is stamped untyped in page-editor.tsx's onCreate.
const livePageId = (livePageEditor?.storage as { pageId?: string })
?.pageId;
const stillOnPage = livePageId === pageId;
if (
stillOnPage &&
liveTitleEditor &&
!liveTitleEditor.isDestroyed &&
!liveTitleEditor.isFocused
) {
liveTitleEditor.commands.setContent(page.title);
}
// Broadcast to other clients, mirroring TitleEditor.saveTitle's event shape.
const event: UpdateEvent = {
operation: "updateOne",
spaceId: page.spaceId,
entity: ["pages"],
id: page.id,
payload: {
title: page.title,
slugId: page.slugId,
parentPageId: page.parentPageId,
icon: page.icon,
},
};
localEmitter.emit("message", event);
emit(event);
notifications.show({ message: t("Title generated") });
},
onError: (err) => {
// Map known HTTP statuses to friendly messages, falling back to generic.
const status = (err as { response?: { status?: number } })?.response
?.status;
const message =
status === 403
? t("AI title generation is disabled")
: status === 503
? t("AI is not configured")
: status === 429
? t("Too many requests, please try again later")
: t("Failed to generate title");
notifications.show({ message, color: "red" });
},
});
}

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

@@ -32,6 +32,7 @@ import { AiTranscriptionService } from './ai-transcription.service';
import {
ChatIdDto,
ExportChatDto,
GeneratePageTitleDto,
GetChatMessagesDto,
RenameChatDto,
} from './dto/ai-chat.dto';
@@ -316,6 +317,43 @@ export class AiChatController {
return { text };
}
/**
* Generate a page title from supplied note content (#199). One-shot,
* non-streaming. Gated by the workspace AI flag (reusing settings.ai.generative,
* the same flag that gates the on-page generative AI menu); returns { title }.
* The endpoint NEVER writes the page — the client applies the title via the
* existing /pages/update route (which enforces edit permission), so access
* checks are not duplicated here. Throttled per user via AI_CHAT_THROTTLER.
*/
@HttpCode(HttpStatus.OK)
@UseGuards(JwtAuthGuard, UserThrottlerGuard)
@Throttle({ [AI_CHAT_THROTTLER]: { limit: 20, ttl: 60000 } })
@Post('generate-page-title')
async generatePageTitle(
@Body() dto: GeneratePageTitleDto,
@AuthWorkspace() workspace: Workspace,
): Promise<{ title: string }> {
const settings = (workspace.settings ?? {}) as {
ai?: { generative?: boolean };
};
if (settings.ai?.generative !== true) {
throw new ForbiddenException('AI title generation is disabled');
}
try {
const title = await this.aiChatService.generatePageTitle(
workspace.id,
dto.content,
);
return { title };
} catch (err) {
// Preserve meaningful HTTP errors (e.g. AiNotConfiguredException -> 503).
if (err instanceof HttpException) throw err;
// Surface the real provider/transport reason instead of an opaque 500.
this.logger.error('AI title generation failed', err as Error);
throw new ServiceUnavailableException(describeProviderError(err));
}
}
/**
* Ensure the chat exists, belongs to this workspace, AND was created by the
* requesting user (per-user isolation). Throws ForbiddenException otherwise.

View File

@@ -0,0 +1,122 @@
import {
ForbiddenException,
HttpException,
ServiceUnavailableException,
} from '@nestjs/common';
import { AiChatController } from './ai-chat.controller';
import { cleanGeneratedTitle } from './ai-chat.service';
import type { Workspace } from '@docmost/db/types/entity.types';
/**
* Pure post-processing of a model-generated title (#199): trims, strips a single
* pair of surrounding quotes, drops a trailing period, and hard-caps the length.
*/
describe('cleanGeneratedTitle', () => {
it('trims surrounding whitespace', () => {
expect(cleanGeneratedTitle(' Hello world ')).toBe('Hello world');
});
it('strips a single pair of surrounding double quotes', () => {
expect(cleanGeneratedTitle('"My note"')).toBe('My note');
});
it('strips surrounding single quotes', () => {
expect(cleanGeneratedTitle("'My note'")).toBe('My note');
});
it('drops a trailing period', () => {
expect(cleanGeneratedTitle('A complete sentence.')).toBe(
'A complete sentence',
);
});
it('caps the result at 255 characters (the page-title column bound)', () => {
expect(cleanGeneratedTitle('x'.repeat(400))).toHaveLength(255);
});
it('returns an empty string for blank/garbage input', () => {
expect(cleanGeneratedTitle(' ')).toBe('');
expect(cleanGeneratedTitle('""')).toBe('');
});
});
/**
* Wiring spec for the #199 `POST /ai-chat/generate-page-title` endpoint. It must:
* gate on settings.ai.generative (403 when off), delegate to the service when on,
* rethrow HttpExceptions verbatim (e.g. AiNotConfiguredException -> 503), and map
* any other provider/transport fault to a 503. Exercised by instantiating the
* controller with hand-rolled mocks — no Nest graph, no DB.
*/
describe('AiChatController.generatePageTitle', () => {
const enabledWorkspace = {
id: 'ws1',
settings: { ai: { generative: true } },
} as unknown as Workspace;
function makeController(generate: jest.Mock) {
const aiChatService = { generatePageTitle: generate };
const controller = new AiChatController(
aiChatService as never,
{} as never,
{} as never,
{} as never,
);
return { controller, aiChatService };
}
it('forbids when the generative AI flag is off', async () => {
const generate = jest.fn();
const { controller } = makeController(generate);
const disabled = { id: 'ws1', settings: {} } as unknown as Workspace;
await expect(
controller.generatePageTitle({ content: 'body' }, disabled),
).rejects.toBeInstanceOf(ForbiddenException);
expect(generate).not.toHaveBeenCalled();
});
it('forbids when settings.ai.generative is anything but exactly true', async () => {
const generate = jest.fn();
const { controller } = makeController(generate);
const ws = {
id: 'ws1',
settings: { ai: { generative: 'yes' } },
} as unknown as Workspace;
await expect(
controller.generatePageTitle({ content: 'body' }, ws),
).rejects.toBeInstanceOf(ForbiddenException);
});
it('returns { title } from the service when enabled', async () => {
const generate = jest.fn().mockResolvedValue('Generated Title');
const { controller } = makeController(generate);
const res = await controller.generatePageTitle(
{ content: 'some markdown body' },
enabledWorkspace,
);
expect(generate).toHaveBeenCalledWith('ws1', 'some markdown body');
expect(res).toEqual({ title: 'Generated Title' });
});
it('rethrows an HttpException from the service verbatim (e.g. 503 not configured)', async () => {
const notConfigured = new ServiceUnavailableException('AI not configured');
const generate = jest.fn().mockRejectedValue(notConfigured);
const { controller } = makeController(generate);
await expect(
controller.generatePageTitle({ content: 'body' }, enabledWorkspace),
).rejects.toBe(notConfigured);
});
it('maps a non-HTTP provider error to a 503', async () => {
const generate = jest.fn().mockRejectedValue(new Error('socket hang up'));
const { controller } = makeController(generate);
// Silence the expected error log.
jest
.spyOn((controller as unknown as { logger: { error: () => void } }).logger, 'error')
.mockImplementation(() => undefined);
const err = await controller
.generatePageTitle({ content: 'body' }, enabledWorkspace)
.catch((e) => e);
expect(err).toBeInstanceOf(ServiceUnavailableException);
expect(err).toBeInstanceOf(HttpException);
});
});

View File

@@ -75,6 +75,18 @@ export function prepareAgentStep(
export { MAX_AGENT_STEPS, FINAL_STEP_INSTRUCTION };
// Pure, unit-testable post-processing for a model-generated title (#199): trim
// whitespace, strip a single pair of surrounding quotes the model often adds,
// drop a trailing period, and hard-cap the length to the page-title column.
export function cleanGeneratedTitle(text: string): string {
return text
.trim()
.replace(/^["']|["']$/g, '')
.replace(/\.+$/, '')
.trim()
.slice(0, 255);
}
/**
* Payload accepted from the client `useChat` POST body. We do NOT bind a strict
* DTO (the global ValidationPipe whitelist would strip the useChat-specific
@@ -793,6 +805,27 @@ export class AiChatService implements OnModuleInit {
}
}
/**
* One-shot page-title generation from a note's content (#199). No tools, no
* streaming — mirrors generateTitle() but for an arbitrary note body supplied
* by the client, and RETURNS the title instead of writing it (the client
* applies it via the existing /pages/update route, which enforces edit
* permission). The content is truncated to keep the prompt cheap and within
* context limits. Throws AiNotConfiguredException (503) if AI is unconfigured.
*/
async generatePageTitle(workspaceId: string, content: string): Promise<string> {
const model = await this.ai.getChatModel(workspaceId);
const { text } = await generateText({
model,
system:
'You generate a single concise, descriptive title for a note based on ' +
'its content. Reply with the title only — at most 8 words, no quotes, ' +
'no trailing punctuation, written in the same language as the note.',
prompt: content.slice(0, 8000),
});
return cleanGeneratedTitle(text);
}
/**
* Cheap, non-blocking title generation from the first user message. Uses
* generateText (async) and writes the result back onto the chat row. Any

View File

@@ -17,6 +17,16 @@ export class RenameChatDto {
title: string;
}
/** One-shot page-title generation from note content (#199). */
export class GeneratePageTitleDto {
// Note body as markdown/plain text. Capped to bound the prompt cost and
// reject abusive payloads; the service truncates again before the model call.
@IsString()
@MinLength(1)
@MaxLength(20000)
content: string;
}
/** Optional chat id for listing messages of a specific chat. */
export class GetChatMessagesDto {
@IsString()

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

@@ -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

@@ -4,7 +4,7 @@
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)sx?$": "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)(@|/))"