Skip to content

Build your personal knowledge base with Trilium Notes

feat(onenote): detect password-protected sections and mark them with a lock icon

Elian Dorandefe014c03f1
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index 536b59c458..40f7f6594c 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -331,7 +331,9 @@
"onenote_import": {
"root-title": "OneNote import",
"failed-page-placeholder": "This page could not be imported from OneNote. Error: {{error}}",
- "failed-section-placeholder": "This section could not be imported from OneNote, so it was created empty. This often means the section is password-protected — unlock it in OneNote and import again. Error: {{error}}",
+ "failed-section-placeholder": "This section could not be imported from OneNote, so it was created empty. Error: {{error}}",
+ "protected-section-error": "This section is password-protected. Remove its password in OneNote, then import it again.",
+ "protected-section-placeholder": "This section is password-protected, so its pages could not be imported and it was created empty. To import it, open the section in OneNote, remove its password protection (right-click the section → Password Protection → Remove Password), then run the import again.",
"report": {
"row-pages": "Pages imported successfully",
"row-notebooks": "Notebooks imported",
diff --git a/apps/server/src/services/import/onenote/graph.spec.ts b/apps/server/src/services/import/onenote/graph.spec.ts
index 321b0b43e3..d8c2d107ef 100644
--- a/apps/server/src/services/import/onenote/graph.spec.ts
+++ b/apps/server/src/services/import/onenote/graph.spec.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../safe_fetch.js", () => ({ safeFetch: vi.fn() }));
import { safeFetch } from "../../safe_fetch.js";
-import { backoffDelayMs, extractGraphErrorDetail, getAccount, getPageContent, getResource, getThrottleStats, listPages, resetThrottleGate, resetThrottleStats, retryAfterMs, sanitizeGraphUrl } from "./graph.js";
+import { backoffDelayMs, ENCRYPTED_SECTION_ERROR_CODE, extractGraphErrorDetail, getAccount, getPageContent, getResource, getThrottleStats, GraphRequestError, isEncryptedSectionError, listPages, resetThrottleGate, resetThrottleStats, retryAfterMs, sanitizeGraphUrl } from "./graph.js";
const safeFetchMock = vi.mocked(safeFetch);
@@ -298,6 +298,29 @@ describe("failed Graph requests", () => {
});
});
+describe("isEncryptedSectionError", () => {
+ afterEach(() => safeFetchMock.mockReset());
+
+ it("is true only for a 403 with the encrypted-section code", () => {
+ expect(isEncryptedSectionError(new GraphRequestError("msg", 403, ENCRYPTED_SECTION_ERROR_CODE))).toBe(true);
+ // Wrong status, wrong code, or a plain error must not be mistaken for a protected section.
+ expect(isEncryptedSectionError(new GraphRequestError("msg", 404, ENCRYPTED_SECTION_ERROR_CODE))).toBe(false);
+ expect(isEncryptedSectionError(new GraphRequestError("msg", 403, "40003"))).toBe(false);
+ expect(isEncryptedSectionError(new GraphRequestError("msg", 403))).toBe(false);
+ expect(isEncryptedSectionError(new Error("HTTP 403: 20185"))).toBe(false);
+ });
+
+ it("makes a protected section detectable end to end: listPages throws a matching GraphRequestError", async () => {
+ safeFetchMock.mockResolvedValue(graphResponse(403, JSON.stringify({
+ error: { code: ENCRYPTED_SECTION_ERROR_CODE, message: "Encrypted sections are not accessible." }
+ })));
+
+ const error = await listPages(token, "sec-locked").catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(GraphRequestError);
+ expect(isEncryptedSectionError(error)).toBe(true);
+ });
+});
+
describe("sanitizeGraphUrl", () => {
it("redacts the email in a users('...') resource URL", () => {
expect(sanitizeGraphUrl("https://graph.microsoft.com/v1.0/users('[email protected]')/onenote/resources/0-abc!1-DEF!42/$value"))
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index ddeb9b71d4..6e951451bf 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -397,20 +397,52 @@ async function graphGetAll<T>(getAccessToken: AccessTokenProvider, pathOrUrl: st
return results;
}
+/**
+ * A failed Graph request, carrying the HTTP status and (when present) the Graph error code from the
+ * response body alongside the human-readable message, so callers can react to specific failures — e.g.
+ * {@link isEncryptedSectionError} — instead of parsing the message string.
+ */
+export class GraphRequestError extends Error {
+ readonly status: number;
+ /** The `error.code` from Graph's JSON error envelope, if the body was one (e.g. "20185"). */
+ readonly code?: string;
+
+ constructor(message: string, status: number, code?: string) {
+ super(message);
+ this.name = "GraphRequestError";
+ this.status = status;
+ this.code = code;
+ }
+}
+
+/**
+ * The Graph error code returned (with HTTP 403) when a section is encrypted/password-protected: its
+ * pages can't be listed or read through the API at all. Not in Microsoft's published error-code list —
+ * that only documents the write-side 10004 ("can't create a page … protected by a password") — so it
+ * was captured from a live import. See {@link isEncryptedSectionError}.
+ */
+export const ENCRYPTED_SECTION_ERROR_CODE = "20185";
+
+/** Whether an error is Graph rejecting a section because it is encrypted/password-protected. */
+export function isEncryptedSectionError(e: unknown): boolean {
+ return e instanceof GraphRequestError && e.status === 403 && e.code === ENCRYPTED_SECTION_ERROR_CODE;
+}
+
/**
* Builds the error for a failed Graph request. A bare HTTP status is not actionable when an import of
* thousands of pages fails on one of them, so the message carries the request URL plus whatever error
* code/message Graph itself returned in the response body.
*/
-async function graphRequestError(summary: string, url: string, response: Response): Promise<Error> {
+async function graphRequestError(summary: string, url: string, response: Response): Promise<GraphRequestError> {
let body = "";
try {
body = await response.text();
} catch {
// The status and URL are still worth reporting when the body cannot be read.
}
+ const { code } = parseGraphError(body);
const detail = extractGraphErrorDetail(body);
- return new Error(`${summary} (HTTP ${response.status}${detail ? `: ${detail}` : ""}) from ${sanitizeGraphUrl(url)}`);
+ return new GraphRequestError(`${summary} (HTTP ${response.status}${detail ? `: ${detail}` : ""}) from ${sanitizeGraphUrl(url)}`, response.status, code);
}
/**
@@ -428,18 +460,27 @@ export function sanitizeGraphUrl(url: string): string {
}
/**
- * Extracts "code: message" from Graph's standard JSON error envelope
- * (`{"error": {"code": "...", "message": "..."}}`), or "" when the body is not one.
+ * Parses Graph's standard JSON error envelope (`{"error": {"code": "...", "message": "..."}}`) into its
+ * code and message, or an empty object when the body is not one.
*/
-export function extractGraphErrorDetail(body: string): string {
+function parseGraphError(body: string): { code?: string; message?: string } {
try {
const parsed = JSON.parse(body) as { error?: { code?: string; message?: string } };
- return [parsed?.error?.code, parsed?.error?.message].filter(Boolean).join(": ");
+ return { code: parsed?.error?.code, message: parsed?.error?.message };
} catch {
- return "";
+ return {};
}
}
+/**
+ * Extracts "code: message" from Graph's standard JSON error envelope
+ * (`{"error": {"code": "...", "message": "..."}}`), or "" when the body is not one.
+ */
+export function extractGraphErrorDetail(body: string): string {
+ const { code, message } = parseGraphError(body);
+ return [code, message].filter(Boolean).join(": ");
+}
+
export default {
getAccount,
listNotebooks,
@@ -447,5 +488,6 @@ export default {
getPageContent,
getResource,
getThrottleStats,
- resetThrottleStats
+ resetThrottleStats,
+ isEncryptedSectionError
};
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.ts
index 8ce1e389de..f1be1d6ee4 100644
--- a/apps/server/src/services/import/onenote/importer.spec.ts
+++ b/apps/server/src/services/import/onenote/importer.spec.ts
@@ -13,7 +13,8 @@ vi.mock("./graph.js", () => ({
getPageContent: vi.fn(),
getResource: vi.fn(),
getThrottleStats: vi.fn(() => ({ requestCount: 0, waitMs: 0 })),
- resetThrottleStats: vi.fn()
+ resetThrottleStats: vi.fn(),
+ isEncryptedSectionError: vi.fn(() => false)
}
}));
@@ -198,10 +199,11 @@ describe("importSelection (real DB)", () => {
expect(content).toContain(`href="#root/${badNote?.noteId}"`);
});
- it("imports a placeholder folder for a section whose pages can't be listed, keeping order and the rest", async () => {
- // The first (locked) section's page list fails, e.g. it's encrypted/password-protected; the
+ it("imports a password-protected section as a locked placeholder with friendly guidance, keeping order and the rest", async () => {
+ // The first section is password-protected (Graph rejects its page list with 403/20185); the
// second succeeds. The locked section is ordered first to prove it doesn't abort the rest and
// that its placeholder keeps its position.
+ graphMock.isEncryptedSectionError.mockImplementation((e) => e instanceof Error && e.message.includes("20185"));
graphMock.listPages.mockImplementation(async (_token, sectionId) => {
if (sectionId === "sec-locked") {
throw new Error("Microsoft Graph request failed (HTTP 403: 20185: Encrypted sections are not accessible.)");
@@ -231,13 +233,16 @@ describe("importSelection (real DB)", () => {
// The readable section still imports: one bad section must not abort the whole import.
expect(Object.values(becca.notes).find((note) => note.title === "Readable Page")).toBeDefined();
- // The locked section becomes an empty placeholder folder: self-explaining, labeled, and keeping
- // the section id so a later retry pass can re-fetch it.
+ // The locked section becomes an empty placeholder folder: lock icon, self-explaining with the
+ // steps to fix it, labeled, and keeping the section id so a later retry pass can re-fetch it.
const lockedNote = Object.values(becca.notes).find((note) => note.title === "Locked Section");
expect(lockedNote?.hasOwnedLabel("oneNoteImportFailed")).toBe(true);
expect(lockedNote?.getOwnedLabelValue("oneNoteSectionId")).toBe("sec-locked");
- expect(lockedNote?.getContent()).toContain("could not be imported");
- expect(lockedNote?.getContent()).toContain("Encrypted sections are not accessible.");
+ expect(lockedNote?.getOwnedLabelValue("iconClass")).toBe("bx bx-lock-alt");
+ expect(lockedNote?.getContent()).toContain("password-protected");
+ expect(lockedNote?.getContent()).toContain("Remove Password");
+ // The opaque Graph error is replaced by the friendly guidance, not shown to the user.
+ expect(lockedNote?.getContent()).not.toContain("20185");
expect(lockedNote?.getChildNotes()).toHaveLength(0);
// Order is preserved: both sections share a notebook folder, and the locked placeholder keeps
@@ -251,12 +256,52 @@ describe("importSelection (real DB)", () => {
expect(orderedSectionTitles).toEqual(["Locked Section", "Open Section"]);
// The report records it (imported/total section count + a dedicated table linking to the
- // placeholder) and surfaces the Graph error verbatim.
+ // placeholder) with the friendly reason, not the raw Graph error code.
const content = parent.getChildNotes()[0]?.getContent() as string;
expect(content).toContain('<tr><th scope="row">Sections imported</th><td>1/2</td></tr>');
expect(content).toContain("Sections that could not be imported");
expect(content).toContain(`href="#root/${lockedNote?.noteId}"`);
- expect(content).toContain("Encrypted sections are not accessible.");
+ expect(content).toContain("Remove its password in OneNote");
+ expect(content).not.toContain("20185");
+ });
+
+ it("imports a section that fails to list for a non-protected reason as a plain placeholder showing the error", async () => {
+ // A transient/other Graph failure (not password protection): no lock icon, and the raw error is
+ // surfaced so the user can see what went wrong.
+ graphMock.isEncryptedSectionError.mockReturnValue(false);
+ graphMock.listPages.mockImplementation(async (_token, sectionId) => {
+ if (sectionId === "sec-broken") {
+ throw new Error("Microsoft Graph request failed (HTTP 504) from https://graph.microsoft.com/v1.0/me/onenote/sections/sec-broken/pages");
+ }
+ return [{ id: "1-ok2", title: "Fine Page", level: 0 }];
+ });
+ graphMock.getPageContent.mockResolvedValue({ html: "<p>hi</p>", inkml: "" });
+
+ const parent = cls.init(() => noteService.createNewNote({
+ parentNoteId: "root",
+ title: "broken parent",
+ content: "",
+ type: "text",
+ mime: "text/html"
+ }).note);
+
+ await cls.init(() => importSelection({
+ getAccessToken: () => Promise.resolve("token"),
+ parentNoteId: parent.noteId,
+ sections: [
+ { id: "sec-broken", title: "Broken Section", groupPath: [], notebookId: "nb-broken", notebookTitle: "Broken Notebook" },
+ { id: "sec-fine", title: "Fine Section", groupPath: [], notebookId: "nb-broken", notebookTitle: "Broken Notebook" }
+ ],
+ taskId: "task-broken"
+ }));
+
+ const brokenNote = Object.values(becca.notes).find((note) => note.title === "Broken Section");
+ expect(brokenNote?.hasOwnedLabel("oneNoteImportFailed")).toBe(true);
+ // Not password-protected: no lock icon, and the raw Graph error is kept for diagnosis.
+ expect(brokenNote?.getOwnedLabelValue("iconClass")).toBeNull();
+ expect(brokenNote?.getContent()).toContain("HTTP 504");
+ expect(brokenNote?.getContent()).not.toContain("password-protected");
+ expect(Object.values(becca.notes).find((note) => note.title === "Fine Page")).toBeDefined();
});
it("preserves the OneNote page order even when #newNotesOnTop is inherited onto the target", async () => {
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index 8d99d5df38..9319f7f53d 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -95,6 +95,9 @@ interface FetchedSection {
* so the user sees where it belongs and can unlock and re-import it.
*/
fetchError?: string;
+ /** Whether {@link fetchError} was caused by the section being password-protected: drives a friendlier
+ * placeholder message and a lock icon, distinguishing it from other (transient) section failures. */
+ passwordProtected?: boolean;
}
/**
@@ -114,7 +117,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
// Enumerate every selected section's pages up front so the total page count is known before
// any content is fetched — this lets the client show a real progress bar rather than a bare count.
- const sectionPages: { section: OneNoteSectionSelection; pages: OneNotePage[]; error?: string }[] = [];
+ const sectionPages: { section: OneNoteSectionSelection; pages: OneNotePage[]; error?: string; passwordProtected?: boolean }[] = [];
for (const section of sections) {
// A section whose page list can't be fetched doesn't abort the whole import: it is tagged
// with the error here and imported as a placeholder folder below, holding its place so the
@@ -123,20 +126,25 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
try {
sectionPages.push({ section, pages: await graph.listPages(getAccessToken, section.id) });
} catch (e: unknown) {
- const message = e instanceof Error ? e.message : String(e);
- getLog().error(`OneNote import: could not list the pages of section '${section.title}' (${section.id}); it will be imported as a placeholder: ${message}`);
- sectionPages.push({ section, pages: [], error: message });
+ const rawMessage = e instanceof Error ? e.message : String(e);
+ // A password-protected section is a user-fixable, expected case, so replace Graph's opaque
+ // "HTTP 403: 20185: Encrypted sections are not accessible." with actionable guidance. The
+ // raw error is still logged for diagnosis.
+ const passwordProtected = graph.isEncryptedSectionError(e);
+ const error = passwordProtected ? t("onenote_import.protected-section-error") : rawMessage;
+ getLog().error(`OneNote import: could not list the pages of section '${section.title}' (${section.id}); it will be imported as a placeholder: ${rawMessage}`);
+ sectionPages.push({ section, pages: [], error, passwordProtected });
}
}
taskContext.setTotalCount(sectionPages.reduce((total, entry) => total + entry.pages.length, 0));
const fetched: FetchedSection[] = [];
let consecutivePageFailures = 0;
- for (const { section, pages, error } of sectionPages) {
+ for (const { section, pages, error, passwordProtected } of sectionPages) {
// A section whose pages couldn't be listed keeps its slot in `fetched` (so import order is
// preserved) but carries the error instead of pages — createNotes renders it as a placeholder.
if (error !== undefined) {
- fetched.push(toFetchedSection(section, [], error));
+ fetched.push(toFetchedSection(section, [], error, passwordProtected));
continue;
}
const fetchedPages: FetchedPage[] = [];
@@ -189,7 +197,7 @@ export async function importSelection({ getAccessToken, parentNoteId, sections,
/** Copies a selected section's metadata into a {@link FetchedSection}, attaching its fetched pages and
* (when its page list couldn't be loaded) the error that turns it into a placeholder folder. */
-function toFetchedSection(section: OneNoteSectionSelection, pages: FetchedPage[], fetchError?: string): FetchedSection {
+function toFetchedSection(section: OneNoteSectionSelection, pages: FetchedPage[], fetchError?: string, passwordProtected?: boolean): FetchedSection {
return {
id: section.id,
title: section.title,
@@ -201,7 +209,8 @@ function toFetchedSection(section: OneNoteSectionSelection, pages: FetchedPage[]
notebookCreatedDateTime: section.notebookCreatedDateTime,
notebookLastModifiedDateTime: section.notebookLastModifiedDateTime,
pages,
- fetchError
+ fetchError,
+ passwordProtected
};
}
@@ -262,10 +271,14 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
if (section.fetchError !== undefined) {
// A section whose pages couldn't be listed becomes an empty placeholder folder: it holds the
// section's place in the tree (so order and hierarchy are preserved), explains itself, and is
- // findable/retryable by label + section id. The report links to this note.
- sectionNote.setContent(renderFailedSectionPlaceholder(section.fetchError));
+ // findable/retryable by label + section id. The report links to this note. A password-protected
+ // section — the expected, user-fixable case — gets a lock icon and tailored guidance.
+ sectionNote.setContent(section.passwordProtected ? renderProtectedSectionPlaceholder() : renderFailedSectionPlaceholder(section.fetchError));
sectionNote.addLabel("oneNoteImportFailed");
sectionNote.addLabel("oneNoteSectionId", section.id);
+ if (section.passwordProtected) {
+ sectionNote.addLabel("iconClass", "bx bx-lock-alt");
+ }
// Applied after setContent, whose save would otherwise re-stamp the modification date.
applyOriginalDates(sectionNote, section.createdDateTime, section.lastModifiedDateTime);
failedSections.push({ title: section.title, notebookTitle: section.notebookTitle, noteId: sectionNote.noteId, error: section.fetchError });
@@ -406,6 +419,12 @@ function renderFailedSectionPlaceholder(error: string): string {
return `<p>${t("onenote_import.failed-section-placeholder", { error })}</p>`;
}
+/** The body of a placeholder folder standing in for a password-protected section, with the steps to
+ * make it importable. No error is interpolated — the cause is known. */
+function renderProtectedSectionPlaceholder(): string {
+ return `<p>${t("onenote_import.protected-section-placeholder")}</p>`;
+}
+
/** Totals `value` over every downloaded page resource of the given kind. */
function sumResources(pages: { page: FetchedPage }[], kind: DownloadedResource["kind"], value: (resource: DownloadedResource) => number): number {
let sum = 0;