Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(import): prototype OneNote importer with generic provider modal
Elian Dorane0edce96c88b
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex eb0609c209..7f48496951 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -136,6 +136,7 @@ export type CommandMappings = {showConfirmDialog: ConfirmWithMessageOptions;showRecentChanges: CommandData & { ancestorNoteId: string };showImportDialog: CommandData & { noteId: string };+ showImportProviderDialog: CommandData & { noteId: string };openNewNoteSplit: NoteCommandData;openInWindow: NoteCommandData;openInPopup: CommandData & { noteIdOrPath: string; };diff --git a/apps/client/src/layouts/layout_commons.tsx b/apps/client/src/layouts/layout_commons.tsxindex 176a08b31f..1c7d181679 100644--- a/apps/client/src/layouts/layout_commons.tsx+++ b/apps/client/src/layouts/layout_commons.tsx@@ -25,6 +25,7 @@ export function applyModals(rootContainer: RootContainer) {.child(<LazyDialog triggerEvents={["cloneNoteIdsTo"]} loader={() => import("../widgets/dialogs/clone_to.js")} />).child(<LazyDialog triggerEvents={["moveBranchIdsTo"]} loader={() => import("../widgets/dialogs/move_to.js")} />).child(<LazyDialog triggerEvents={["showImportDialog"]} loader={() => import("../widgets/dialogs/import.js")} />)+ .child(<LazyDialog triggerEvents={["showImportProviderDialog"]} loader={() => import("../widgets/dialogs/import_provider.js")} />).child(<LazyDialog triggerEvents={["showExportDialog"]} loader={() => import("../widgets/dialogs/export.js")} />).child(<LazyDialog triggerEvents={["showPasteMarkdownDialog"]} loader={() => import("../widgets/dialogs/markdown_import.js")} />).child(<LazyDialog triggerEvents={["showProtectedSessionPasswordDialog"]} loader={() => import("../widgets/dialogs/protected_session_password.js")} />)diff --git a/apps/client/src/services/onenote_import.ts b/apps/client/src/services/onenote_import.tsnew file mode 100644index 0000000000..e9ddaab3b5--- /dev/null+++ b/apps/client/src/services/onenote_import.ts@@ -0,0 +1,57 @@+import server from "./server.js";++export interface OneNoteAccount {+ name: string;+ email: string;+}++export interface OneNoteStatus {+ connected: boolean;+ account: OneNoteAccount | null;+}++export interface OneNoteSection {+ id: string;+ title: string;+}++export interface OneNoteNotebook {+ id: string;+ title: string;+ sections: OneNoteSection[];+}++/** Mirrors `SectionSelection` on the server. */+export interface OneNoteSectionSelection {+ id: string;+ title: string;+ notebookTitle: string;+}++function getAuthUrl() {+ return server.get<{ authUrl: string }>("onenote-import/auth-url");+}++function getStatus() {+ return server.get<OneNoteStatus>("onenote-import/status");+}++function disconnect() {+ return server.post("onenote-import/disconnect");+}++function getNotebooks() {+ return server.get<{ notebooks: OneNoteNotebook[] }>("onenote-import/notebooks");+}++function runImport(payload: { parentNoteId: string; sections: OneNoteSectionSelection[]; taskId: string }) {+ return server.post<{ noteId: string }>("onenote-import/import", payload);+}++export default {+ getAuthUrl,+ getStatus,+ disconnect,+ getNotebooks,+ runImport+};diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex c174388c9a..2d8ad9e733 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -228,6 +228,25 @@"in-progress": "Import in progress: {{progress}}","successful": "Import finished successfully."},+ "import_provider": {+ "title": "Import from a service",+ "choose_provider": "Choose a service to import from:",+ "back": "Back"+ },+ "onenote_import": {+ "name": "Microsoft OneNote",+ "description": "Import notebooks, sections and pages from your OneNote account.",+ "connect_description": "Sign in with your Microsoft account to import your OneNote notebooks.",+ "connect": "Sign in with Microsoft",+ "connecting": "Waiting for sign-in to complete…",+ "connected_as": "Connected as {{name}}",+ "disconnect": "Disconnect",+ "load_failed": "Could not load your OneNote notebooks.",+ "no_notebooks": "No notebooks were found in this account.",+ "select_sections": "Select the sections to import:",+ "import": "Import selected",+ "import_started": "OneNote import started…"+ },"include_note": {"dialog_title": "Include note","label_note": "Note",@@ -808,6 +827,7 @@"open_note_custom": "Open note custom","open_note_on_server": "Open note on server","import_files": "Import files",+ "import_from_service": "Import from a service…","export_note": "Export note","delete_note": "Delete note","print_note": "Print note...",diff --git a/apps/client/src/widgets/dialogs/import_provider.css b/apps/client/src/widgets/dialogs/import_provider.cssnew file mode 100644index 0000000000..dda7c48257--- /dev/null+++ b/apps/client/src/widgets/dialogs/import_provider.css@@ -0,0 +1,78 @@+.modal.import-provider-dialog {+ .import-provider-picker {+ display: flex;+ flex-direction: column;+ gap: 0.75em;+ }++ .import-provider-card {+ display: flex;+ align-items: center;+ gap: 1em;+ width: 100%;+ padding: 1em;+ text-align: left;+ border: 1px solid var(--main-border-color);+ border-radius: 8px;+ background: var(--accented-background-color);+ cursor: pointer;+ }++ .import-provider-card:hover {+ border-color: var(--main-text-color);+ }++ .import-provider-card .tn-icon {+ font-size: 1.8em;+ }++ .import-provider-card-text {+ display: flex;+ flex-direction: column;+ }++ .import-provider-card-name {+ font-weight: bold;+ }++ .import-provider-card-description {+ color: var(--muted-text-color);+ font-size: 0.9em;+ }++ .onenote-account {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1em;+ margin-bottom: 1em;+ padding-bottom: 0.75em;+ border-bottom: 1px solid var(--main-border-color);+ }++ .onenote-status {+ display: flex;+ align-items: center;+ gap: 0.5em;+ }++ .onenote-notebooks {+ display: flex;+ flex-direction: column;+ gap: 1em;+ max-height: 45vh;+ overflow-y: auto;+ }++ .onenote-notebook {+ display: flex;+ flex-direction: column;+ gap: 0.25em;+ }++ .onenote-actions {+ display: flex;+ justify-content: flex-end;+ margin-top: 1em;+ }+}diff --git a/apps/client/src/widgets/dialogs/import_provider.tsx b/apps/client/src/widgets/dialogs/import_provider.tsxnew file mode 100644index 0000000000..34c33c9e98--- /dev/null+++ b/apps/client/src/widgets/dialogs/import_provider.tsx@@ -0,0 +1,58 @@+import "./import_provider.css";++import { useState } from "preact/hooks";++import { t } from "../../services/i18n.js";+import Button from "../react/Button.js";+import { useTriliumEvent } from "../react/hooks.js";+import Icon from "../react/Icon.js";+import Modal from "../react/Modal.js";+import { importProviders } from "./import_providers/index.js";++/**+ * Generic "import from a service" dialog. It is provider-agnostic: it shows a picker of registered+ * {@link importProviders} and then hands off to the chosen provider's panel, which drives its own+ * flow (auth, selection, progress). Add new sources by registering them in `import_providers`.+ */+export default function ImportProviderDialog() {+ const [parentNoteId, setParentNoteId] = useState<string>();+ const [providerId, setProviderId] = useState<string>();+ const [shown, setShown] = useState(false);++ useTriliumEvent("showImportProviderDialog", ({ noteId }) => {+ setParentNoteId(noteId);+ setProviderId(undefined);+ setShown(true);+ });++ const provider = importProviders.find((p) => p.id === providerId);++ return (+ <Modal+ className="import-provider-dialog"+ size="lg"+ scrollable+ title={provider ? provider.name : t("import_provider.title")}+ header={provider && <Button text={t("import_provider.back")} kind="lowProfile" size="small" icon="bx-arrow-back" onClick={() => setProviderId(undefined)} />}+ onHidden={() => setShown(false)}+ show={shown}+ >+ {!provider && (+ <div className="import-provider-picker">+ <p>{t("import_provider.choose_provider")}</p>+ {importProviders.map((p) => (+ <button type="button" className="import-provider-card" key={p.id} onClick={() => setProviderId(p.id)}>+ <Icon icon={p.icon} />+ <span className="import-provider-card-text">+ <span className="import-provider-card-name">{p.name}</span>+ <span className="import-provider-card-description">{p.description}</span>+ </span>+ </button>+ ))}+ </div>+ )}++ {provider && parentNoteId && <provider.Panel parentNoteId={parentNoteId} closeDialog={() => setShown(false)} />}+ </Modal>+ );+}diff --git a/apps/client/src/widgets/dialogs/import_providers/index.ts b/apps/client/src/widgets/dialogs/import_providers/index.tsnew file mode 100644index 0000000000..276a952260--- /dev/null+++ b/apps/client/src/widgets/dialogs/import_providers/index.ts@@ -0,0 +1,10 @@+import oneNoteProvider from "./onenote.js";+import type { ImportProvider } from "./types.js";++/**+ * Registry of available import providers. Append new providers here; the generic import dialog+ * renders the picker and each provider's panel automatically.+ */+export const importProviders: ImportProvider[] = [oneNoteProvider];++export type { ImportProvider, ImportProviderPanelProps } from "./types.js";diff --git a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx b/apps/client/src/widgets/dialogs/import_providers/onenote.tsxnew file mode 100644index 0000000000..574c8e9a45--- /dev/null+++ b/apps/client/src/widgets/dialogs/import_providers/onenote.tsx@@ -0,0 +1,189 @@+import { useCallback, useEffect, useRef, useState } from "preact/hooks";++import { t } from "../../../services/i18n.js";+import onenoteImport, { type OneNoteAccount, type OneNoteNotebook, type OneNoteSectionSelection } from "../../../services/onenote_import.js";+import toast from "../../../services/toast.js";+import { isElectron, randomString } from "../../../services/utils.js";+import Button from "../../react/Button.js";+import FormCheckbox from "../../react/FormCheckbox.js";+import LoadingSpinner from "../../react/LoadingSpinner.js";+import type { ImportProvider, ImportProviderPanelProps } from "./types.js";++type Phase = "checking" | "disconnected" | "connecting" | "ready";++function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {+ const [phase, setPhase] = useState<Phase>("checking");+ const [account, setAccount] = useState<OneNoteAccount | null>(null);+ const [notebooks, setNotebooks] = useState<OneNoteNotebook[]>([]);+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());+ const [importing, setImporting] = useState(false);+ const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);++ const stopPolling = useCallback(() => {+ if (pollRef.current) {+ clearInterval(pollRef.current);+ pollRef.current = null;+ }+ }, []);++ const loadNotebooks = useCallback(async () => {+ try {+ const { notebooks } = await onenoteImport.getNotebooks();+ setNotebooks(notebooks);+ } catch {+ toast.showError(t("onenote_import.load_failed"));+ }+ }, []);++ // On mount, see whether this session is already connected.+ useEffect(() => {+ void onenoteImport.getStatus().then(async (status) => {+ if (status.connected) {+ setAccount(status.account);+ await loadNotebooks();+ setPhase("ready");+ } else {+ setPhase("disconnected");+ }+ });+ return stopPolling;+ }, [loadNotebooks, stopPolling]);++ const connect = useCallback(async () => {+ try {+ const { authUrl } = await onenoteImport.getAuthUrl();+ if (isElectron()) {+ window.electronApi?.shell.openExternal(authUrl);+ } else {+ window.open(authUrl, "_blank", "noopener,noreferrer");+ }++ setPhase("connecting");+ stopPolling();+ pollRef.current = setInterval(async () => {+ const status = await onenoteImport.getStatus();+ if (status.connected) {+ stopPolling();+ setAccount(status.account);+ await loadNotebooks();+ setPhase("ready");+ }+ }, 2000);+ } catch (e) {+ toast.showError(e instanceof Error ? e.message : String(e));+ setPhase("disconnected");+ }+ }, [loadNotebooks, stopPolling]);++ const disconnect = useCallback(async () => {+ stopPolling();+ await onenoteImport.disconnect();+ setAccount(null);+ setNotebooks([]);+ setSelectedIds(new Set());+ setPhase("disconnected");+ }, [stopPolling]);++ const toggleSection = useCallback((id: string, checked: boolean) => {+ setSelectedIds((prev) => {+ const next = new Set(prev);+ if (checked) {+ next.add(id);+ } else {+ next.delete(id);+ }+ return next;+ });+ }, []);++ const doImport = useCallback(async () => {+ const sections: OneNoteSectionSelection[] = [];+ for (const notebook of notebooks) {+ for (const section of notebook.sections) {+ if (selectedIds.has(section.id)) {+ sections.push({ id: section.id, title: section.title, notebookTitle: notebook.title });+ }+ }+ }+ if (!sections.length) {+ return;+ }++ setImporting(true);+ try {+ await onenoteImport.runImport({ parentNoteId, sections, taskId: randomString(10) });+ toast.showMessage(t("onenote_import.import_started"));+ closeDialog();+ } catch (e) {+ toast.showError(e instanceof Error ? e.message : String(e));+ setImporting(false);+ }+ }, [notebooks, selectedIds, parentNoteId, closeDialog]);++ if (phase === "checking") {+ return <div className="onenote-panel"><LoadingSpinner /></div>;+ }++ if (phase === "disconnected" || phase === "connecting") {+ return (+ <div className="onenote-panel">+ <p>{t("onenote_import.connect_description")}</p>+ {phase === "connecting"+ ? <p className="onenote-status"><LoadingSpinner /> {t("onenote_import.connecting")}</p>+ : <Button text={t("onenote_import.connect")} kind="primary" icon="bxl-microsoft" onClick={connect} />}+ </div>+ );+ }++ return (+ <div className="onenote-panel">+ <div className="onenote-account">+ <span>{t("onenote_import.connected_as", { name: account?.name ?? "" })}</span>+ <Button text={t("onenote_import.disconnect")} kind="lowProfile" size="small" onClick={disconnect} />+ </div>++ {notebooks.length === 0+ ? <p>{t("onenote_import.no_notebooks")}</p>+ : (+ <>+ <p>{t("onenote_import.select_sections")}</p>+ <div className="onenote-notebooks">+ {notebooks.map((notebook) => (+ <div className="onenote-notebook" key={notebook.id}>+ <strong>{notebook.title}</strong>+ {notebook.sections.map((section) => (+ <FormCheckbox+ key={section.id}+ name={`onenote-section-${section.id}`}+ label={section.title}+ currentValue={selectedIds.has(section.id)}+ onChange={(checked) => toggleSection(section.id, checked)}+ />+ ))}+ </div>+ ))}+ </div>+ </>+ )}++ <div className="onenote-actions">+ <Button+ text={t("onenote_import.import")}+ kind="primary"+ disabled={importing || selectedIds.size === 0}+ onClick={doImport}+ />+ </div>+ </div>+ );+}++const provider: ImportProvider = {+ id: "onenote",+ name: t("onenote_import.name"),+ icon: "bx bxl-microsoft",+ description: t("onenote_import.description"),+ Panel: OneNotePanel+};++export default provider;diff --git a/apps/client/src/widgets/dialogs/import_providers/types.ts b/apps/client/src/widgets/dialogs/import_providers/types.tsnew file mode 100644index 0000000000..5c125a3186--- /dev/null+++ b/apps/client/src/widgets/dialogs/import_providers/types.ts@@ -0,0 +1,25 @@+import type { ComponentType } from "preact";++export interface ImportProviderPanelProps {+ /** The note the imported tree should be created under. */+ parentNoteId: string;+ /** Closes the surrounding import dialog (e.g. once the import has been kicked off). */+ closeDialog: () => void;+}++/**+ * A pluggable source the generic import dialog can import from. Add a new provider by implementing+ * this interface and appending it to the registry in `index.ts`; the dialog wires up the rest.+ */+export interface ImportProvider {+ /** Stable identifier. */+ id: string;+ /** Human-readable name shown in the provider picker. */+ name: string;+ /** Boxicons class, e.g. `"bx bxl-microsoft"`. */+ icon: string;+ /** One-line description shown under the name. */+ description: string;+ /** The component rendered once this provider is chosen; it drives its own multi-step flow. */+ Panel: ComponentType<ImportProviderPanelProps>;+}diff --git a/apps/client/src/widgets/ribbon/NoteActions.tsx b/apps/client/src/widgets/ribbon/NoteActions.tsxindex bd0f30147a..d48511257f 100644--- a/apps/client/src/widgets/ribbon/NoteActions.tsx+++ b/apps/client/src/widgets/ribbon/NoteActions.tsx@@ -148,6 +148,9 @@ export function NoteContextMenu({ note, noteContext, itemsAtStart, itemsNearNote<CommandItem icon="bx bx-import" text={t("note_actions.import_files")}disabled={isInOptionsOrHelp || note.type === "search"}command={() => parentComponent?.triggerCommand("showImportDialog", { noteId: note.noteId })} />+ <CommandItem icon="bx bx-cloud-download" text={t("note_actions.import_from_service")}+ disabled={isInOptionsOrHelp || note.type === "search"}+ command={() => parentComponent?.triggerCommand("showImportProviderDialog", { noteId: note.noteId })} /><CommandItem icon="bx bx-export" text={t("note_actions.export_note")}disabled={isInOptionsOrHelp || note.noteId === "_backendLog"}command={() => noteContext?.notePath && parentComponent?.triggerCommand("showExportDialog", {diff --git a/apps/server/src/express.d.ts b/apps/server/src/express.d.tsindex a5ff1b77ee..1c5938ef5e 100644--- a/apps/server/src/express.d.ts+++ b/apps/server/src/express.d.ts@@ -44,5 +44,19 @@ export declare module "express-session" {* after the post-enrollment redirect lands on the app root.*/ssoJustEnrolled?: true;+ /**+ * Transient state for the OneNote importer's delegated-Graph OAuth flow. During sign-in it+ * holds the PKCE verifier + state + redirect URI; after a successful callback it holds the+ * access/refresh tokens and the connected account. Session-scoped only — never synced.+ */+ oneNoteImport?: {+ verifier?: string;+ state?: string;+ redirectUri?: string;+ accessToken?: string;+ refreshToken?: string;+ expiresAt?: number;+ account?: { name: string; email: string };+ };}}diff --git a/apps/server/src/routes/api/onenote_import.ts b/apps/server/src/routes/api/onenote_import.tsnew file mode 100644index 0000000000..05ec215476--- /dev/null+++ b/apps/server/src/routes/api/onenote_import.ts@@ -0,0 +1,160 @@+/**+ * REST endpoints for the OneNote importer. Implements the OAuth authorization-code-with-PKCE flow+ * (delegated Microsoft Graph access) and the actual import. Tokens live in the user's session only —+ * they are never written to the synced options store.+ *+ * Flow:+ * 1. GET /api/onenote-import/auth-url -> { authUrl } (client opens it in a browser)+ * 2. GET /api/onenote-import/callback -> browser lands here after sign-in; tokens are stored+ * 3. GET /api/onenote-import/status -> { connected, account } (client polls)+ * 4. GET /api/onenote-import/notebooks -> { notebooks }+ * 5. POST /api/onenote-import/import -> { noteId }+ */++import { becca, ValidationError } from "@triliumnext/core";+import type { Request, Response } from "express";++import graph from "../../services/import/onenote/graph.js";+import importer, { type SectionSelection } from "../../services/import/onenote/importer.js";+import oauth from "../../services/import/onenote/oauth.js";++function getAuthUrl(req: Request) {+ const clientId = oauth.getClientId();+ if (!clientId) {+ return [400, "OneNote import is not configured. Set the TRILIUM_ONENOTE_CLIENT_ID environment variable to the client id of a registered Microsoft Entra application."];+ }++ const { verifier, challenge } = oauth.generatePkce();+ const state = oauth.generateState();+ const redirectUri = getRedirectUri(req);++ req.session.oneNoteImport = { verifier, state, redirectUri };++ return { authUrl: oauth.buildAuthorizationUrl({ clientId, redirectUri, state, challenge }) };+}++async function callback(req: Request, res: Response) {+ res.triliumResponseHandled = true;++ try {+ const { code, state, error } = req.query as { code?: string; state?: string; error?: string };+ const pending = req.session.oneNoteImport;++ if (error) {+ return sendHtml(res, `Sign-in failed: ${error}. You can close this window and try again.`);+ }+ if (!code || !pending?.verifier || !pending.state || !pending.redirectUri || pending.state !== state) {+ return sendHtml(res, "Sign-in could not be completed (invalid or expired state). Please close this window and try again.");+ }++ const clientId = oauth.getClientId();+ if (!clientId) {+ return sendHtml(res, "OneNote import is not configured on the server.");+ }++ const tokens = await oauth.exchangeCodeForToken({ clientId, code, verifier: pending.verifier, redirectUri: pending.redirectUri });+ const account = await graph.getAccount(tokens.access_token);++ req.session.oneNoteImport = {+ accessToken: tokens.access_token,+ refreshToken: tokens.refresh_token,+ expiresAt: Date.now() + tokens.expires_in * 1000,+ account+ };+ await saveSession(req);++ return sendHtml(res, `Connected as ${account.name}. You can close this window and return to Trilium.`);+ } catch (e) {+ return sendHtml(res, `Sign-in failed: ${e instanceof Error ? e.message : String(e)}`);+ }+}++function getStatus(req: Request) {+ const session = req.session.oneNoteImport;+ return { connected: !!session?.accessToken, account: session?.account ?? null };+}++function disconnect(req: Request) {+ delete req.session.oneNoteImport;+ return {};+}++async function getNotebooks(req: Request) {+ const accessToken = await getValidAccessToken(req);+ if (!accessToken) {+ return [401, "Not connected to OneNote."];+ }+ return { notebooks: await graph.listNotebooks(accessToken) };+}++async function runImport(req: Request) {+ const accessToken = await getValidAccessToken(req);+ if (!accessToken) {+ return [401, "Not connected to OneNote."];+ }++ const { parentNoteId, sections, taskId } = req.body as { parentNoteId: string; sections: SectionSelection[]; taskId: string };+ if (!parentNoteId || !taskId) {+ throw new ValidationError("parentNoteId and taskId are required.");+ }+ if (!Array.isArray(sections) || sections.length === 0) {+ return [400, "No sections were selected."];+ }+ becca.getNoteOrThrow(parentNoteId);++ const noteId = await importer.importSelection({ accessToken, parentNoteId, sections, taskId });+ return { noteId };+}++function getRedirectUri(req: Request): string {+ return `${req.protocol}://${req.get("host")}/api/onenote-import/callback`;+}++/** Returns a usable access token, transparently refreshing it when expired, or null if disconnected. */+async function getValidAccessToken(req: Request): Promise<string | null> {+ const session = req.session.oneNoteImport;+ if (!session?.accessToken) {+ return null;+ }++ const stillValid = session.expiresAt && Date.now() < session.expiresAt - 60_000;+ if (stillValid) {+ return session.accessToken;+ }++ const clientId = oauth.getClientId();+ if (session.refreshToken && clientId) {+ const tokens = await oauth.refreshAccessToken({ clientId, refreshToken: session.refreshToken });+ session.accessToken = tokens.access_token;+ session.refreshToken = tokens.refresh_token ?? session.refreshToken;+ session.expiresAt = Date.now() + tokens.expires_in * 1000;+ await saveSession(req);+ }++ return session.accessToken;+}++function saveSession(req: Request): Promise<void> {+ return new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve())));+}++function sendHtml(res: Response, message: string) {+ res.status(200).setHeader("Content-Type", "text/html").send(+ `<!doctype html><html><head><meta charset="utf-8"><title>OneNote import</title></head>` ++ `<body style="font-family: sans-serif; padding: 2rem; text-align: center;">` ++ `<p>${escapeHtml(message)}</p><script>setTimeout(() => window.close(), 1500);</script></body></html>`+ );+}++function escapeHtml(text: string): string {+ return text.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c] ?? c);+}++export default {+ getAuthUrl,+ callback,+ getStatus,+ disconnect,+ getNotebooks,+ runImport+};diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 85fa7059b0..c25944057e 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -29,6 +29,7 @@ import llmSpecialNotesRoute from "./api/llm_special_notes.js";import loginApiRoute from "./api/login.js";import metricsRoute from "./api/metrics.js";import ocrRoute from "./api/ocr.js";+import onenoteImportRoute from "./api/onenote_import.js";import recoveryCodes from './api/recovery_codes.js';import senderRoute from "./api/sender.js";import systemInfoRoute from "./api/system_info.js";@@ -182,6 +183,15 @@ function register(app: express.Application) {route(GET, "/api/fonts", [auth.checkApiAuthOrElectron], fontsRoute.getFontCss);asyncApiRoute(GET, "/api/link-embed/metadata", linkEmbedRoute.getMetadata);+ apiRoute(GET, "/api/onenote-import/auth-url", onenoteImportRoute.getAuthUrl);+ // Plain GET (no CSRF/auth headers): this is a top-level browser redirect back from Microsoft.+ // The OAuth `state` validated against the session is what guards it.+ asyncRoute(GET, "/api/onenote-import/callback", [], onenoteImportRoute.callback);+ apiRoute(GET, "/api/onenote-import/status", onenoteImportRoute.getStatus);+ apiRoute(PST, "/api/onenote-import/disconnect", onenoteImportRoute.disconnect);+ asyncApiRoute(GET, "/api/onenote-import/notebooks", onenoteImportRoute.getNotebooks);+ asyncApiRoute(PST, "/api/onenote-import/import", onenoteImportRoute.runImport);+shareRoutes.register(router);etapiAuthRoutes.register(router, [loginRateLimiter]);diff --git a/apps/server/src/services/import/onenote/converter.ts b/apps/server/src/services/import/onenote/converter.tsnew file mode 100644index 0000000000..8563187bf5--- /dev/null+++ b/apps/server/src/services/import/onenote/converter.ts@@ -0,0 +1,40 @@+/**+ * Converts a OneNote page (a full HTML document returned by the Graph API) into the HTML body that+ * Trilium stores for a text note.+ *+ * This is a deliberately minimal first pass: it extracts the document body and sanitizes it. The+ * Obsidian importer additionally rebuilds code blocks from Consolas-styled spans, converts MathML to+ * LaTeX, downloads attachments, and rasterizes ink to SVG — all of which are good future additions+ * but out of scope for this prototype. The OneNote "to-do" tags are converted here because they map+ * cleanly onto Trilium task-list checkboxes and are cheap to handle.+ *+ * NOTE: images and file attachments are referenced via authenticated Graph URLs and are NOT yet+ * downloaded, so embedded media will not render after import. See the summary for follow-up work.+ */++import { sanitize } from "@triliumnext/core";+import { parse } from "node-html-parser";++export function convertPageHtml(rawHtml: string): string {+ const root = parse(rawHtml);++ convertTodoTags(root);++ const body = root.querySelector("body");+ const inner = body ? body.innerHTML : rawHtml;++ return sanitize.sanitizeHtml(inner);+}++/** OneNote marks checkboxes with `data-tag="to-do"` / `"to-do:completed"`; render them as task items. */+function convertTodoTags(root: ReturnType<typeof parse>) {+ for (const el of root.querySelectorAll("[data-tag]")) {+ const tag = el.getAttribute("data-tag");+ if (tag === "to-do" || tag === "to-do:completed") {+ const checkbox = tag === "to-do:completed" ? "[x]" : "[ ]";+ el.set_content(`${checkbox} ${el.innerHTML}`);+ }+ }+}++export default { convertPageHtml };diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.tsnew file mode 100644index 0000000000..0eedff7c5a--- /dev/null+++ b/apps/server/src/services/import/onenote/graph.ts@@ -0,0 +1,129 @@+/**+ * Minimal Microsoft Graph client for the OneNote importer. Only the read endpoints needed to+ * enumerate the notebook tree and pull page content are implemented.+ *+ * Graph reference: https://learn.microsoft.com/en-us/graph/api/resources/onenote-api-overview+ */++const GRAPH_BASE = "https://graph.microsoft.com/v1.0";++export interface GraphAccount {+ name: string;+ email: string;+}++export interface OneNoteSection {+ id: string;+ title: string;+}++export interface OneNoteNotebook {+ id: string;+ title: string;+ sections: OneNoteSection[];+}++export interface OneNotePage {+ id: string;+ title: string;+ createdDateTime?: string;+ lastModifiedDateTime?: string;+}++export async function getAccount(accessToken: string): Promise<GraphAccount> {+ const me = await graphGet<{ displayName?: string; mail?: string; userPrincipalName?: string }>(accessToken, "/me");+ return {+ name: me.displayName ?? me.userPrincipalName ?? "Unknown",+ email: me.mail ?? me.userPrincipalName ?? ""+ };+}++/**+ * Returns the notebooks with their sections. Sections nested inside section groups are flattened+ * into the owning notebook with a "Group / Section" title — good enough for a first import pass.+ */+export async function listNotebooks(accessToken: string): Promise<OneNoteNotebook[]> {+ const url = "/me/onenote/notebooks?$select=id,displayName&$expand=sections($select=id,displayName),sectionGroups($expand=sections($select=id,displayName))&$orderby=displayName";+ const raw = await graphGetAll<RawNotebook>(accessToken, url);++ return raw.map((notebook) => {+ const sections: OneNoteSection[] = (notebook.sections ?? []).map((s) => ({ id: s.id, title: s.displayName }));+ for (const group of notebook.sectionGroups ?? []) {+ for (const s of group.sections ?? []) {+ sections.push({ id: s.id, title: `${group.displayName} / ${s.displayName}` });+ }+ }+ return { id: notebook.id, title: notebook.displayName, sections };+ });+}++export async function listPages(accessToken: string, sectionId: string): Promise<OneNotePage[]> {+ const url = `/me/onenote/sections/${sectionId}/pages?$select=id,title,createdDateTime,lastModifiedDateTime&$orderby=order&pagelevel=true`;+ const raw = await graphGetAll<RawPage>(accessToken, url);+ return raw.map((p) => ({+ id: p.id,+ title: p.title || "Untitled",+ createdDateTime: p.createdDateTime,+ lastModifiedDateTime: p.lastModifiedDateTime+ }));+}++/** Returns the raw HTML body of a page (a full HTML document as produced by the OneNote API). */+export async function getPageContent(accessToken: string, pageId: string): Promise<string> {+ const response = await fetch(`${GRAPH_BASE}/me/onenote/pages/${pageId}/content`, {+ headers: { Authorization: `Bearer ${accessToken}` }+ });+ if (!response.ok) {+ throw new Error(`Failed to fetch OneNote page content (HTTP ${response.status})`);+ }+ return response.text();+}++interface RawNotebook {+ id: string;+ displayName: string;+ sections?: { id: string; displayName: string }[];+ sectionGroups?: { displayName: string; sections?: { id: string; displayName: string }[] }[];+}++interface RawPage {+ id: string;+ title?: string;+ createdDateTime?: string;+ lastModifiedDateTime?: string;+}++async function graphGet<T>(accessToken: string, path: string): Promise<T> {+ const response = await fetch(`${GRAPH_BASE}${path}`, {+ headers: { Authorization: `Bearer ${accessToken}` }+ });+ if (!response.ok) {+ throw new Error(`Microsoft Graph request failed: ${path} (HTTP ${response.status})`);+ }+ return response.json() as Promise<T>;+}++/** GETs a Graph collection endpoint, following @odata.nextLink pagination. */+async function graphGetAll<T>(accessToken: string, path: string): Promise<T[]> {+ const results: T[] = [];+ let next: string | null = `${GRAPH_BASE}${path}`;++ while (next) {+ const response: Response = await fetch(next, { headers: { Authorization: `Bearer ${accessToken}` } });+ if (!response.ok) {+ throw new Error(`Microsoft Graph request failed: ${path} (HTTP ${response.status})`);+ }+ const json = (await response.json()) as { value?: T[]; "@odata.nextLink"?: string };+ results.push(...(json.value ?? []));+ next = json["@odata.nextLink"] ?? null;+ }++ return results;+}++export default {+ getAccount,+ listNotebooks,+ listPages,+ getPageContent+};diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.tsnew file mode 100644index 0000000000..dff718df88--- /dev/null+++ b/apps/server/src/services/import/onenote/importer.ts@@ -0,0 +1,91 @@+/**+ * Creates the Trilium note tree from a OneNote selection. Mirrors the structure of the existing+ * file-based importers (see packages/trilium-core/src/services/import/enex.ts): build a container,+ * then child notes, reporting progress through a TaskContext of type "importNotes" so the existing+ * client-side import toasts apply unchanged.+ */++import { becca, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";++import sql from "../../sql.js";+import converter from "./converter.js";+import graph from "./graph.js";++export interface SectionSelection {+ id: string;+ title: string;+ notebookTitle: string;+}++interface FetchedPage {+ title: string;+ html: string;+}++interface FetchedSection {+ title: string;+ notebookTitle: string;+ pages: FetchedPage[];+}++export async function importSelection({ accessToken, parentNoteId, sections, taskId }: { accessToken: string; parentNoteId: string; sections: SectionSelection[]; taskId: string }): Promise<string> {+ const taskContext = TaskContext.getInstance(taskId, "importNotes", { safeImport: true });++ // Phase 1: pull everything over the network first, so note creation can run in a single+ // synchronous transaction afterwards.+ const fetched: FetchedSection[] = [];+ for (const section of sections) {+ const pages = await graph.listPages(accessToken, section.id);+ const fetchedPages: FetchedPage[] = [];+ for (const page of pages) {+ const rawHtml = await graph.getPageContent(accessToken, page.id);+ fetchedPages.push({ title: page.title, html: converter.convertPageHtml(rawHtml) });+ taskContext.increaseProgressCount();+ }+ fetched.push({ title: section.title, notebookTitle: section.notebookTitle, pages: fetchedPages });+ }++ // Phase 2: create the note tree.+ const rootNoteId = sql.transactional(() => createNotes(parentNoteId, fetched));++ taskContext.taskSucceeded({ parentNoteId, importedNoteId: rootNoteId });++ return rootNoteId;+}++function createNotes(parentNoteId: string, sections: FetchedSection[]): string {+ const parentNote = becca.getNoteOrThrow(parentNoteId);+ const isProtected = parentNote.isProtected && protectedSession.isProtectedSessionAvailable();++ const createFolder = (parentId: string, title: string) =>+ noteService.createNewNote({ parentNoteId: parentId, title, content: "", type: "text", mime: "text/html", isProtected }).note;++ const rootNote = createFolder(parentNoteId, "OneNote import");++ // Group selected sections under a note per notebook so the original hierarchy is preserved.+ const notebookNotes = new Map<string, string>();+ for (const section of sections) {+ let notebookNoteId = notebookNotes.get(section.notebookTitle);+ if (!notebookNoteId) {+ notebookNoteId = createFolder(rootNote.noteId, section.notebookTitle).noteId;+ notebookNotes.set(section.notebookTitle, notebookNoteId);+ }++ const sectionNote = createFolder(notebookNoteId, section.title);++ for (const page of section.pages) {+ noteService.createNewNote({+ parentNoteId: sectionNote.noteId,+ title: page.title,+ content: page.html,+ type: "text",+ mime: "text/html",+ isProtected+ });+ }+ }++ return rootNote.noteId;+}++export default { importSelection };diff --git a/apps/server/src/services/import/onenote/oauth.ts b/apps/server/src/services/import/onenote/oauth.tsnew file mode 100644index 0000000000..854266842d--- /dev/null+++ b/apps/server/src/services/import/onenote/oauth.ts@@ -0,0 +1,109 @@+/**+ * OAuth 2.0 authorization-code-with-PKCE flow against Microsoft Entra ID, used to obtain a+ * delegated Microsoft Graph access token for the OneNote importer.+ *+ * This is intentionally separate from the user-login OAuth in `open_id.ts`: that one authenticates+ * the Trilium user (OIDC), whereas this one authorizes the app to call the Graph API on the user's+ * behalf and therefore needs to keep (and refresh) the resulting access/refresh tokens.+ *+ * It is a PUBLIC client (no client secret), so PKCE is mandatory. Register an app of type+ * "Mobile and desktop applications" in the Microsoft Entra admin center, allow personal + work/school+ * accounts, add the redirect URI shown in the dialog, grant delegated Graph permissions+ * (Notes.Read, User.Read, offline_access), and expose its client id via TRILIUM_ONENOTE_CLIENT_ID.+ */++import { createHash, randomBytes } from "node:crypto";++/** `/common` lets both personal Microsoft accounts and work/school accounts sign in. */+const AUTHORITY = "https://login.microsoftonline.com/common/oauth2/v2.0";+const AUTHORIZE_ENDPOINT = `${AUTHORITY}/authorize`;+const TOKEN_ENDPOINT = `${AUTHORITY}/token`;++/** offline_access is requested so we receive a refresh token that survives long imports. */+const SCOPES = "offline_access User.Read Notes.Read";++export interface TokenResponse {+ access_token: string;+ refresh_token?: string;+ expires_in: number;+ token_type: string;+ scope?: string;+}++export interface Pkce {+ verifier: string;+ challenge: string;+}++/** The public client id of the registered Microsoft Entra app, or null if not configured. */+export function getClientId(): string | null {+ return process.env.TRILIUM_ONENOTE_CLIENT_ID || null;+}++export function generatePkce(): Pkce {+ const verifier = randomBytes(32).toString("base64url");+ const challenge = createHash("sha256").update(verifier).digest("base64url");+ return { verifier, challenge };+}++export function generateState(): string {+ return randomBytes(16).toString("hex");+}++export function buildAuthorizationUrl({ clientId, redirectUri, state, challenge }: { clientId: string; redirectUri: string; state: string; challenge: string }): string {+ const params = new URLSearchParams({+ client_id: clientId,+ response_type: "code",+ redirect_uri: redirectUri,+ response_mode: "query",+ scope: SCOPES,+ state,+ code_challenge: challenge,+ code_challenge_method: "S256"+ });+ return `${AUTHORIZE_ENDPOINT}?${params.toString()}`;+}++export async function exchangeCodeForToken({ clientId, code, verifier, redirectUri }: { clientId: string; code: string; verifier: string; redirectUri: string }): Promise<TokenResponse> {+ return postToken({+ client_id: clientId,+ grant_type: "authorization_code",+ code,+ code_verifier: verifier,+ redirect_uri: redirectUri,+ scope: SCOPES+ });+}++export async function refreshAccessToken({ clientId, refreshToken }: { clientId: string; refreshToken: string }): Promise<TokenResponse> {+ return postToken({+ client_id: clientId,+ grant_type: "refresh_token",+ refresh_token: refreshToken,+ scope: SCOPES+ });+}++async function postToken(body: Record<string, string>): Promise<TokenResponse> {+ const response = await fetch(TOKEN_ENDPOINT, {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams(body).toString()+ });++ const json = await response.json();+ if (!response.ok || !json.access_token) {+ const detail = json.error_description || json.error || `HTTP ${response.status}`;+ throw new Error(`OneNote token request failed: ${detail}`);+ }+ return json as TokenResponse;+}++export default {+ getClientId,+ generatePkce,+ generateState,+ buildAuthorizationUrl,+ exchangeCodeForToken,+ refreshAccessToken+};