Skip to content

Build your personal knowledge base with Trilium Notes

fix(share): open any note an app view names on its shared page

Elian Doranf5312a99c8b0
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
index c1d8f202cb..ab3688138b 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Sharing.html
@@ -319,7 +319,8 @@ for (const attr of parentNote.attributes) {
<p>Shared notes typically have URLs like <code>http://domain.tld/share/knvU8aJy4dJ7</code>,
where the last part is the note's ID. You can make these URLs more user-friendly
by adding the <code>#shareAlias</code> label to individual notes (e.g., <code>#shareAlias=highlighting</code>).
- This will change the URL to <code>http://domain.tld/share/highlighting</code>.</p>
+ This will change the URL to <code>http://domain.tld/share/highlighting</code>.
+ The URL with the note's ID keeps working and redirects to the alias.</p>
<p><strong>Important</strong>:</p>
<ol>
<li>Ensure that aliases are unique.</li>
@@ -360,7 +361,8 @@ for (const attr of parentNote.attributes) {
target URL as its value (e.g. <code>#shareExternalLink="https://example.com"</code>).</p>
<p>Any link pointing to this note will then redirect to the external website
and open in a new browser tab, instead of opening the note's own shared
- page. This applies to:</p>
+ page. Opening the note's shared URL by its ID also redirects to the external
+ website. This applies to:</p>
<ul>
<li>the listing produced by the <code>#shareIndex</code> label;</li>
<li>the navigation tree of the shared site;</li>
diff --git a/docs/User Guide/User Guide/Advanced Usage/Sharing.md b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
index 15cdfae797..693bd95a3b 100644
--- a/docs/User Guide/User Guide/Advanced Usage/Sharing.md
+++ b/docs/User Guide/User Guide/Advanced Usage/Sharing.md
@@ -187,7 +187,7 @@ To completely redesign the share, it is possible to create or use an existing [c
### Creating human-readable URL aliases
-Shared notes typically have URLs like `http://domain.tld/share/knvU8aJy4dJ7`, where the last part is the note's ID. You can make these URLs more user-friendly by adding the `#shareAlias` label to individual notes (e.g., `#shareAlias=highlighting`). This will change the URL to `http://domain.tld/share/highlighting`.
+Shared notes typically have URLs like `http://domain.tld/share/knvU8aJy4dJ7`, where the last part is the note's ID. You can make these URLs more user-friendly by adding the `#shareAlias` label to individual notes (e.g., `#shareAlias=highlighting`). This will change the URL to `http://domain.tld/share/highlighting`. The URL with the note's ID keeps working and redirects to the alias.
**Important**:
@@ -219,7 +219,7 @@ To do so, create a shared text note and apply the `shareIndex` label. When viewe
Sometimes it's useful to include a link to an external website alongside your shared notes — for example in the shared navigation or in an index. To do so, add the `#shareExternalLink` label to a note, with the target URL as its value (e.g. `#shareExternalLink="https://example.com"`).
-Any link pointing to this note will then redirect to the external website and open in a new browser tab, instead of opening the note's own shared page. This applies to:
+Any link pointing to this note will then redirect to the external website and open in a new browser tab, instead of opening the note's own shared page. Opening the note's shared URL by its ID also redirects to the external website. This applies to:
* the listing produced by the `#shareIndex` label;
* the navigation tree of the shared site;
diff --git a/packages/share-theme/src/content/app_host.tsx b/packages/share-theme/src/content/app_host.tsx
index 154a6797a6..82d87f7ee2 100644
--- a/packages/share-theme/src/content/app_host.tsx
+++ b/packages/share-theme/src/content/app_host.tsx
@@ -97,9 +97,10 @@ function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {
const staticSource = payload.exportBasePath === undefined
? undefined : createStaticFrocaSource(links, payload.exportBasePath);
- froca.setSource(withRootAnchors(staticSource ?? createShareFrocaSource(links)));
+ const source = staticSource ?? createShareFrocaSource(links);
+ froca.setSource(withRootAnchors(source));
setImageUrlResolver(staticSource?.getImageUrl);
- linkContextMenu.setShareLinkResolver((linkedNoteId) => links[linkedNoteId] ?? null);
+ linkContextMenu.setShareLinkResolver(source.getNoteLink);
froca.addResp({
...anchorAtRoot(rows),
attributes: [ ...rows.attributes, {
@@ -122,12 +123,12 @@ function loadPayload(noteId: string, payload: AppPayload): HostedApp | null {
note,
parentNoteId: payload.parentNoteId,
openNote: (openedNoteId) => {
- const link = links[openedNoteId];
+ const link = source.getNoteLink(openedNoteId);
if (link) {
window.location.href = link;
}
},
- hasLink: (linkedNoteId) => !!links[linkedNoteId],
+ hasLink: (linkedNoteId) => source.getNoteLink(linkedNoteId) !== null,
staticSource
};
}
@@ -165,7 +166,8 @@ function anchorAtRoot<T extends SubtreeResponse>(rows: T): T {
/**
* Opens the shared page of the note a clicked link into the note tree names, such as a table's
- * `.reference-link[data-href="#root/…"]` cell. A link to a note the share does not hold is left alone.
+ * `.reference-link[data-href="#root/…"]` cell. On a page of the static export, a link to a note the
+ * export does not hold is left alone.
*/
function openNoteLink(event: MouseEvent, app: HostedApp) {
const link = (event.target as Element | null)?.closest("[data-href], a[href^='#']");
diff --git a/packages/share-theme/src/content/share_froca_source.spec.ts b/packages/share-theme/src/content/share_froca_source.spec.ts
index 71081a9c38..30ab2d9c10 100644
--- a/packages/share-theme/src/content/share_froca_source.spec.ts
+++ b/packages/share-theme/src/content/share_froca_source.spec.ts
@@ -1,6 +1,23 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { createStaticFrocaSource } from "./share_froca_source.js";
+import { createShareFrocaSource, createStaticFrocaSource } from "./share_froca_source.js";
+
+describe("createShareFrocaSource", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("links a note to the page of its ID until a loaded row names its own link", async () => {
+ stubFiles({ "api/tree?noteIds=aliased": { notes: [], branches: [], attributes: [], links: { aliased: "./nice-name" } } });
+ const source = createShareFrocaSource({ shown: "./shown-alias" });
+
+ expect(source.getNoteLink("shown")).toBe("./shown-alias");
+ expect(source.getNoteLink("aliased")).toBe("./aliased");
+ expect(source.getNoteLink("a b")).toBe("./a%20b");
+ await source.loadNotes([ "aliased" ]);
+ expect(source.getNoteLink("aliased")).toBe("./nice-name");
+ });
+});
describe("createStaticFrocaSource", () => {
afterEach(() => {
@@ -23,6 +40,8 @@ describe("createStaticFrocaSource", () => {
notes: ROWS.notes, branches: ROWS.branches, attributes: ROWS.attributes
});
expect(links).toEqual({ siteRoot: "../", event: "../pages/event.html" });
+ expect(source.getNoteLink("event")).toBe("../pages/event.html");
+ expect(source.getNoteLink("notExported")).toBeNull();
expect(await source.getAttachments("canvas")).toEqual([ SVG ]);
expect(await source.getAttachments("event")).toEqual([]);
expect(await source.getSiblingAttachments("svg")).toEqual([ SVG ]);
diff --git a/packages/share-theme/src/content/share_froca_source.ts b/packages/share-theme/src/content/share_froca_source.ts
index 3915c792e1..97c576fa88 100644
--- a/packages/share-theme/src/content/share_froca_source.ts
+++ b/packages/share-theme/src/content/share_froca_source.ts
@@ -9,12 +9,20 @@ export interface ShareFrocaRows extends SubtreeResponse {
links: Record<string, string>;
}
+/** A source of froca's notes that also links each note to its page. */
+export interface ShareFrocaSource extends FrocaSource {
+ /** The URL of a note's page, relative to the page, or `null` for a note without one. */
+ getNoteLink(noteId: string): string | null;
+}
+
/**
* Reads the notes, attachments and blobs froca lacks from the share's API, relative to the page,
- * and records the share link of each note it loads in `links`.
+ * and records the share link of each note it loads in `links`. A note no row has linked yet links
+ * to `./<noteId>`, which the share redirects to the note's own link.
*/
-export function createShareFrocaSource(links: Record<string, string>): FrocaSource {
+export function createShareFrocaSource(links: Record<string, string>): ShareFrocaSource {
return {
+ getNoteLink: (noteId) => links[noteId] ?? `./${encodeURIComponent(noteId)}`,
loadNotes: async (noteIds) => {
const query = noteIds.map(encodeURIComponent).join(",");
const rows = await getJson<ShareFrocaRows>(`api/tree?noteIds=${query}`);
@@ -67,7 +75,7 @@ interface StaticShareRows extends ShareFrocaRows {
}
/** A source of froca's notes that also finds the images of the export. */
-export interface StaticFrocaSource extends FrocaSource {
+export interface StaticFrocaSource extends ShareFrocaSource {
/**
* The URL of the file of a note's image or of an image attachment, relative to the page, or
* `null` for one the export does not hold or before the source has read `rows.json`.
@@ -99,6 +107,7 @@ export function createStaticFrocaSource(
const readData = <T>(path: string) => getJson<T>(`${basePath}data/${path}`);
return {
+ getNoteLink: (noteId) => links[noteId] ?? null,
loadNotes: async () => {
const { notes, branches, attributes, links: rootLinks } = await readRows();
for (const [ noteId, link ] of Object.entries(rootLinks)) {
diff --git a/packages/trilium-core/src/share/handlers.spec.ts b/packages/trilium-core/src/share/handlers.spec.ts
index 7590d43153..6b1318691b 100644
--- a/packages/trilium-core/src/share/handlers.spec.ts
+++ b/packages/trilium-core/src/share/handlers.spec.ts
@@ -69,6 +69,27 @@ describe("share handlers", () => {
expect(raw.body).toBe("<p>Hello</p>");
});
+ it("sends a note opened by its ID to its alias or its external link", () => {
+ buildShareTree([
+ { "id": "aliasedNote", "content": "<p>Aliased</p>", "#shareAlias": "nice-name" },
+ { "id": "externalNote", "content": "", "#shareExternalLink": "https://example.com/" },
+ { "id": "lockedAlias", "content": "", "#shareAlias": "secret-name", "#shareCredentials": "root:hunter2" },
+ { id: "plainPage", content: "<p>Plain</p>" }
+ ]);
+ shaca.aliasToNote["nice-name"] = shaca.getNote("aliasedNote");
+ shaca.aliasToNote["secret-name"] = shaca.getNote("lockedAlias");
+ const page = (shareId: string, query: ShareRequest["query"] = {}) =>
+ request("/share/:shareId", { params: { shareId }, query });
+
+ expect(page("aliasedNote")).toMatchObject({ status: 302, redirect: "./nice-name" });
+ expect(page("externalNote")).toMatchObject({ status: 302, redirect: "https://example.com/" });
+ expect(page("lockedAlias")).toMatchObject({ status: 401 });
+ expect(page("lockedAlias").redirect).toBeUndefined();
+ expect(page("nice-name").status).toBe(200);
+ expect(page("plainPage").status).toBe(200);
+ expect(page("aliasedNote", { raw: "" })).toMatchObject({ status: 200, body: "<p>Aliased</p>" });
+ });
+
it("refuses a protected note's bytes on every route that streams them (GHSA-xmv9-3v98-7gq8)", () => {
buildShareTree([
{ id: "lockedUp", content: "<p>classified body</p>", isProtected: true },
diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.ts
index 44deacbf64..103e0407e6 100644
--- a/packages/trilium-core/src/share/handlers.ts
+++ b/packages/trilium-core/src/share/handlers.ts
@@ -1,4 +1,5 @@
import { isImageAttachmentRole, isSvgMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";
+import { getShareLink } from "@triliumnext/share-theme/model/page";
import ejs from "ejs";
import { t } from "i18next";
@@ -7,6 +8,7 @@ import attributeService from "../services/attributes.js";
import { getCrypto } from "../services/encryption/crypto.js";
import searchService from "../services/search/services/search.js";
import SearchContext from "../services/search/search_context.js";
+import * as sanitize from "../services/sanitizer.js";
import { decodeBase64, decodeUtf8, encodeUtf8 } from "../services/utils/binary.js";
import * as utils from "../services/utils/index.js";
import { readShareTemplate, renderNoteContent } from "./content_renderer.js";
@@ -127,8 +129,20 @@ function getShareRoot(req: ShareRequest): ShareReply {
function getShareNote(req: ShareRequest): ShareReply {
const shareId = req.params.shareId ?? "";
- const note = shaca.aliasToNote[shareId] || shaca.notes[shareId];
+ const aliasedNote = shaca.aliasToNote[shareId];
+ if (aliasedNote) {
+ return renderNote(aliasedNote, req);
+ }
+ // An app view links a note it knows only by ID to `./<noteId>`, which lands on its own link.
+ const note = shaca.notes[shareId];
+ if (note && typeof req.query.raw === "undefined") {
+ checkNoteAccess(note.noteId, req);
+ const link = getShareLink(note, sanitize.sanitizeUrl).href;
+ if (link !== `./${note.noteId}`) {
+ return { status: 302, headers: {}, redirect: link };
+ }
+ }
return renderNote(note, req);
}