Skip to content

Build your personal knowledge base with Trilium Notes

feat(share): complete attribute names from the notes a visitor can read

Elian Doran19d422f68a9e
diff --git a/apps/client/src/services/froca-interface.ts b/apps/client/src/services/froca-interface.ts
index edb4c10e0e..aeb3bfc529 100644
--- a/apps/client/src/services/froca-interface.ts
+++ b/apps/client/src/services/froca-interface.ts
@@ -53,6 +53,8 @@ export interface FrocaSource {
searchInSubtree(query: string, ancestorNoteId: string): Promise<SearchWithTokensResponse>;
/** What is wrong with the search string, read without running it. */
lintSearch(searchString: string): Promise<SearchLintResponse>;
+ /** The names of the attributes of `type` that contain `query`, to complete one with. */
+ getAttributeNames(type: "label" | "relation", query: string): Promise<string[]>;
/** The notes and the links of the note map of `mapRootNoteId`, as a tree or as its relations. */
getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters): Promise<NoteMapPostResponse>;
/** The relations the relation map note `relationMapNoteId` draws between the notes `noteIds`. */
@@ -84,6 +86,7 @@ export interface Froca {
searchNoteIds(query: string, ancestorNoteId: string): Promise<string[]>;
searchInSubtree(query: string, ancestorNoteId: string): Promise<SearchWithTokensResponse>;
lintSearch(searchString: string): Promise<SearchLintResponse>;
+ getAttributeNames(type: "label" | "relation", query: string): Promise<string[]>;
getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters): Promise<NoteMapPostResponse>;
getRelationMap(relationMapNoteId: string, noteIds: string[]): Promise<RelationMapPostResponse>;
getScriptBundle(noteId: string): Promise<Bundle | undefined>;
diff --git a/apps/client/src/services/froca.ts b/apps/client/src/services/froca.ts
index 0303e1b122..8b3cd13be1 100644
--- a/apps/client/src/services/froca.ts
+++ b/apps/client/src/services/froca.ts
@@ -415,6 +415,10 @@ class FrocaImpl implements Froca {
return this.source.lintSearch(searchString);
}
+ getAttributeNames(type: "label" | "relation", query: string) {
+ return this.source.getAttributeNames(type, query);
+ }
+
getNoteMap(mapRootNoteId: string, mapType: "tree" | "link", filters: NoteMapFilters) {
return this.source.getNoteMap(mapRootNoteId, mapType, filters);
}
@@ -476,6 +480,8 @@ const SERVER_SOURCE: FrocaSource = {
`search?searchString=${encodeURIComponent(query)}`
+ `&ancestorNoteId=${encodeURIComponent(ancestorNoteId)}&includeTokens=true`),
lintSearch: (searchString) => server.post<SearchLintResponse>("search/lint", { searchString }),
+ getAttributeNames: (type, query) =>
+ server.get<string[]>(`attribute-names/?type=${type}&query=${encodeURIComponent(query)}`),
getNoteMap: (mapRootNoteId, mapType, filters) =>
server.post<NoteMapPostResponse>(`note-map/${mapRootNoteId}/${mapType}`, filters),
getRelationMap: (relationMapNoteId, noteIds) =>
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
index e26e92cde5..597ebbca2d 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
+++ b/apps/client/src/widgets/attribute_widgets/attribute_detail.tsx
@@ -859,7 +859,7 @@ export const DEFINITION_TYPES: { value: string; title: string; icon: string; sta
];
export function fetchAttributeNames(type: "label" | "relation", query: string) {
- return server.get<string[]>(`attribute-names/?type=${type}&query=${encodeURIComponent(query)}`);
+ return froca.getAttributeNames(type, query);
}
/**
diff --git a/packages/share-theme/src/content/share_froca_source.ts b/packages/share-theme/src/content/share_froca_source.ts
index 3809df8edb..69fe7a28f9 100644
--- a/packages/share-theme/src/content/share_froca_source.ts
+++ b/packages/share-theme/src/content/share_froca_source.ts
@@ -34,6 +34,8 @@ export function createShareFrocaSource(links: Record<string, string>): FrocaSour
const params = new URLSearchParams({ searchString: query, ancestorNoteId });
return getJson(`api/search?${params}`);
},
+ getAttributeNames: (type, query) =>
+ getJson(`api/attribute-names?${new URLSearchParams({ type, query })}`),
lintSearch: (searchString) => getJson(`api/search/lint?${new URLSearchParams({ searchString })}`),
getNoteMap: (mapRootNoteId, mapType, { excludeRelations, includeRelations }) => {
const params = new URLSearchParams([
diff --git a/packages/trilium-core/src/services/attributes.spec.ts b/packages/trilium-core/src/services/attributes.spec.ts
index 2a11dac646..7bb99ac382 100644
--- a/packages/trilium-core/src/services/attributes.spec.ts
+++ b/packages/trilium-core/src/services/attributes.spec.ts
@@ -185,6 +185,18 @@ describe("attributes service", () => {
});
});
+ describe("completeAttributeNames", () => {
+ it("adds the matching built-in names, drops the internal links and lists prefix matches first", () => {
+ expect(attributeService.completeAttributeNames([ "myShareNote", "shareAlias" ], "label", "SHARE"))
+ .toEqual(expect.arrayContaining([ "shareAlias", "shareRoot", "myShareNote" ]));
+ const names = attributeService.completeAttributeNames([ "myShareNote" ], "label", "share");
+ expect(names.indexOf("myShareNote")).toBe(names.length - 1);
+ expect(names.filter((name) => name === "shareAlias")).toHaveLength(1);
+ expect(attributeService.completeAttributeNames([ "internalLink", "zzLink" ], "relation", "zzlink"))
+ .toEqual([ "zzLink" ]);
+ });
+ });
+
describe("getAttributeNames (real DB + built-ins)", () => {
it("returns built-in names matching the search, sorted with prefix matches first", () => {
const names = getAttributeNames("label", "share");
diff --git a/packages/trilium-core/src/services/attributes.ts b/packages/trilium-core/src/services/attributes.ts
index 4cd2d20ffb..41b16363ba 100644
--- a/packages/trilium-core/src/services/attributes.ts
+++ b/packages/trilium-core/src/services/attributes.ts
@@ -60,17 +60,27 @@ function createAttribute(attribute: AttributeRow) {
}
function getAttributeNames(type: string, nameLike: string) {
- nameLike = nameLike.toLowerCase();
-
- let names = getSql().getColumn<string>(
+ const names = getSql().getColumn<string>(
/*sql*/`SELECT DISTINCT name
FROM attributes
WHERE isDeleted = 0
AND type = ?
AND name LIKE ?`,
- [type, `%${nameLike}%`]
+ [type, `%${nameLike.toLowerCase()}%`]
);
+ return completeAttributeNames(names, type, nameLike);
+}
+
+/**
+ * Adds to `names`, the attribute names of `type` matching `nameLike` found in notes, the built-in
+ * ones that match, leaves out the names of the links Trilium keeps itself, and lists the names
+ * starting with `nameLike` first.
+ */
+function completeAttributeNames(foundNames: string[], type: string, nameLike: string) {
+ nameLike = nameLike.toLowerCase();
+ let names = [ ...foundNames ];
+
for (const attr of BUILTIN_ATTRIBUTES) {
if (attr.type === type && attr.name.toLowerCase().includes(nameLike) && !names.includes(attr.name)) {
names.push(attr.name);
@@ -108,6 +118,7 @@ export default {
createRelation,
createAttribute,
getAttributeNames,
+ completeAttributeNames,
isAttributeType,
isAttributeDangerous
};
diff --git a/packages/trilium-core/src/share/handlers.spec.ts b/packages/trilium-core/src/share/handlers.spec.ts
index 9484074a6b..087daec744 100644
--- a/packages/trilium-core/src/share/handlers.spec.ts
+++ b/packages/trilium-core/src/share/handlers.spec.ts
@@ -5,6 +5,7 @@ import { getCrypto } from "../services/encryption/crypto.js";
import SearchResult from "../services/search/search_result.js";
import searchService from "../services/search/services/search.js";
import { encodeBase64, encodeUtf8 } from "../services/utils/binary.js";
+import { buildNote } from "../test/becca_easy_mocking.js";
import { buildShareNote } from "../test/shaca_mocking.js";
import {
getShareRoute, getShareRoutes, handleShareRequest, type ShareReply, type ShareRequest
@@ -515,6 +516,32 @@ describe("share handlers", () => {
expect(filter({ searchString: "seen", ancestorNoteId: "missing" }).status).toBe(404);
});
+ it("completes attribute names only from the notes the caller can read", () => {
+ buildShareTree([
+ { "id": "open", "title": "Open", "content": "", "#projectPhase": "", "~projectOwner": "open" },
+ { "id": "guarded", "title": "Guarded", "content": "", "#projectBudget": "",
+ "#shareCredentials": "root:hunter2" },
+ { "id": "secret", "title": "Secret", "content": "", "#projectSecret": "", "isProtected": true }
+ ]);
+ const names = (query: ShareRequest["query"], authorization?: string) => {
+ const reply = request("/share/api/attribute-names",
+ { query, headers: authorization ? { authorization } : {} });
+ return reply.status === 200 ? JSON.parse(String(reply.body)) as string[] : reply.status;
+ };
+
+ // A note the share does not hold names nothing, whatever the database holds.
+ buildNote({ id: "unshared", title: "Unshared", "#projectPayroll": "" });
+ expect(names({ type: "label", query: "PROJECT" })).toEqual([ "projectPhase" ]);
+ expect(names({ type: "label", query: "project" }, `Basic ${encodeBase64("root:hunter2")}`))
+ .toEqual([ "projectBudget", "projectPhase" ]);
+ expect(names({ type: "relation", query: "project" })).toEqual([ "projectOwner" ]);
+ // The built-in names are the app's own, so a visitor is offered them too.
+ expect(names({ type: "label", query: "shareAlias" })).toEqual([ "shareAlias" ]);
+
+ expect(names({ type: "attribute", query: "project" })).toBe(400);
+ expect(names({ type: "label" })).toBe(400);
+ });
+
it("reads a search string without running it, answering its error", () => {
const lint = (query: ShareRequest["query"]) => request("/share/api/search/lint", { query });
vi.spyOn(searchService, "validateSearchQuery").mockImplementation((query) =>
diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.ts
index 080cd94b6f..e05cbb76ba 100644
--- a/packages/trilium-core/src/share/handlers.ts
+++ b/packages/trilium-core/src/share/handlers.ts
@@ -5,6 +5,7 @@ import { t } from "i18next";
import becca from "../becca/becca.js";
import { buildLinkMap, buildTreeMap } from "../routes/api/note_map.js";
import { buildRelationMap } from "../routes/api/relation-map.js";
+import attributeService from "../services/attributes.js";
import { getCrypto } from "../services/encryption/crypto.js";
import scriptService from "../services/script.js";
import searchService from "../services/search/services/search.js";
@@ -97,6 +98,7 @@ const HANDLERS: Record<ShareRoutePath, (req: ShareRequest) => ShareReply> = {
"/share/api/tree": loadTree,
"/share/api/search/lint": lintSearch,
"/share/api/search": searchInSubtree,
+ "/share/api/attribute-names": getAttributeNames,
"/share/api/note-map/:noteId/:mapType": getNoteMap,
"/share/api/relation-map/:noteId": getRelationMap,
"/share/api/script/bundle/:noteId": getScriptBundle,
@@ -412,6 +414,29 @@ function searchInSubtree(req: ShareRequest): ShareReply {
});
}
+/**
+ * Completes an attribute name for the search editor from the attributes of the notes a visitor can
+ * read, and the built-in names. The names in the rest of the database are none of a visitor's
+ * business.
+ */
+function getAttributeNames(req: ShareRequest): ShareReply {
+ const { type, query } = req.query;
+ if ((type !== "label" && type !== "relation") || typeof query !== "string") {
+ return jsonReply(400, { message: "'type' and 'query' parameters are mandatory." });
+ }
+
+ const nameLike = query.toLowerCase();
+ const names = new Set<string>();
+ for (const attribute of Object.values(shaca.attributes)) {
+ const { note } = attribute;
+ if (attribute.type === type && attribute.name.toLowerCase().includes(nameLike)
+ && !note.isProtected && hasCredentialAccess(note, req)) {
+ names.add(attribute.name);
+ }
+ }
+ return jsonReply(200, attributeService.completeAttributeNames([ ...names ], type, query));
+}
+
/** Reads a search string without running it, for the search editor's own checks. */
function lintSearch(req: ShareRequest): ShareReply {
const { searchString } = req.query;
diff --git a/packages/trilium-core/src/share/route_paths.ts b/packages/trilium-core/src/share/route_paths.ts
index 8ca1b4c9ef..6549c7ef3e 100644
--- a/packages/trilium-core/src/share/route_paths.ts
+++ b/packages/trilium-core/src/share/route_paths.ts
@@ -22,6 +22,7 @@ export const SHARE_ROUTE_PATHS = [
"/share/api/tree",
"/share/api/search/lint",
"/share/api/search",
+ "/share/api/attribute-names",
"/share/api/note-map/:noteId/:mapType",
"/share/api/relation-map/:noteId",
"/share/api/script/bundle/:noteId",