Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): open Windows Markdown files reliably (PRD-8204) (#4343)
mike-inkeepac28f719089d
diff --git a/.changeset/windows-file-association-argv.md b/.changeset/windows-file-association-argv.mdnew file mode 100644index 000000000..cb12df302--- /dev/null+++ b/.changeset/windows-file-association-argv.md@@ -0,0 +1,10 @@+---+"@inkeep/open-knowledge": patch+"@inkeep/open-knowledge-desktop": patch+---++Fix opening Markdown files from Windows Explorer with Open With or double-click. File paths now reach the single-file open flow on cold launch and when OpenKnowledge is already running, without restoring an unrelated project on cold launch. Preserve literal percent signs and escape-like text in file, project, document, and folder names in deep links. Files with a detected enclosing project open in that project's window. Loose files open in standalone windows, which no longer restore or overwrite a sibling file's project tab session.++Previously saved project tabs are preserved. If an older version saved standalone-file tabs for a folder, those tabs may still appear when opening that folder as a project. Close unwanted tabs to save the updated project layout.++Existing Windows installer behavior can make OpenKnowledge the default opener for `.md` and `.mdx` files when you have not explicitly chosen a default in Windows. To choose another app, use Settings → Apps → Default apps.diff --git a/docs/content/features/editor.mdx b/docs/content/features/editor.mdxindex 22cb220df..725b747cc 100644--- a/docs/content/features/editor.mdx+++ b/docs/content/features/editor.mdx@@ -18,6 +18,8 @@ When the file is inside an existing OpenKnowledge project, this opens that projeIt opens in the desktop app when it's installed, and falls back to your browser otherwise (press Ctrl-C in the terminal to end a browser session). Single-file sessions show just the file and the editor — no sidebar, tabs, or project switcher. Discover it any time with `ok --help`.+On Windows, you can also open `.md` and `.mdx` files from Explorer with **Open With → OpenKnowledge**, or double-click them when OpenKnowledge is their default app. With the desktop app installed, these actions open a project or a standalone file using the same rules as `ok <file>`; see [Windows file associations and changing the default app](/docs/reference/what-open-knowledge-writes#installing-and-launching-the-app).+## Document bodyOpen any doc from the sidebar. The body renders as WYSIWYG markdown with familiar conventions: bold / italic / headings / lists / tables / code fences / links / images. Toggle to source mode from the editor controls or with `Cmd+Option+M` to edit the raw markdown directly; both views are bound to the same CRDT document, so they stay in sync across users and AI agents. Switching modes keeps your place — the block you were looking at stays in view either way.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 7820b3687..83dab157b 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -31,7 +31,7 @@ OpenKnowledge installs one of two ways, and the footprint differs a little betweHow the app lands depends on your platform:- **macOS** — a signed `.dmg` you drag into `/Applications`. Because a `.dmg` app can't put a CLI on your `PATH` on its own, first launch asks, in one dialog, whether to register the MCP server with your AI editors and whether to add `ok` to your shell's `PATH` (both covered below, both with your consent).-- **Windows** — a per-user installer: the app lands under `%LOCALAPPDATA%\Programs\`, with no admin prompt. The installer itself adds the bundled `ok` CLI to your **user** `PATH` (a registry value under `HKCU\Environment`) and registers the `openknowledge://` URL scheme under `HKCU\Software\Classes` — both removed by its uninstaller. Your shell startup files are never touched.+- **Windows** — a per-user installer: the app lands under `%LOCALAPPDATA%\Programs\`, with no admin prompt. The installer itself adds the bundled `ok` CLI to your **user** `PATH` (a registry value under `HKCU\Environment`) and registers the `openknowledge://` URL scheme under `HKCU\Software\Classes` — both removed by its uninstaller. It also registers OpenKnowledge for `.md` and `.mdx` files under `HKCU\Software\Classes`, which can make it the default opener when you have not explicitly chosen one in Windows. Uninstall removes its Open With and file-handler registrations but does not restore a previous file-type default. To choose another opener, use **Settings → Apps → Default apps**. Your shell startup files are never touched.- **Linux** — a deb or rpm package: the app installs to `/opt/OpenKnowledge/`, and the package's post-install script symlinks `/usr/bin/ok`, `/usr/bin/open-knowledge`, and `/usr/bin/openknowledge` (plus a desktop entry that registers the `openknowledge://` scheme, and an AppArmor profile on Ubuntu 24.04+ so the Chromium sandbox keeps working). Your shell startup files are never touched.On every platform the app writes app-level state and logs on launch. The table below shows the macOS locations; on Windows the same app-state files live under `%APPDATA%\OpenKnowledge\` and staged updates under `%LOCALAPPDATA%\@inkeepopen-knowledge-desktop-updater\`. On Linux, app state defaults to `~/.config/OpenKnowledge/` and staged updates to `~/.cache/@inkeepopen-knowledge-desktop-updater/` (or the corresponding XDG config and cache directories). The `~/.ok/` paths are the same everywhere.diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 421686e52..33a739ab5 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -378,6 +378,7 @@ import {checkAndRepairProjectMcpOnProjectOpen,type ProjectMcpReclaimCliSurface,} from './project-mcp-reclaim.ts';+import { createProjectSessionHandlers } from './project-session.ts';import { readHeadBranch as readHeadBranchImpl } from './read-head-branch.ts';import {applyReducedTransparency,@@ -424,10 +425,8 @@ import {addRecentFile,addRecentProject,annotateMissing,- emptyProjectSessionState,emptyState,evaluateSchemaCompatibility,- getProjectSessionState,getTerminalDockState,MAX_SUPPORTED_SCHEMA_VERSION,normalizeTerminalRestartSnapshot,@@ -439,7 +438,6 @@ import {saveAppStateToDir,setLastUsedProjectParent,setNoteWindowBounds,- setProjectSessionState,setProjectWindowBounds,setSpellCheckEnabled as setSpellCheckEnabledState,type UpdateChannel,@@ -4668,21 +4666,24 @@ function registerIpcHandlers() {return undefined;});- handle('ok:project:get-session-state', async (event) => {- const win = BrowserWindow.fromWebContents(event.sender);- if (!win || !wm) return emptyProjectSessionState();- const ctx = wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike);- if (!ctx) return emptyProjectSessionState();- return getProjectSessionState(appState, ctx.projectPath);+ const projectSessionHandlers = createProjectSessionHandlers({+ resolveContext: (sender: WebContents) => {+ const win = BrowserWindow.fromWebContents(sender);+ return win && wm+ ? wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike)+ : undefined;+ },+ getState: () => appState,+ saveState: (state) => {+ appState = state;+ saveAppState(appState);+ },});+ handle('ok:project:get-session-state', async (event) => projectSessionHandlers.get(event.sender));+handle('ok:project:set-session-state', async (event, state) => {- const win = BrowserWindow.fromWebContents(event.sender);- if (!win || !wm) return undefined;- const ctx = wm.getContextForBrowserWindow(win as unknown as BrowserWindowLike);- if (!ctx) return undefined;- appState = setProjectSessionState(appState, ctx.projectPath, state);- saveAppState(appState);+ projectSessionHandlers.set(event.sender, state);return undefined;});diff --git a/packages/desktop/src/main/project-session.test.ts b/packages/desktop/src/main/project-session.test.tsnew file mode 100644index 000000000..6458e9ab5--- /dev/null+++ b/packages/desktop/src/main/project-session.test.ts@@ -0,0 +1,98 @@+import { describe, expect, test, vi } from 'vitest';+import { createProjectSessionHandlers } from './project-session.ts';+import {+ emptyProjectSessionState,+ emptyState,+ type ProjectSessionState,+ setProjectSessionState,+} from './state-store.ts';++function sessionWithTab(tabId: string): ProjectSessionState {+ const session = emptyProjectSessionState();+ return {+ ...session,+ panes: session.panes.map((pane) => ({+ ...pane,+ openTabs: [tabId],+ activeTabId: tabId,+ })),+ };+}++function createHarness() {+ const contexts = {+ firstFile: {+ projectPath: '/notes',+ ephemeral: { projectDir: '/tmp/first-file', pid: 11, lockDir: '/tmp/first-file/.ok/local' },+ },+ secondFile: {+ projectPath: '/notes',+ ephemeral: { projectDir: '/tmp/second-file', pid: 12, lockDir: '/tmp/second-file/.ok/local' },+ },+ project: { projectPath: '/notes' },+ otherProject: { projectPath: '/other' },+ unbound: null,+ };+ let state = emptyState();+ const saveState = vi.fn((next: typeof state) => {+ state = next;+ });+ return {+ handlers: createProjectSessionHandlers({+ resolveContext: (sender: keyof typeof contexts) => contexts[sender],+ getState: () => state,+ saveState,+ }),+ saveState,+ getState: () => state,+ seed: (session: ProjectSessionState) => {+ state = setProjectSessionState(state, '/notes', session);+ },+ };+}++describe('project session handlers', () => {+ test('opening a second standalone file does not restore the first file tab', () => {+ const { handlers, saveState } = createHarness();+ handlers.set('firstFile', sessionWithTab('first'));+ expect(handlers.get('secondFile')).toEqual(emptyProjectSessionState());+ expect(saveState).not.toHaveBeenCalled();+ });++ test('standalone files ignore saved sibling tabs from older app versions', () => {+ const { handlers, seed } = createHarness();+ seed(sessionWithTab('old-sibling'));+ expect(handlers.get('firstFile')).toEqual(emptyProjectSessionState());+ expect(handlers.get('secondFile')).toEqual(emptyProjectSessionState());+ });++ test('standalone files cannot overwrite a project session in their parent directory', () => {+ const { handlers, seed, getState, saveState } = createHarness();+ const projectSession = sessionWithTab('project-note');+ seed(projectSession);+ const before = getState();+ handlers.set('firstFile', sessionWithTab('first'));+ handlers.set('secondFile', sessionWithTab('second'));+ expect(getState()).toBe(before);+ expect(handlers.get('project')).toEqual(projectSession);+ expect(saveState).not.toHaveBeenCalled();+ });++ test('project windows persist and restore tabs independently', () => {+ const { handlers, saveState } = createHarness();+ const first = sessionWithTab('project-note');+ const second = sessionWithTab('other-note');+ handlers.set('project', first);+ handlers.set('otherProject', second);+ expect(handlers.get('project')).toEqual(first);+ expect(handlers.get('otherProject')).toEqual(second);+ expect(saveState).toHaveBeenCalledTimes(2);+ });++ test('a window without a project context has no persisted session', () => {+ const { handlers, saveState } = createHarness();+ expect(handlers.get('unbound')).toEqual(emptyProjectSessionState());+ handlers.set('unbound', sessionWithTab('orphan'));+ expect(saveState).not.toHaveBeenCalled();+ });+});diff --git a/packages/desktop/src/main/project-session.ts b/packages/desktop/src/main/project-session.tsnew file mode 100644index 000000000..052e12e71--- /dev/null+++ b/packages/desktop/src/main/project-session.ts@@ -0,0 +1,34 @@+import {+ type AppState,+ emptyProjectSessionState,+ getProjectSessionState,+ type ProjectSessionState,+ setProjectSessionState,+} from './state-store.ts';+import type { WindowManager } from './window-manager.ts';++type ProjectSessionContext = Pick<+ NonNullable<ReturnType<WindowManager['getContextForBrowserWindow']>>,+ 'projectPath' | 'ephemeral'+>;++interface ProjectSessionDeps<Sender> {+ resolveContext: (sender: Sender) => ProjectSessionContext | null | undefined;+ getState: () => AppState;+ saveState: (state: AppState) => void;+}++export function createProjectSessionHandlers<Sender>(deps: ProjectSessionDeps<Sender>) {+ return {+ get(sender: Sender): ProjectSessionState {+ const context = deps.resolveContext(sender);+ if (!context || context.ephemeral) return emptyProjectSessionState();+ return getProjectSessionState(deps.getState(), context.projectPath);+ },+ set(sender: Sender, session: ProjectSessionState): void {+ const context = deps.resolveContext(sender);+ if (!context || context.ephemeral) return;+ deps.saveState(setProjectSessionState(deps.getState(), context.projectPath, session));+ },+ };+}diff --git a/packages/desktop/src/main/url-scheme.argv.test.ts b/packages/desktop/src/main/url-scheme.argv.test.tsnew file mode 100644index 000000000..c6710364e--- /dev/null+++ b/packages/desktop/src/main/url-scheme.argv.test.ts@@ -0,0 +1,240 @@+import { EventEmitter } from 'node:events';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { describe, expect, test, vi } from 'vitest';+import { resolveBootRestoreDecision } from './boot-restore-decision.ts';+import { registerProtocolHandler } from './url-scheme.ts';++const executable = resolve(tmpdir(), 'OpenKnowledge.exe');+const documentPath = (name: string) => resolve(tmpdir(), 'open-knowledge-argv', name);++function makeHandler(+ argv: readonly string[] = [executable],+ options: { platform?: NodeJS.Platform; isPackaged?: boolean } = {},+) {+ const events = new EventEmitter();+ const ready = Promise.withResolvers<void>();+ const openEphemeralFile = vi.fn(async (_filePath: string) => {});+ const openProject = vi.fn(async (_projectPath: string) => null);+ const sendDeepLink = vi.fn();+ const infoLog = vi.fn();+ const scheduled: Array<() => void> = [];+ const control = registerProtocolHandler({+ app: {+ on: events.on.bind(events),+ whenReady: () => ready.promise,+ isPackaged: options.isPackaged ?? true,+ setAsDefaultProtocolClient: () => true,+ removeAsDefaultProtocolClient: () => true,+ },+ focusWindowForProject: () => null,+ openProject,+ openEphemeralFile,+ sendDeepLink,+ getAnyReadyWindow: () => null,+ getInitialArgv: () => argv,+ platform: options.platform ?? 'win32',+ log: { info: infoLog, warn: vi.fn(), error: vi.fn() },+ setTimeout: (cb) => scheduled.push(cb),+ });+ return {+ control,+ openEphemeralFile,+ openProject,+ sendDeepLink,+ infoLog,+ ready: ready.resolve,+ secondInstance: (args: readonly string[]) => events.emit('second-instance', {}, args),+ runScheduled: () => {+ while (scheduled.length > 0) scheduled.shift()?.();+ },+ };+}++const names = [+ 'notes.md',+ 'notes.mdx',+ 'notes.MD',+ 'notes.MDX',+ 'My notes.md',+ '日本語 café.md',+ '100% complete.md',+ 'literal%20name.md',+ 'literal%00name.md',+ 'Q4 #1 & follow-up.md',+];++describe('Windows file-association argv delivery', () => {+ test.each(['cold', 'second-instance'])(+ 'skips unencodable paths and records only counts on %s delivery',+ (delivery) => {+ const file = documentPath('valid + 日本語 😀.md');+ const linkedFile = documentPath('linked.md');+ const args = [+ executable,+ documentPath(`high-${String.fromCharCode(0xd800)}.md`),+ file,+ documentPath(`low-${String.fromCharCode(0xdc00)}.mdx`),+ `openknowledge://open?file=${encodeURIComponent(linkedFile)}`,+ '--inspect=9229',+ ];+ const h = makeHandler(delivery === 'cold' ? args : undefined);+ if (delivery === 'second-instance') {+ h.infoLog.mockClear();+ h.secondInstance(args);+ }+ h.control.drainQueuedUrls();+ expect(h.openEphemeralFile.mock.calls.map(([path]) => path)).toEqual([file, linkedFile]);+ expect(+ h.infoLog.mock.calls.filter(([, message]) => message === '[receive] action=argv-scan'),+ ).toEqual([+ [+ { argvLength: 6, urlArguments: 1, fileArguments: 1, unencodableArguments: 2 },+ '[receive] action=argv-scan',+ ],+ ]);+ },+ );++ test.each(names)('queues cold-start file %s and preserves its exact path', (name) => {+ const file = documentPath(name);+ const h = makeHandler([executable, file]);+ expect(h.openEphemeralFile).not.toHaveBeenCalled();+ h.control.drainQueuedUrls();+ expect(h.openEphemeralFile).toHaveBeenCalledExactlyOnceWith(file);+ expect(h.openProject).not.toHaveBeenCalled();+ });++ test.each(names)('routes second-instance file %s after startup', (name) => {+ const file = documentPath(name);+ const h = makeHandler();+ h.control.drainQueuedUrls();+ h.secondInstance([executable, file]);+ expect(h.openEphemeralFile).toHaveBeenCalledExactlyOnceWith(file);+ expect(h.openProject).not.toHaveBeenCalled();+ });++ test('claims the cold launch synchronously before restore chooses a window', async () => {+ const h = makeHandler([executable, documentPath('notes.md')]);+ expect(h.control.singleFileLaunch()).toBe(true);+ expect(h.control.urlLaunchOwnsWindow()).toBe(true);+ expect(+ await resolveBootRestoreDecision({+ pendingRestore: [{ kind: 'project', projectPath: documentPath('previous-project') }],+ lastOpenedProject: documentPath('last-project'),+ optionHeld: false,+ pathExists: () => true,+ urlLaunchOwnsWindow: h.control.urlLaunchOwnsWindow,+ waitForUrlLaunchSettled: h.control.waitForUrlLaunchSettled,+ }),+ ).toEqual({ clearSnapshot: true, action: 'none' });+ expect(h.openEphemeralFile).not.toHaveBeenCalled();+ });++ test('routes a file when Electron prepends switches to second-instance argv', () => {+ const file = documentPath('notes.md');+ const h = makeHandler();+ h.control.drainQueuedUrls();+ h.secondInstance(['--original-process-start-time=123', file, executable]);+ expect(h.openEphemeralFile).toHaveBeenCalledExactlyOnceWith(file);+ });++ test('queues second-instance files received before the first window is ready', () => {+ const first = documentPath('first.md');+ const second = documentPath('second.mdx');+ const h = makeHandler();+ h.secondInstance([executable, first, second]);+ expect(h.openEphemeralFile).not.toHaveBeenCalled();+ expect(h.control.singleFileLaunch()).toBe(true);+ expect(h.control.urlLaunchOwnsWindow()).toBe(true);+ h.control.drainQueuedUrls();+ expect(h.openEphemeralFile.mock.calls).toEqual([[first], [second]]);+ });++ test('flushes a cold file without an existing ready window', async () => {+ const file = documentPath('notes.md');+ const h = makeHandler([executable, file]);+ h.ready();+ await Promise.resolve();+ h.runScheduled();+ expect(h.openEphemeralFile).toHaveBeenCalledExactlyOnceWith(file);+ });++ test.each(['cold', 'second-instance'])(+ 'ignores non-document arguments on %s delivery',+ (delivery) => {+ const args = [+ executable,+ '--original-process-start-time=123',+ '--inspect=9229',+ `--log-file=${documentPath('electron.md')}`,+ 'relative.md',+ documentPath('main.js'),+ documentPath('program.exe'),+ documentPath('photo.png'),+ documentPath('.md'),+ documentPath('.mdx'),+ 'https://example.com/page.md',+ ];+ const h = makeHandler(delivery === 'cold' ? args : undefined);+ if (delivery === 'second-instance') h.secondInstance(args);+ h.control.drainQueuedUrls();+ expect(h.openEphemeralFile).not.toHaveBeenCalled();+ expect(h.openProject).not.toHaveBeenCalled();+ expect(h.control.urlLaunchOwnsWindow()).toBe(false);+ },+ );++ test.each(['cold', 'second-instance'])(+ 'ignores document and dev-entrypoint arguments on %s delivery when unpackaged',+ (delivery) => {+ const args = [+ executable,+ documentPath('notes.md'),+ documentPath('out/main/index.js'),+ '--inspect=9229',+ ];+ const h = makeHandler(delivery === 'cold' ? args : undefined, { isPackaged: false });+ if (delivery === 'second-instance') h.secondInstance(args);+ h.control.drainQueuedUrls();+ expect(h.openEphemeralFile).not.toHaveBeenCalled();+ expect(h.control.urlLaunchOwnsWindow()).toBe(false);+ },+ );++ test.each(['cold', 'second-instance'])(+ 'preserves custom-scheme single-file delivery on %s startup',+ (delivery) => {+ const file = documentPath('url-note.md');+ const args = [executable, `openknowledge://open?file=${encodeURIComponent(file)}`];+ const h = makeHandler(delivery === 'cold' ? args : undefined);+ if (delivery === 'second-instance') h.secondInstance(args);+ expect(h.control.urlLaunchOwnsWindow()).toBe(true);+ h.control.drainQueuedUrls();+ expect(h.openEphemeralFile).toHaveBeenCalledExactlyOnceWith(file);+ },+ );++ test.each<NodeJS.Platform>(['darwin', 'linux'])(+ 'retains URL-only argv behavior on %s',+ (platform) => {+ const file = documentPath('notes.md');+ const h = makeHandler([executable, file], { platform });+ h.secondInstance([executable, file]);+ h.control.drainQueuedUrls();+ expect(h.openEphemeralFile).not.toHaveBeenCalled();+ expect(h.control.urlLaunchOwnsWindow()).toBe(false);+ },+ );++ test+ .skipIf(process.platform !== 'win32')+ .each(['C:\\Users\\Test User\\Documents\\notes.md', 'D:\\日本語\\100% # & notes.mdx'])(+ 'routes native Windows path %s',+ (file) => {+ const h = makeHandler([executable, file]);+ h.control.drainQueuedUrls();+ expect(h.openEphemeralFile).toHaveBeenCalledExactlyOnceWith(file);+ },+ );+});diff --git a/packages/desktop/src/main/url-scheme.test.ts b/packages/desktop/src/main/url-scheme.test.tsindex 00c511baf..41a38decd 100644--- a/packages/desktop/src/main/url-scheme.test.ts+++ b/packages/desktop/src/main/url-scheme.test.ts@@ -1,3 +1,5 @@+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';import { encodeShareUrl } from '@inkeep/open-knowledge-core';import { describe, expect, test } from 'vitest';import fixture from '../../../../test-support/fixtures/share-url-v1-v2.json';@@ -5,7 +7,12 @@ import {frozenV1CustomSchemeOutcome,frozenV1DecodeShareToken,} from '../../../../test-support/share/frozen-v1-share-reader.test-helper.ts';-import { parseOpenKnowledgeUrl, parseScreenUrl, parseShareUrl } from './url-scheme.ts';+import {+ parseOpenKnowledgeFileUrl,+ parseOpenKnowledgeUrl,+ parseScreenUrl,+ parseShareUrl,+} from './url-scheme.ts';describe('frozen pre-v2 reader compatibility oracle', () => {test.each(fixture.customSchemeCases)('$id keeps its documented old-app outcome', (entry) => {@@ -141,6 +148,23 @@ describe('parseOpenKnowledgeUrl — required params', () => {});describe('parseOpenKnowledgeUrl — null-byte defense', () => {+ test.each([9, 10, 13])('rejects NUL escapes normalized across ASCII %i', (codePoint) => {+ const splitNulEscape = `%${String.fromCharCode(codePoint)}00`;+ const project = encodeURIComponent(resolve(tmpdir(), 'safe-project'));+ const file = encodeURIComponent(resolve(tmpdir(), 'safe-file'));+ for (const kind of ['doc', 'folder']) {+ expect(+ parseOpenKnowledgeUrl(`openknowledge://open?project=${project}&${kind}=x${splitNulEscape}`),+ ).toBeNull();+ }+ expect(+ parseOpenKnowledgeUrl(`openknowledge://open?project=${project}${splitNulEscape}&doc=x.md`),+ ).toBeNull();+ expect(+ parseOpenKnowledgeFileUrl(`openknowledge://open?file=${file}${splitNulEscape}.md`),+ ).toBeNull();+ });+test('rejects literal null byte in raw input', () => {expect(parseOpenKnowledgeUrl('openknowledge://open?project=/abs\x00&doc=x.md')).toBeNull();});@@ -153,17 +177,29 @@ describe('parseOpenKnowledgeUrl — null-byte defense', () => {expect(parseOpenKnowledgeUrl('openknowledge://open?project=/abs&doc=x%00.md')).toBeNull();});- test('rejects double-encoded %2500 in project (layered null-byte smuggle)', () => {+ test('rejects encoded NUL inside an otherwise absolute project', () => {expect(- parseOpenKnowledgeUrl('openknowledge://open?project=%2500/safe/proj&doc=x.md'),+ parseOpenKnowledgeUrl('openknowledge://open?project=/abs/safe%00/proj&doc=x.md'),).toBeNull();});- test('rejects double-encoded %2500 in doc (layered null-byte smuggle)', () => {- expect(parseOpenKnowledgeUrl('openknowledge://open?project=/abs&doc=x%2500.md')).toBeNull();+ test('rejects encoded NUL in folder', () => {+ expect(parseOpenKnowledgeUrl('openknowledge://open?project=/abs&folder=x%00')).toBeNull();});});+describe.each(['doc', 'folder'] as const)('single-encoded %s links', (kind) => {+ test.each(['100% complete', 'literal%20name', 'literal%00name', '日本語 café'])(+ 'preserves project and target names containing %s',+ (name) => {+ const project = resolve(tmpdir(), 'open-knowledge-links', name);+ const target = `notes/${name}`;+ const url = `openknowledge://open?project=${encodeURIComponent(project)}&${kind}=${encodeURIComponent(target)}`;+ expect(parseOpenKnowledgeUrl(url)).toEqual({ host: 'open', project, kind, doc: target });+ },+ );+});+describe('parseOpenKnowledgeUrl — path-traversal defense', () => {test('rejects literal ../ in project', () => {expect(@@ -609,6 +645,10 @@ describe('parseScreenUrl', () => {});});+ test('does not reinterpret a literal escape as a screen name', () => {+ expect(parseScreenUrl('openknowledge://screen?name=install%252Dclaude')).toBeNull();+ });+test('returns null for an unknown screen name', () => {expect(parseScreenUrl('openknowledge://screen?name=admin')).toBeNull();expect(parseScreenUrl('openknowledge://screen?name=')).toBeNull();diff --git a/packages/desktop/src/main/url-scheme.ts b/packages/desktop/src/main/url-scheme.tsindex fb7409f6b..7a44d2c8c 100644--- a/packages/desktop/src/main/url-scheme.ts+++ b/packages/desktop/src/main/url-scheme.ts@@ -10,12 +10,13 @@* delivery path is silently dead. The call site is `packages/desktop/src/main/index.ts`.*/-import { isAbsolute, resolve } from 'node:path';+import { extname, isAbsolute, resolve } from 'node:path';import { parseGitHubShareUrl } from '@inkeep/open-knowledge';import {type CandidateSelection,decodeShareUrl,InvalidShareUrlError,+ SUPPORTED_DOC_EXTENSIONS,UnsupportedShareVersionError,} from '@inkeep/open-knowledge-core';import type {@@ -257,26 +258,17 @@ export function parseOpenKnowledgeUrl(input: string): ParsedOpenKnowledgeUrl | nif (parsed.protocol !== 'openknowledge:') return null;if (parsed.hostname !== 'open') return null;- const rawProject = parsed.searchParams.get('project');+ const project = parsed.searchParams.get('project');const rawDoc = parsed.searchParams.get('doc');const rawFolder = parsed.searchParams.get('folder');- if (!rawProject) return null;+ if (!project) return null;if ((rawDoc == null) === (rawFolder == null)) return null;const kind: 'doc' | 'folder' = rawDoc != null ? 'doc' : 'folder';- const rawTarget = (rawDoc ?? rawFolder) as string;-- let project: string;- let doc: string;- try {- project = decodeURIComponent(rawProject);- doc = decodeURIComponent(rawTarget);- } catch {- return null;- }+ const doc = (rawDoc ?? rawFolder) as string;if (project.includes('\x00') || doc.includes('\x00')) return null;- if (project.length === 0 || doc.length === 0) return null;+ if (doc.length === 0) return null;if (!isAbsolute(project)) return null;if (project.split(/[/\\]/).includes('..')) return null;@@ -311,18 +303,10 @@ export function parseOpenKnowledgeFileUrl(input: string): ParsedOpenKnowledgeFilif (parsed.protocol !== 'openknowledge:') return null;if (parsed.hostname !== 'open') return null;- const rawFile = parsed.searchParams.get('file');- if (!rawFile) return null;-- let file: string;- try {- file = decodeURIComponent(rawFile);- } catch {- return null;- }+ const file = parsed.searchParams.get('file');+ if (!file) return null;if (file.includes('\x00')) return null;- if (file.length === 0) return null;if (!isAbsolute(file)) return null;if (file.split(/[/\\]/).includes('..')) return null;@@ -355,15 +339,8 @@ export function parseScreenUrl(input: string): ParsedScreenUrl | null {if (parsed.protocol !== 'openknowledge:') return null;if (parsed.hostname !== 'screen') return null;- const rawName = parsed.searchParams.get('name');- if (!rawName) return null;-- let name: string;- try {- name = decodeURIComponent(rawName);- } catch {- return null;- }+ const name = parsed.searchParams.get('name');+ if (!name) return null;if (!isScreenTarget(name)) return null;return { host: 'screen', name };@@ -891,20 +868,39 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHandenqueueOrRoute(webpageURL);});- deps.app.on('second-instance', (_event, argv) => {+ const ingestArgv = (argv: readonly string[]): void => {+ let urlArguments = 0;+ let fileArguments = 0;+ let unencodableArguments = 0;for (const arg of argv) {- if (typeof arg === 'string' && arg.startsWith('openknowledge://')) {+ if (arg.startsWith('openknowledge://')) {+ urlArguments += 1;enqueueOrRoute(arg);+ } else if (+ platform === 'win32' &&+ deps.app.isPackaged &&+ isAbsolute(arg) &&+ (SUPPORTED_DOC_EXTENSIONS as readonly string[]).includes(extname(arg).toLowerCase())+ ) {+ if (!arg.isWellFormed()) {+ unencodableArguments += 1;+ continue;+ }+ fileArguments += 1;+ enqueueOrRoute(`openknowledge://open?file=${encodeURIComponent(arg)}`);}}+ deps.log?.info?.(+ { argvLength: argv.length, urlArguments, fileArguments, unencodableArguments },+ '[receive] action=argv-scan',+ );+ };++ deps.app.on('second-instance', (_event, argv) => {+ ingestArgv(argv);});- const initialArgv = deps.getInitialArgv ? deps.getInitialArgv() : [];- for (const arg of initialArgv) {- if (typeof arg === 'string' && arg.startsWith('openknowledge://')) {- enqueueOrRoute(arg);- }- }+ ingestArgv(deps.getInitialArgv?.() ?? []);void deps.app.whenReady().then(() => {if (platform === 'darwin') {