Skip to content

Build your personal knowledge base with Trilium Notes

fix(server): redact the user's email from OneNote import logs

Elian Doran4162f3e08921
diff --git a/apps/server/src/services/import/onenote/graph.spec.ts b/apps/server/src/services/import/onenote/graph.spec.ts
index 1bded2e9d4..068516ac0a 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 } from "./graph.js";
+import { backoffDelayMs, extractGraphErrorDetail, getAccount, getPageContent, getResource, getThrottleStats, listPages, resetThrottleGate, resetThrottleStats, retryAfterMs, sanitizeGraphUrl } from "./graph.js";
const safeFetchMock = vi.mocked(safeFetch);
@@ -266,6 +266,29 @@ describe("failed Graph requests", () => {
});
});
+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"))
+ .toBe("https://graph.microsoft.com/v1.0/users('<redacted>')/onenote/resources/0-abc!1-DEF!42/$value");
+ });
+
+ it("redacts a users/{id} path segment (guid or email)", () => {
+ expect(sanitizeGraphUrl("https://graph.microsoft.com/v1.0/users/8f3a-guid-1234/onenote/pages"))
+ .toBe("https://graph.microsoft.com/v1.0/users/<redacted>/onenote/pages");
+ });
+
+ it("leaves URLs without an identity segment untouched", () => {
+ // The importer's own calls use the /me alias, which carries no PII.
+ const url = "https://graph.microsoft.com/v1.0/me/onenote/pages/1-abc/content?includeInkML=true";
+ expect(sanitizeGraphUrl(url)).toBe(url);
+ });
+
+ it("redacts every occurrence and preserves the rest of the path", () => {
+ expect(sanitizeGraphUrl("/users('[email protected]')/x/users('[email protected]')/y"))
+ .toBe("/users('<redacted>')/x/users('<redacted>')/y");
+ });
+});
+
describe("extractGraphErrorDetail", () => {
it("extracts code and message from Graph's error envelope", () => {
expect(extractGraphErrorDetail(JSON.stringify({ error: { code: "20102", message: "The specified resource ID does not exist." } })))
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index 3eecd692fa..41dbe76923 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -88,7 +88,7 @@ async function graphFetch(accessToken: string, url: string): Promise<Response> {
// Drain the failed response so its connection is released before we back off.
await response.body?.cancel();
- getLog().info(`OneNote import: Graph gateway timeout (HTTP 504) on ${url}; retry ${gatewayTimeoutRetry}/${MAX_GATEWAY_TIMEOUT_RETRIES} after ${waitMs}ms`);
+ getLog().info(`OneNote import: Graph gateway timeout (HTTP 504) on ${sanitizeGraphUrl(url)}; retry ${gatewayTimeoutRetry}/${MAX_GATEWAY_TIMEOUT_RETRIES} after ${waitMs}ms`);
await delay(waitMs);
continue;
}
@@ -113,7 +113,7 @@ async function graphFetch(accessToken: string, url: string): Promise<Response> {
throttleWaitMs += Math.max(0, Date.now() + waitMs - Math.max(throttledUntilMs, Date.now()));
throttledUntilMs = Math.max(throttledUntilMs, Date.now() + waitMs);
throttleAttempt++;
- getLog().info(`OneNote import: Graph throttled (HTTP ${response.status}) on ${url}; retry ${throttleAttempt} after ${waitMs}ms (${Math.round((giveUpAtMs - Date.now()) / 60_000)}min of wait budget left)`);
+ getLog().info(`OneNote import: Graph throttled (HTTP ${response.status}) on ${sanitizeGraphUrl(url)}; retry ${throttleAttempt} after ${waitMs}ms (${Math.round((giveUpAtMs - Date.now()) / 60_000)}min of wait budget left)`);
}
}
@@ -314,7 +314,7 @@ export async function getResource(accessToken: string, url: string): Promise<{ c
}
const buffer = new Uint8Array(await response.arrayBuffer());
const contentType = response.headers.get("content-type") ?? "application/octet-stream";
- getLog().info(`OneNote import: downloaded resource (${contentType}, ${buffer.length} bytes) from ${url}`);
+ getLog().info(`OneNote import: downloaded resource (${contentType}, ${buffer.length} bytes) from ${sanitizeGraphUrl(url)}`);
return { content: buffer, contentType };
}
@@ -398,7 +398,21 @@ async function graphRequestError(summary: string, url: string, response: Respons
// The status and URL are still worth reporting when the body cannot be read.
}
const detail = extractGraphErrorDetail(body);
- return new Error(`${summary} (HTTP ${response.status}${detail ? `: ${detail}` : ""}) from ${url}`);
+ return new Error(`${summary} (HTTP ${response.status}${detail ? `: ${detail}` : ""}) from ${sanitizeGraphUrl(url)}`);
+}
+
+/**
+ * Redacts personal data from a Graph URL before it is logged or embedded in an error message. OneNote
+ * resource URLs (taken from page HTML) address the mailbox by the signed-in user's email — e.g.
+ * `…/users('[email protected]')/onenote/resources/…` — so the raw URL is PII. The email (or user id) in
+ * the `users('…')` / `users/{id}` segment is replaced with a placeholder; the rest of the path, which
+ * is what makes the log line useful for debugging, is kept. The importer's own calls use the `/me`
+ * alias and pass through unchanged.
+ */
+export function sanitizeGraphUrl(url: string): string {
+ return url
+ .replace(/users\('[^']*'\)/gi, "users('<redacted>')")
+ .replace(/users\/[^/?#]+/gi, "users/<redacted>");
}
/**
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index ca45d7eecd..18264e7651 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -12,7 +12,7 @@ import { parse } from "node-html-parser";
import sql from "../../sql.js";
import converter, { ONENOTE_ATTACHMENT_CLASS } from "./converter.js";
-import graph, { type OneNotePage } from "./graph.js";
+import graph, { type OneNotePage, sanitizeGraphUrl } from "./graph.js";
import { inkmlToSvg } from "./inkml.js";
import { type LinkTarget, rewritePageLinks } from "./links.js";
import { type FailedPageReport, type ImportReportData, renderImportReport } from "./report.js";
@@ -423,7 +423,7 @@ async function downloadPageResources(accessToken: string, pageTitle: string, htm
const { content, contentType } = await graph.getResource(accessToken, ref.url);
return { ...ref, mime: ref.mime || contentType, content };
} catch (e: unknown) {
- getLog().error(`OneNote import: could not download resource ${ref.url}: ${e instanceof Error ? e.message : e}`);
+ getLog().error(`OneNote import: could not download resource ${sanitizeGraphUrl(ref.url)}: ${e instanceof Error ? e.message : e}`);
return null;
}
});