Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): refuse symlinks into private state outside sync (#5394)

Andrew Mikofalvy38ff5bdb5d2f
diff --git a/.changeset/content-symlinks-stay-in-repo.md b/.changeset/content-symlinks-stay-in-repo.md
new file mode 100644
index 000000000..ebd5f229a
--- /dev/null
+++ b/.changeset/content-symlinks-stay-in-repo.md
@@ -0,0 +1,6 @@
+---
+"@inkeep/open-knowledge": patch
+"@inkeep/open-knowledge-desktop": patch
+---
+
+Symlinks can no longer expose or overwrite private `.git` or OpenKnowledge files. Docs, diagrams and attachments that link into them, or outside the project, are not opened, served, saved or duplicated, and `ok clone` and opening a shared branch in a worktree refuse such links.
diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdx
index 4acb31698..5d72fb8a4 100644
--- a/docs/content/reference/cli.mdx
+++ b/docs/content/reference/cli.mdx
@@ -88,6 +88,8 @@ ok clone <owner/repo> -b <branch>
If the branch no longer exists, `ok clone` falls back to the repository's default branch.
+Before checking out any files, `ok clone` checks the repository's symlinks. If a link points outside the repository, at its root, or into a `.git` folder or OpenKnowledge's private state, it removes the clone and names up to five refused links, each with its reason.
+
A **public** repo clones without authentication. For a **private** repo, sign in first:
```bash
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index 20abb01ab..6d5d09695 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -92,7 +92,7 @@ A `reconcile` conflict also carries a `reason`: `merged-with-markers`, `refused-
A write to a document whose file has been deleted returns `urn:ok:error:doc-removed` (409): the edit reached collaborative state, but the disk write was refused rather than recreating the removed file. This is not retryable — the document is gone. Re-create it with `write` if you still want the content.
-A write whose document path cannot be resolved inside the content directory returns `urn:ok:error:path-escape` (400): the edit reached collaborative state, but the disk write was refused. This covers a symlink cycle at the document's own path and a link resolving outside the content directory. It is not retryable — repair the path on disk before writing this content again.
+A write whose document path cannot be resolved inside the content directory returns `urn:ok:error:path-escape` (400): the edit reached collaborative state, but the disk write was refused. This covers a symlink cycle at the document's own path, a link resolving outside the content directory, and a link resolving into a `.git` folder, an OpenKnowledge config folder itself, or its machine-local state. It is not retryable — repair the path on disk before writing this content again.
A write refused because the document's duplication baseline could not be read at the final disk flush returns `urn:ok:error:store-refused` (503): the edit reached collaborative state, but the disk write was refused rather than risk persisting duplicated content. The document file was not updated; the server preserves the edited document, with a copy in its recovery buffer unless that buffer is unavailable or unwritable. Retry only after the filesystem fault is repaired.
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
index 234912636..4f4f51346 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
@@ -587,7 +587,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
['a.md', 'b.md', 'c.md', 'd.md', 'e.md', 'f.md', 'g.md'],
{
description: 'a.md, b.md, c.md, d.md, e.md, and 2 more links',
- id: 'share-switch-unsafe-symlinks:feat/branch-x',
+ id: 'share-branch-unsafe-symlinks:feat/branch-x',
duration: Infinity,
},
],
@@ -596,7 +596,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
['a.md', 'b.md', 'c.md', 'd.md', 'e.md', 'f.md'],
{
description: 'a.md, b.md, c.md, d.md, e.md, and 1 more link',
- id: 'share-switch-unsafe-symlinks:feat/branch-x',
+ id: 'share-branch-unsafe-symlinks:feat/branch-x',
duration: Infinity,
},
],
@@ -605,19 +605,19 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
['a.md', 'b.md', 'c.md', 'd.md', 'e.md'],
{
description: 'a.md, b.md, c.md, d.md, and e.md',
- id: 'share-switch-unsafe-symlinks:feat/branch-x',
+ id: 'share-branch-unsafe-symlinks:feat/branch-x',
duration: Infinity,
},
],
[
'one link',
['a.md'],
- { description: 'a.md', id: 'share-switch-unsafe-symlinks:feat/branch-x', duration: Infinity },
+ { description: 'a.md', id: 'share-branch-unsafe-symlinks:feat/branch-x', duration: Infinity },
],
[
'no listed links',
[],
- { id: 'share-switch-unsafe-symlinks:feat/branch-x', duration: Infinity },
+ { id: 'share-branch-unsafe-symlinks:feat/branch-x', duration: Infinity },
],
])(
'Switch refused for unsafe symlinks (%s) names the links, never suggests a manual switch, and stays open',
@@ -710,7 +710,7 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
await Promise.resolve();
});
await waitFor(() => {
- expect(toastDismiss).toHaveBeenCalledWith('share-switch-unsafe-symlinks:feat/branch-x');
+ expect(toastDismiss).toHaveBeenCalledWith('share-branch-unsafe-symlinks:feat/branch-x');
});
await waitFor(() => {
expect(toastError).toHaveBeenCalledTimes(errorToasts);
@@ -1309,6 +1309,73 @@ describe('ShareBranchSwitchDialog — worktree leg', () => {
expect(calls.open).not.toHaveBeenCalled();
});
+ test('a branch with unsafe symlinks shows its own copy with the refused links and never opens', async () => {
+ const store = createShareReceiveStore();
+ const refusedSymlinkPaths = ['l1', 'l2', 'l3', 'l4', 'l5', 'l6', 'l7'];
+ const { bridge, calls } = makeBridge({
+ checkout: vi.fn(async () => ({
+ ok: false as const,
+ reason: 'unsafe-symlinks' as const,
+ refusedSymlinkPaths,
+ })),
+ });
+ renderDialog(bridge, store);
+
+ const worktreeBtn = await findEnabledWorktreeButton();
+ await act(async () => {
+ fireEvent.click(worktreeBtn);
+ await Promise.resolve();
+ });
+
+ await waitFor(() =>
+ expect(toastError).toHaveBeenCalledWith(
+ 'Did not open feat/branch-x in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again.',
+ {
+ description: 'l1, l2, l3, l4, l5, and 2 more links',
+ id: 'share-branch-unsafe-symlinks:feat/branch-x',
+ duration: Infinity,
+ },
+ ),
+ );
+ expect(calls.open).not.toHaveBeenCalled();
+ });
+
+ test('a worktree open that succeeds after a refusal clears the branch refusal toast', async () => {
+ toastDismiss.mockReset();
+ const store = createShareReceiveStore();
+ const checkout = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: false as const,
+ reason: 'unsafe-symlinks' as const,
+ refusedSymlinkPaths: ['l1'],
+ })
+ .mockResolvedValue({
+ ok: true as const,
+ path: '/repo/.ok/worktrees/feat-branch-x',
+ created: true as const,
+ });
+ const { bridge } = makeBridge({ checkout });
+ renderDialog(bridge, store);
+
+ const first = await findEnabledWorktreeButton();
+ await act(async () => {
+ fireEvent.click(first);
+ await Promise.resolve();
+ });
+ await waitFor(() => expect(toastError).toHaveBeenCalled());
+ expect(toastDismiss).not.toHaveBeenCalledWith('share-branch-unsafe-symlinks:feat/branch-x');
+
+ const second = await findEnabledWorktreeButton();
+ await act(async () => {
+ fireEvent.click(second);
+ await Promise.resolve();
+ });
+ await waitFor(() =>
+ expect(toastDismiss).toHaveBeenCalledWith('share-branch-unsafe-symlinks:feat/branch-x'),
+ );
+ });
+
test('a not-found fetch failure shows the not-found copy, not the connection toast', async () => {
const store = createShareReceiveStore();
const { bridge } = makeBridge({
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.tsx b/packages/app/src/components/ShareBranchSwitchDialog.tsx
index 3eb31a516..a5d2f0685 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.tsx
@@ -91,8 +91,8 @@ function isBranchSwitchPayload(
const REFUSED_LINKS_SHOWN = 5;
-function shareSwitchRefusalToastId(branch: string): string {
- return `share-switch-unsafe-symlinks:${branch}`;
+function shareBranchRefusalToastId(branch: string): string {
+ return `share-branch-unsafe-symlinks:${branch}`;
}
export function ShareBranchSwitchDialog({
@@ -100,6 +100,16 @@ export function ShareBranchSwitchDialog({
store = shareReceiveStore,
}: ShareBranchSwitchDialogProps) {
const { t } = useLingui();
+
+ function refusedLinksDescription(paths: readonly string[]): string | undefined {
+ const shownPaths = paths.slice(0, REFUSED_LINKS_SHOWN);
+ const hiddenCount = paths.length - shownPaths.length;
+ const listed =
+ hiddenCount > 0
+ ? [...shownPaths, t`${plural(hiddenCount, { one: '# more link', other: '# more links' })}`]
+ : shownPaths;
+ return listed.length === 0 ? undefined : formatToolList(listed, i18n.locale);
+ }
const payload = useSyncExternalStore(store.subscribe, store.getSnapshot, () => null);
const [branchSwitchState, setBranchSwitchState] =
useState<BranchSwitchDialogState>(initialBranchSwitchState);
@@ -314,22 +324,13 @@ export function ShareBranchSwitchDialog({
}
return next;
});
- const refusalToastId = shareSwitchRefusalToastId(shareBranch);
+ const refusalToastId = shareBranchRefusalToastId(shareBranch);
if (toastReason !== 'unsafe-symlinks') toast.dismiss(refusalToastId);
if (toastReason === 'unsafe-symlinks') {
- const shownPaths = refusedPaths.slice(0, REFUSED_LINKS_SHOWN);
- const hiddenCount = refusedPaths.length - shownPaths.length;
- const listed =
- hiddenCount > 0
- ? [
- ...shownPaths,
- t`${plural(hiddenCount, { one: '# more link', other: '# more links' })}`,
- ]
- : shownPaths;
toast.error(
t`Did not switch to ${shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again.`,
{
- description: listed.length === 0 ? undefined : formatToolList(listed, i18n.locale),
+ description: refusedLinksDescription(refusedPaths),
id: refusalToastId,
duration: Infinity,
},
@@ -353,7 +354,7 @@ export function ShareBranchSwitchDialog({
err instanceof Error ? err.message : err,
);
setBranchSwitchState((prev) => applyCheckoutOutcome(prev, null).state);
- toast.dismiss(shareSwitchRefusalToastId(shareBranch));
+ toast.dismiss(shareBranchRefusalToastId(shareBranch));
toast.error(t`Could not switch to ${shareBranch}. Try switching manually.`);
});
}
@@ -472,6 +473,17 @@ export function ShareBranchSwitchDialog({
),
);
return;
+ case 'unsafe-symlinks': {
+ toast.error(
+ t`Did not open ${shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again.`,
+ {
+ description: refusedLinksDescription(failure.paths),
+ id: shareBranchRefusalToastId(shareBranch),
+ duration: Infinity,
+ },
+ );
+ return;
+ }
case 'proxy-null':
case 'error':
toast.error(t`Could not open ${shareBranch} in a worktree. Try again.`);
@@ -501,6 +513,9 @@ export function ShareBranchSwitchDialog({
}
return next;
});
+ if (failureSideEffect?.reason !== 'unsafe-symlinks') {
+ toast.dismiss(shareBranchRefusalToastId(shareBranch));
+ }
if (failureSideEffect !== undefined) {
console.log(
formatReceiveLog({
diff --git a/packages/app/src/lib/share/branch-switch-flow.test.ts b/packages/app/src/lib/share/branch-switch-flow.test.ts
index 37a5c2981..53d2e2be9 100644
--- a/packages/app/src/lib/share/branch-switch-flow.test.ts
+++ b/packages/app/src/lib/share/branch-switch-flow.test.ts
@@ -719,6 +719,20 @@ describe('applyWorktreeCheckoutOutcome (worktree leg)', () => {
});
});
+ test('a branch with unsafe symlinks stays open and carries the refused paths to the toast', () => {
+ const result = applyWorktreeCheckoutOutcome(creating, {
+ ok: false,
+ reason: 'unsafe-symlinks',
+ refusedSymlinkPaths: ['notes/leak.md', 'notes/root'],
+ });
+ expect(result.state).toEqual({ phase: 'ready', info: cleanInfo() });
+ expect(result.sideEffect).toEqual({
+ kind: 'toast',
+ reason: 'unsafe-symlinks',
+ paths: ['notes/leak.md', 'notes/root'],
+ });
+ });
+
test('branch-not-found dismisses with the branch-gone toast signal (terminal, mirrors the switch leg)', () => {
const result = applyWorktreeCheckoutOutcome(creating, {
ok: false,
diff --git a/packages/app/src/lib/share/branch-switch-flow.ts b/packages/app/src/lib/share/branch-switch-flow.ts
index 2ec41a678..a88f57584 100644
--- a/packages/app/src/lib/share/branch-switch-flow.ts
+++ b/packages/app/src/lib/share/branch-switch-flow.ts
@@ -296,7 +296,15 @@ export type WorktreeCheckoutSideEffect =
}
| {
readonly kind: 'toast';
- readonly reason: Exclude<WorktreeCheckoutSideEffectReason, 'project-scope-unavailable'>;
+ readonly reason: 'unsafe-symlinks';
+ readonly paths: readonly string[];
+ }
+ | {
+ readonly kind: 'toast';
+ readonly reason: Exclude<
+ WorktreeCheckoutSideEffectReason,
+ 'project-scope-unavailable' | 'unsafe-symlinks'
+ >;
readonly helper?: string;
readonly authFailed?: true;
readonly notFoundAsIdentity?: true;
@@ -337,6 +345,12 @@ export function applyWorktreeCheckoutOutcome(
},
};
}
+ if (result.reason === 'unsafe-symlinks') {
+ return {
+ state: { phase: 'ready', info: state.info },
+ sideEffect: { kind: 'toast', reason: result.reason, paths: result.refusedSymlinkPaths },
+ };
+ }
return {
state: { phase: 'ready', info: state.info },
sideEffect: {
diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.json
index 32d776339..11f07afac 100644
--- a/packages/app/src/locales/ar/messages.json
+++ b/packages/app/src/locales/ar/messages.json
@@ -3727,6 +3727,11 @@
" بدلاً من نسخة الإضافة — وتتوقف عن متابعة تحديثات الإضافة."
],
"_6FVBz": ["الانتقال إلى التبويب 1-8"],
+ "_6cS9O": [
+ "لم يتم فتح ",
+ ["shareBranch"],
+ " في شجرة عمل: يحتوي على رابط رمزي يشير إلى خارج المستودع أو إلى ملفات خاصة أو إلى موضع لا يمكن التحقق منه. عادةً يجب على من دفع الفرع إصلاح الرابط. إذا تعذّرت قراءة مجلد على هذا الكمبيوتر، فاجعله قابلًا للقراءة وحاول مرة أخرى."
+ ],
"_7UQ7y": ["الكلمة كاملة"],
"_8quCH": ["من قالب"],
"_902BE": [
diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.po
index 3b7f69b16..ffd6537c3 100644
--- a/packages/app/src/locales/ar/messages.po
+++ b/packages/app/src/locales/ar/messages.po
@@ -5172,6 +5172,10 @@ msgstr "مخطط من مصدر Mermaid — انسيابي، تسلسلي، أص
msgid "Diagram view mode"
msgstr "وضع عرض المخطط"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "لم يتم فتح {shareBranch} في شجرة عمل: يحتوي على رابط رمزي يشير إلى خارج المستودع أو إلى ملفات خاصة أو إلى موضع لا يمكن التحقق منه. عادةً يجب على من دفع الفرع إصلاح الرابط. إذا تعذّرت قراءة مجلد على هذا الكمبيوتر، فاجعله قابلًا للقراءة وحاول مرة أخرى."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "لم يتم التبديل إلى {shareBranch}: يحتوي على رابط رمزي يشير إلى خارج المستودع أو إلى ملفات خاصة أو إلى موضع لا يمكن التحقق منه. عادةً يجب على من دفع الفرع إصلاح الرابط. إذا تعذّرت قراءة مجلد على هذا الكمبيوتر، فاجعله قابلًا للقراءة وحاول مرة أخرى."
diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.json
index 5993c4edf..c68eae0b6 100644
--- a/packages/app/src/locales/bn/messages.json
+++ b/packages/app/src/locales/bn/messages.json
@@ -3145,6 +3145,10 @@
" প্লাগইনের বদলে ব্যবহার করে — সেটি আর প্লাগইনের আপডেট অনুসরণ করে না।"
],
"_6FVBz": ["ট্যাব ১-৮-এ যান"],
+ "_6cS9O": [
+ ["shareBranch"],
+ " কোনো ওয়ার্কট্রিতে খোলা হয়নি: এতে এমন একটি সিমলিংক আছে যা রিপোজিটরির বাইরে, ব্যক্তিগত ফাইলের দিকে, অথবা এমন কোথাও নির্দেশ করে যা যাচাই করা যায় না। সাধারণত যিনি ব্রাঞ্চটি পাঠিয়েছেন তাঁকেই লিংকটি ঠিক করতে হবে। এই কম্পিউটারের কোনো ফোল্ডার পড়া না গেলে সেটি পড়ার যোগ্য করে আবার চেষ্টা করুন।"
+ ],
"_7UQ7y": ["পূর্ণ শব্দ"],
"_8quCH": ["টেমপ্লেট থেকে"],
"_902BE": [
diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.po
index 1a2365661..766b3a9e5 100644
--- a/packages/app/src/locales/bn/messages.po
+++ b/packages/app/src/locales/bn/messages.po
@@ -5168,6 +5168,10 @@ msgstr "Mermaid সোর্স থেকে চিত্র — ফ্লোচ
msgid "Diagram view mode"
msgstr "চিত্র দেখার মোড"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "{shareBranch} কোনো ওয়ার্কট্রিতে খোলা হয়নি: এতে এমন একটি সিমলিংক আছে যা রিপোজিটরির বাইরে, ব্যক্তিগত ফাইলের দিকে, অথবা এমন কোথাও নির্দেশ করে যা যাচাই করা যায় না। সাধারণত যিনি ব্রাঞ্চটি পাঠিয়েছেন তাঁকেই লিংকটি ঠিক করতে হবে। এই কম্পিউটারের কোনো ফোল্ডার পড়া না গেলে সেটি পড়ার যোগ্য করে আবার চেষ্টা করুন।"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "{shareBranch}-এ যাওয়া হয়নি: এতে এমন একটি সিমলিংক আছে যা রিপোজিটরির বাইরে, ব্যক্তিগত ফাইলের দিকে, অথবা এমন কোথাও নির্দেশ করে যা যাচাই করা যায় না। সাধারণত যিনি ব্রাঞ্চটি পাঠিয়েছেন তাঁকেই লিংকটি ঠিক করতে হবে। এই কম্পিউটারের কোনো ফোল্ডার পড়া না গেলে সেটি পড়ার যোগ্য করে আবার চেষ্টা করুন।"
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 1d110d5b6..410a16bed 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -3232,6 +3232,11 @@
" uses instead of the plugin's — it stops tracking plugin updates."
],
"_6FVBz": ["Jump to tab 1-8"],
+ "_6cS9O": [
+ "Did not open ",
+ ["shareBranch"],
+ " in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+ ],
"_7UQ7y": ["Whole word"],
"_8quCH": ["From template"],
"_902BE": [
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index dddfd355c..61e45d160 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -5172,6 +5172,10 @@ msgstr "Diagram from Mermaid source — flowchart, sequence, class, state, ER, g
msgid "Diagram view mode"
msgstr "Diagram view mode"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.json
index bbb600b4c..64a4cb3c3 100644
--- a/packages/app/src/locales/es/messages.json
+++ b/packages/app/src/locales/es/messages.json
@@ -3740,6 +3740,11 @@
" usa en lugar de la del plugin; deja de seguir las actualizaciones del plugin."
],
"_6FVBz": ["Ir a las pestañas 1-8"],
+ "_6cS9O": [
+ "No se abrió ",
+ ["shareBranch"],
+ " en un worktree: tiene un enlace simbólico que apunta fuera del repositorio, a archivos privados o a un lugar que no se puede comprobar. Normalmente quien envió la rama tiene que corregir el enlace. Si no se puede leer una carpeta de este equipo, hazla legible y vuelve a intentarlo."
+ ],
"_7UQ7y": ["Palabra completa"],
"_8quCH": ["Desde plantilla"],
"_902BE": [
diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.po
index f765d5e2d..99d1ec99f 100644
--- a/packages/app/src/locales/es/messages.po
+++ b/packages/app/src/locales/es/messages.po
@@ -5172,6 +5172,10 @@ msgstr "Diagrama a partir de código Mermaid: de flujo, de secuencia, de clases,
msgid "Diagram view mode"
msgstr "Modo de vista del diagrama"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "No se abrió {shareBranch} en un worktree: tiene un enlace simbólico que apunta fuera del repositorio, a archivos privados o a un lugar que no se puede comprobar. Normalmente quien envió la rama tiene que corregir el enlace. Si no se puede leer una carpeta de este equipo, hazla legible y vuelve a intentarlo."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "No se cambió a {shareBranch}: tiene un enlace simbólico que apunta fuera del repositorio, a archivos privados o a un lugar que no se puede comprobar. Normalmente quien envió la rama tiene que corregir el enlace. Si no se puede leer una carpeta de este equipo, hazla legible y vuelve a intentarlo."
diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.json
index cc485f41d..2b681c6da 100644
--- a/packages/app/src/locales/fr/messages.json
+++ b/packages/app/src/locales/fr/messages.json
@@ -3791,6 +3791,11 @@
" utilise à la place de celle du plugin — elle ne suit plus les mises à jour du plugin."
],
"_6FVBz": ["Aller aux onglets 1 à 8"],
+ "_6cS9O": [
+ "L'ouverture de ",
+ ["shareBranch"],
+ " dans un worktree n'a pas eu lieu : cette branche contient un lien symbolique qui pointe hors du dépôt, vers des fichiers privés ou vers un emplacement qui ne peut pas être vérifié. En général, la personne qui a poussé la branche doit corriger le lien. Si un dossier de cet ordinateur ne peut pas être lu, rendez-le lisible et réessayez."
+ ],
"_7UQ7y": ["Mot entier"],
"_8quCH": ["À partir d'un modèle"],
"_902BE": [
diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.po
index 27de09b7c..141d88414 100644
--- a/packages/app/src/locales/fr/messages.po
+++ b/packages/app/src/locales/fr/messages.po
@@ -5172,6 +5172,10 @@ msgstr "Diagramme issu d'une source Mermaid — organigramme, séquence, classes
msgid "Diagram view mode"
msgstr "Mode d'affichage du diagramme"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "L'ouverture de {shareBranch} dans un worktree n'a pas eu lieu : cette branche contient un lien symbolique qui pointe hors du dépôt, vers des fichiers privés ou vers un emplacement qui ne peut pas être vérifié. En général, la personne qui a poussé la branche doit corriger le lien. Si un dossier de cet ordinateur ne peut pas être lu, rendez-le lisible et réessayez."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "Le passage à {shareBranch} n'a pas eu lieu : cette branche contient un lien symbolique qui pointe hors du dépôt, vers des fichiers privés ou vers un emplacement qui ne peut pas être vérifié. En général, la personne qui a poussé la branche doit corriger le lien. Si un dossier de cet ordinateur ne peut pas être lu, rendez-le lisible et réessayez."
diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.json
index 85850b613..a0bd5b3c8 100644
--- a/packages/app/src/locales/hi/messages.json
+++ b/packages/app/src/locales/hi/messages.json
@@ -3136,6 +3136,10 @@
" प्लगइन की जगह इस्तेमाल करता है — यह प्लगइन के अपडेट लेना बंद कर देती है।"
],
"_6FVBz": ["टैब 1-8 पर जाएँ"],
+ "_6cS9O": [
+ ["shareBranch"],
+ " को किसी वर्कट्री में नहीं खोला गया: इसमें एक सिमलिंक है जो रिपॉज़िटरी के बाहर, निजी फ़ाइलों की ओर, या ऐसी जगह की ओर इशारा करता है जिसकी जाँच नहीं की जा सकती। आमतौर पर जिसने ब्रांच भेजी है उसे ही लिंक ठीक करना होगा। अगर इस कंप्यूटर का कोई फ़ोल्डर पढ़ा नहीं जा सकता, तो उसे पढ़ने योग्य बनाएँ और फिर से कोशिश करें।"
+ ],
"_7UQ7y": ["पूरा शब्द"],
"_8quCH": ["टेम्पलेट से"],
"_902BE": [
diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.po
index 1e3598a0b..1771331f6 100644
--- a/packages/app/src/locales/hi/messages.po
+++ b/packages/app/src/locales/hi/messages.po
@@ -5168,6 +5168,10 @@ msgstr "Mermaid स्रोत से आरेख — फ़्लोचार
msgid "Diagram view mode"
msgstr "आरेख दृश्य मोड"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "{shareBranch} को किसी वर्कट्री में नहीं खोला गया: इसमें एक सिमलिंक है जो रिपॉज़िटरी के बाहर, निजी फ़ाइलों की ओर, या ऐसी जगह की ओर इशारा करता है जिसकी जाँच नहीं की जा सकती। आमतौर पर जिसने ब्रांच भेजी है उसे ही लिंक ठीक करना होगा। अगर इस कंप्यूटर का कोई फ़ोल्डर पढ़ा नहीं जा सकता, तो उसे पढ़ने योग्य बनाएँ और फिर से कोशिश करें।"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "{shareBranch} पर स्विच नहीं किया गया: इसमें एक सिमलिंक है जो रिपॉज़िटरी के बाहर, निजी फ़ाइलों की ओर, या ऐसी जगह की ओर इशारा करता है जिसकी जाँच नहीं की जा सकती। आमतौर पर जिसने ब्रांच भेजी है उसे ही लिंक ठीक करना होगा। अगर इस कंप्यूटर का कोई फ़ोल्डर पढ़ा नहीं जा सकता, तो उसे पढ़ने योग्य बनाएँ और फिर से कोशिश करें।"
diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.json
index 7b3b6f30c..9d16ff734 100644
--- a/packages/app/src/locales/id/messages.json
+++ b/packages/app/src/locales/id/messages.json
@@ -3246,6 +3246,11 @@
" alih-alih milik plugin — salinan itu berhenti mengikuti pembaruan plugin."
],
"_6FVBz": ["Lompat ke tab 1-8"],
+ "_6cS9O": [
+ "Tidak membuka ",
+ ["shareBranch"],
+ " di worktree: cabang ini memiliki symlink yang mengarah ke luar repositori, ke berkas pribadi, atau ke tempat yang tidak dapat diperiksa. Biasanya orang yang melakukan push cabang ini yang harus memperbaiki tautannya. Jika sebuah folder di komputer ini tidak dapat dibaca, buat agar dapat dibaca lalu coba lagi."
+ ],
"_7UQ7y": ["Kata utuh"],
"_8quCH": ["Dari templat"],
"_902BE": [
diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.po
index dede9c847..e592e77fe 100644
--- a/packages/app/src/locales/id/messages.po
+++ b/packages/app/src/locales/id/messages.po
@@ -5168,6 +5168,10 @@ msgstr "Diagram dari sumber Mermaid — bagan alir, sekuens, kelas, keadaan, ER,
msgid "Diagram view mode"
msgstr "Mode tampilan diagram"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "Tidak membuka {shareBranch} di worktree: cabang ini memiliki symlink yang mengarah ke luar repositori, ke berkas pribadi, atau ke tempat yang tidak dapat diperiksa. Biasanya orang yang melakukan push cabang ini yang harus memperbaiki tautannya. Jika sebuah folder di komputer ini tidak dapat dibaca, buat agar dapat dibaca lalu coba lagi."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "Tidak beralih ke {shareBranch}: cabang ini memiliki symlink yang mengarah ke luar repositori, ke berkas pribadi, atau ke tempat yang tidak dapat diperiksa. Biasanya orang yang melakukan push cabang ini yang harus memperbaiki tautannya. Jika sebuah folder di komputer ini tidak dapat dibaca, buat agar dapat dibaca lalu coba lagi."
diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.json
index 4e6b92092..54690b9c3 100644
--- a/packages/app/src/locales/ko/messages.json
+++ b/packages/app/src/locales/ko/messages.json
@@ -3104,6 +3104,11 @@
"이(가) 플러그인 대신 그 복사본을 사용합니다. 복사본은 플러그인 업데이트를 더 이상 따르지 않습니다."
],
"_6FVBz": ["1~8번 탭으로 이동"],
+ "_6cS9O": [
+ "워크트리에서 ",
+ ["shareBranch"],
+ " 브랜치를 열지 않았습니다. 저장소 밖이나 비공개 파일, 또는 확인할 수 없는 위치를 가리키는 심볼릭 링크가 있습니다. 보통 브랜치를 푸시한 사람이 링크를 수정해야 합니다. 이 컴퓨터의 폴더를 읽을 수 없다면 읽을 수 있게 한 뒤 다시 시도하세요."
+ ],
"_7UQ7y": ["전체 단어"],
"_8quCH": ["템플릿에서"],
"_902BE": [
diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.po
index 2034d5552..d48ef5f2d 100644
--- a/packages/app/src/locales/ko/messages.po
+++ b/packages/app/src/locales/ko/messages.po
@@ -5172,6 +5172,10 @@ msgstr "Mermaid 소스에서 만든 다이어그램입니다. 플로차트, 시
msgid "Diagram view mode"
msgstr "다이어그램 보기 모드"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "워크트리에서 {shareBranch} 브랜치를 열지 않았습니다. 저장소 밖이나 비공개 파일, 또는 확인할 수 없는 위치를 가리키는 심볼릭 링크가 있습니다. 보통 브랜치를 푸시한 사람이 링크를 수정해야 합니다. 이 컴퓨터의 폴더를 읽을 수 없다면 읽을 수 있게 한 뒤 다시 시도하세요."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "{shareBranch}(으)로 전환하지 않았습니다. 저장소 밖이나 비공개 파일, 또는 확인할 수 없는 위치를 가리키는 심볼릭 링크가 있습니다. 보통 브랜치를 푸시한 사람이 링크를 수정해야 합니다. 이 컴퓨터의 폴더를 읽을 수 없다면 읽을 수 있게 한 뒤 다시 시도하세요."
diff --git a/packages/app/src/locales/pl/messages.json b/packages/app/src/locales/pl/messages.json
index 4c2d57346..e08f4d785 100644
--- a/packages/app/src/locales/pl/messages.json
+++ b/packages/app/src/locales/pl/messages.json
@@ -3826,6 +3826,11 @@
" używa zamiast kopii z wtyczki — to zatrzymuje śledzenie aktualizacji wtyczki."
],
"_6FVBz": ["Przejdź do karty 1-8"],
+ "_6cS9O": [
+ "Nie otwarto ",
+ ["shareBranch"],
+ " w worktree: gałąź zawiera dowiązanie symboliczne wskazujące poza repozytorium, na prywatne pliki albo w miejsce, którego nie da się sprawdzić. Zwykle dowiązanie musi poprawić osoba, która wypchnęła gałąź. Jeśli nie da się odczytać folderu na tym komputerze, nadaj mu uprawnienia do odczytu i spróbuj ponownie."
+ ],
"_7UQ7y": ["Całe słowo"],
"_8quCH": ["Z szablonu"],
"_902BE": [
diff --git a/packages/app/src/locales/pl/messages.po b/packages/app/src/locales/pl/messages.po
index ec9bcaf61..8e4e803b0 100644
--- a/packages/app/src/locales/pl/messages.po
+++ b/packages/app/src/locales/pl/messages.po
@@ -5172,6 +5172,10 @@ msgstr "Diagram ze źródła Mermaid — schemat przepływu, sekwencji, klas, st
msgid "Diagram view mode"
msgstr "Tryb widoku diagramu"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "Nie otwarto {shareBranch} w worktree: gałąź zawiera dowiązanie symboliczne wskazujące poza repozytorium, na prywatne pliki albo w miejsce, którego nie da się sprawdzić. Zwykle dowiązanie musi poprawić osoba, która wypchnęła gałąź. Jeśli nie da się odczytać folderu na tym komputerze, nadaj mu uprawnienia do odczytu i spróbuj ponownie."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "Nie przełączono na {shareBranch}: gałąź zawiera dowiązanie symboliczne wskazujące poza repozytorium, na prywatne pliki albo w miejsce, którego nie da się sprawdzić. Zwykle dowiązanie musi poprawić osoba, która wypchnęła gałąź. Jeśli nie da się odczytać folderu na tym komputerze, nadaj mu uprawnienia do odczytu i spróbuj ponownie."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 2ce57878f..4fa4d6beb 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -3232,6 +3232,11 @@
" ũśēś ĩńśţēàď ōƒ ţĥē ƥĺũĝĩń'ś — ĩţ śţōƥś ţŕàćķĩńĝ ƥĺũĝĩń ũƥďàţēś."
],
"_6FVBz": ["ĵũḿƥ ţō ţàƀ 1-8"],
+ "_6cS9O": [
+ "Ďĩď ńōţ ōƥēń ",
+ ["shareBranch"],
+ " ĩń à ŵōŕķţŕēē: ĩţ ĥàś à śŷḿĺĩńķ ƥōĩńţĩńĝ ōũţśĩďē ţĥē ŕēƥōśĩţōŕŷ, ĩńţō ƥŕĩvàţē ƒĩĺēś, ōŕ śōḿēŵĥēŕē ţĥàţ ćàńńōţ ƀē ćĥēćķēď. Ũśũàĺĺŷ ŵĥōēvēŕ ƥũśĥēď ţĥē ƀŕàńćĥ ĥàś ţō ƒĩx ţĥē ĺĩńķ. Ĩƒ à ƒōĺďēŕ ōń ţĥĩś ćōḿƥũţēŕ ćàńńōţ ƀē ŕēàď, ḿàķē ĩţ ŕēàďàƀĺē àńď ţŕŷ àĝàĩń."
+ ],
"_7UQ7y": ["Ŵĥōĺē ŵōŕď"],
"_8quCH": ["Ƒŕōḿ ţēḿƥĺàţē"],
"_902BE": [
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index b2a8fbe08..0c0d2f876 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -5168,6 +5168,10 @@ msgstr ""
msgid "Diagram view mode"
msgstr ""
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr ""
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr ""
diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.json
index 431f1d48e..2f2708e90 100644
--- a/packages/app/src/locales/pt-BR/messages.json
+++ b/packages/app/src/locales/pt-BR/messages.json
@@ -484,7 +484,7 @@
"461Vg9": [
"A troca para ",
["shareBranch"],
- " não foi feita: ela tem um link simbólico apontando para fora do repositório, para arquivos privados ou para um lugar que não pode ser verificado. Normalmente quem enviou o branch precisa corrigir o link. Se uma pasta deste computador não puder ser lida, torne-a legível e tente novamente."
+ " não foi feita: ela tem um link simbólico apontando para fora do repositório, para arquivos privados ou para um lugar que não pode ser verificado. Normalmente quem enviou o ramo precisa corrigir o link. Se uma pasta deste computador não puder ser lida, torne-a legível e tente novamente."
],
"46YgRZ": ["Adicionar bloco abaixo"],
"484LKL": ["Remover o link"],
@@ -3676,6 +3676,10 @@
" usa no lugar da do plugin — ela deixa de acompanhar as atualizações do plugin."
],
"_6FVBz": ["Ir para as abas 1-8"],
+ "_6cS9O": [
+ ["shareBranch"],
+ " não foi aberto em um worktree: o ramo tem um link simbólico apontando para fora do repositório, para arquivos privados ou para um lugar que não pode ser verificado. Normalmente quem enviou o ramo precisa corrigir o link. Se uma pasta deste computador não puder ser lida, torne-a legível e tente novamente."
+ ],
"_7UQ7y": ["Palavra inteira"],
"_8quCH": ["A partir de um modelo"],
"_902BE": [
diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.po
index 5f24cbfdd..f05901250 100644
--- a/packages/app/src/locales/pt-BR/messages.po
+++ b/packages/app/src/locales/pt-BR/messages.po
@@ -5168,9 +5168,13 @@ msgstr "Diagrama a partir de código Mermaid — fluxograma, sequência, classes
msgid "Diagram view mode"
msgstr "Modo de visualização do diagrama"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "{shareBranch} não foi aberto em um worktree: o ramo tem um link simbólico apontando para fora do repositório, para arquivos privados ou para um lugar que não pode ser verificado. Normalmente quem enviou o ramo precisa corrigir o link. Se uma pasta deste computador não puder ser lida, torne-a legível e tente novamente."
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
-msgstr "A troca para {shareBranch} não foi feita: ela tem um link simbólico apontando para fora do repositório, para arquivos privados ou para um lugar que não pode ser verificado. Normalmente quem enviou o branch precisa corrigir o link. Se uma pasta deste computador não puder ser lida, torne-a legível e tente novamente."
+msgstr "A troca para {shareBranch} não foi feita: ela tem um link simbólico apontando para fora do repositório, para arquivos privados ou para um lugar que não pode ser verificado. Normalmente quem enviou o ramo precisa corrigir o link. Se uma pasta deste computador não puder ser lida, torne-a legível e tente novamente."
#: src/components/AgentDiffPane.tsx
#: src/components/TimelineDiffPane.tsx
diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.json
index da8c0d7c9..1d3a7f70d 100644
--- a/packages/app/src/locales/ur/messages.json
+++ b/packages/app/src/locales/ur/messages.json
@@ -3298,6 +3298,10 @@
" پلگ اِن کی بجائے استعمال کرتا ہے — وہ نقل پلگ اِن کی تازہ کاریوں کی پیروی چھوڑ دیتی ہے۔"
],
"_6FVBz": ["ٹیب 1-8 پر جائیں"],
+ "_6cS9O": [
+ ["shareBranch"],
+ " کسی ورک ٹری میں نہیں کھولا گیا: اس میں ایک سِم لنک ہے جو ریپازٹری سے باہر، نجی فائلوں کی طرف، یا ایسی جگہ کی طرف اشارہ کرتا ہے جس کی جانچ نہیں ہو سکتی۔ عام طور پر جس نے برانچ پُش کی ہے اسی کو لنک درست کرنا ہوگا۔ اگر اس کمپیوٹر کا کوئی فولڈر پڑھا نہیں جا سکتا تو اسے پڑھنے کے قابل بنائیں اور دوبارہ کوشش کریں۔"
+ ],
"_7UQ7y": ["پورا لفظ"],
"_8quCH": ["ٹیمپلیٹ سے"],
"_902BE": [
diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.po
index aa0717649..f98c0ea42 100644
--- a/packages/app/src/locales/ur/messages.po
+++ b/packages/app/src/locales/ur/messages.po
@@ -5172,6 +5172,10 @@ msgstr "Mermaid سورس سے خاکہ — فلو چارٹ، سیکوئنس، ک
msgid "Diagram view mode"
msgstr "خاکے کا منظر موڈ"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "{shareBranch} کسی ورک ٹری میں نہیں کھولا گیا: اس میں ایک سِم لنک ہے جو ریپازٹری سے باہر، نجی فائلوں کی طرف، یا ایسی جگہ کی طرف اشارہ کرتا ہے جس کی جانچ نہیں ہو سکتی۔ عام طور پر جس نے برانچ پُش کی ہے اسی کو لنک درست کرنا ہوگا۔ اگر اس کمپیوٹر کا کوئی فولڈر پڑھا نہیں جا سکتا تو اسے پڑھنے کے قابل بنائیں اور دوبارہ کوشش کریں۔"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "{shareBranch} پر منتقل نہیں کیا گیا: اس میں ایک سِم لنک ہے جو ریپازٹری سے باہر، نجی فائلوں کی طرف، یا ایسی جگہ کی طرف اشارہ کرتا ہے جس کی جانچ نہیں ہو سکتی۔ عام طور پر جس نے برانچ پُش کی ہے اسی کو لنک درست کرنا ہوگا۔ اگر اس کمپیوٹر کا کوئی فولڈر پڑھا نہیں جا سکتا تو اسے پڑھنے کے قابل بنائیں اور دوبارہ کوشش کریں۔"
diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.json
index fbed03bfe..4f9e94d4a 100644
--- a/packages/app/src/locales/zh-Hans/messages.json
+++ b/packages/app/src/locales/zh-Hans/messages.json
@@ -2834,6 +2834,11 @@
" 将使用该副本而不是插件的版本——副本不再跟随插件更新。"
],
"_6FVBz": ["跳到第 1-8 个标签页"],
+ "_6cS9O": [
+ "未在 worktree 中打开 ",
+ ["shareBranch"],
+ ":它包含一个指向仓库之外、私有文件或无法检查之处的符号链接。通常需要由推送该分支的人修复该链接。如果这台电脑上的某个文件夹无法读取,请使其可读后重试。"
+ ],
"_7UQ7y": ["全字匹配"],
"_8quCH": ["来自模板"],
"_902BE": [
diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.po
index 7ebd2963e..f64a69ca1 100644
--- a/packages/app/src/locales/zh-Hans/messages.po
+++ b/packages/app/src/locales/zh-Hans/messages.po
@@ -5172,6 +5172,10 @@ msgstr "由 Mermaid 源码生成的图示——流程图、时序图、类图、
msgid "Diagram view mode"
msgstr "图示查看模式"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "未在 worktree 中打开 {shareBranch}:它包含一个指向仓库之外、私有文件或无法检查之处的符号链接。通常需要由推送该分支的人修复该链接。如果这台电脑上的某个文件夹无法读取,请使其可读后重试。"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "未切换到 {shareBranch}:它包含一个指向仓库之外、私有文件或无法检查之处的符号链接。通常需要由推送该分支的人修复该链接。如果这台电脑上的某个文件夹无法读取,请使其可读后重试。"
diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.json
index d8c5b2560..532d56d4f 100644
--- a/packages/app/src/locales/zh-Hant/messages.json
+++ b/packages/app/src/locales/zh-Hant/messages.json
@@ -2852,6 +2852,11 @@
" 將使用該副本而非外掛的版本——副本不再跟隨外掛更新。"
],
"_6FVBz": ["跳到第 1-8 個分頁"],
+ "_6cS9O": [
+ "未在 worktree 中開啟 ",
+ ["shareBranch"],
+ ":它包含一個指向儲存庫之外、私有檔案或無法檢查之處的符號連結。通常需要由推送該分支的人修正該連結。如果這台電腦上的某個資料夾無法讀取,請使其可讀後重試。"
+ ],
"_7UQ7y": ["全字相符"],
"_8quCH": ["來自範本"],
"_902BE": [
diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.po
index 20b99bddc..9628af358 100644
--- a/packages/app/src/locales/zh-Hant/messages.po
+++ b/packages/app/src/locales/zh-Hant/messages.po
@@ -5172,6 +5172,10 @@ msgstr "由 Mermaid 原始碼產生的圖表——流程圖、循序圖、類別
msgid "Diagram view mode"
msgstr "圖表檢視模式"
+#: src/components/ShareBranchSwitchDialog.tsx
+msgid "Did not open {shareBranch} in a worktree: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
+msgstr "未在 worktree 中開啟 {shareBranch}:它包含一個指向儲存庫之外、私有檔案或無法檢查之處的符號連結。通常需要由推送該分支的人修正該連結。如果這台電腦上的某個資料夾無法讀取,請使其可讀後重試。"
+
#: src/components/ShareBranchSwitchDialog.tsx
msgid "Did not switch to {shareBranch}: it has a symlink pointing outside the repository, into private files, or somewhere that cannot be checked. Usually whoever pushed the branch has to fix the link. If a folder on this computer cannot be read, make it readable and try again."
msgstr "未切換到 {shareBranch}:它包含一個指向儲存庫之外、私有檔案或無法檢查之處的符號連結。通常需要由推送該分支的人修正該連結。如果這台電腦上的某個資料夾無法讀取,請使其可讀後重試。"
diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.ts
index 75c48c9da..349609f4a 100644
--- a/packages/app/src/server/hocuspocus-plugin.ts
+++ b/packages/app/src/server/hocuspocus-plugin.ts
@@ -228,6 +228,7 @@ export function hocuspocusPlugin(): Plugin {
server.httpServer?.prependListener('upgrade', collaborationHost.handleUpgrade);
const assetMiddleware = createAssetServeMiddleware({
+ contentDir: CONTENT_DIR,
contentFilter: currentSrv.contentFilter,
contentSirv: sirv(CONTENT_DIR, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
diff --git a/packages/app/tests/integration/branch-switch-private-state-link.test.ts b/packages/app/tests/integration/branch-switch-private-state-link.test.ts
new file mode 100644
index 000000000..e5b3c4ed8
--- /dev/null
+++ b/packages/app/tests/integration/branch-switch-private-state-link.test.ts
@@ -0,0 +1,87 @@
+import { execSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { setTimeout as wait } from 'node:timers/promises';
+import { ensureProjectGit } from '@inkeep/open-knowledge-server';
+import { afterEach, describe, expect, test } from 'vitest';
+import { createRestartableServer, createTestClient, pollUntil } from './test-harness';
+
+const cleanups: Array<() => Promise<void> | void> = [];
+
+afterEach(async () => {
+ while (cleanups.length > 0) {
+ await cleanups.pop()?.();
+ }
+});
+
+function git(cwd: string, args: string): string {
+ return execSync(`git ${args}`, {
+ cwd,
+ env: {
+ ...process.env,
+ GIT_CONFIG_GLOBAL: '/dev/null',
+ GIT_AUTHOR_NAME: 'test',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'test',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ },
+ encoding: 'utf-8',
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim();
+}
+
+describe('branch switch with a document that became a link into private state', () => {
+ test.runIf(process.platform !== 'win32')(
+ 'does not reseed the open document from the private file it now points at',
+ async () => {
+ const contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-branch-switch-private-')));
+ cleanups.push(() => rmSync(contentDir, { recursive: true, force: true }));
+ await ensureProjectGit(contentDir);
+ git(contentDir, 'config user.name test');
+ git(contentDir, 'config user.email [email protected]');
+ mkdirSync(join(contentDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(join(contentDir, '.ok', 'local', 'secret.md'), '# Secret\n\nPRIVATE-BYTES\n');
+ writeFileSync(join(contentDir, 'leak.md'), '# Leak\n\nOn main.\n', 'utf-8');
+ writeFileSync(join(contentDir, 'other.md'), '# Other\n\nOn main.\n', 'utf-8');
+ git(contentDir, 'add leak.md other.md');
+ git(contentDir, 'commit -m main');
+ git(contentDir, 'checkout -b feature');
+ git(contentDir, 'rm -q leak.md');
+ symlinkSync('.ok/local/secret.md', join(contentDir, 'leak.md'));
+ writeFileSync(join(contentDir, 'other.md'), '# Other\n\nOn feature.\n', 'utf-8');
+ git(contentDir, 'add leak.md other.md');
+ git(contentDir, 'commit -m feature');
+ git(contentDir, 'checkout main');
+
+ const server = await createRestartableServer({
+ contentDir,
+ keepContentDir: true,
+ gitEnabled: true,
+ commitDebounceMs: 500,
+ });
+ cleanups.push(() => server.shutdown());
+
+ const leak = await createTestClient(server.port, 'leak');
+ cleanups.push(() => leak.cleanup());
+ const other = await createTestClient(server.port, 'other');
+ cleanups.push(() => other.cleanup());
+ await pollUntil(() => leak.ytext.toString().includes('On main.'), 10_000, 50);
+ await pollUntil(() => other.ytext.toString().includes('On main.'), 10_000, 50);
+
+ git(contentDir, 'checkout feature');
+
+ const serverText = (docName: string): string =>
+ server.instance.hocuspocus.documents.get(docName)?.getText('source').toString() ?? '';
+ await pollUntil(() => serverText('other').includes('On feature.'), 15_000, 50);
+ await wait(1000);
+
+ expect(serverText('leak')).not.toContain('PRIVATE-BYTES');
+ expect(leak.ytext.toString()).not.toContain('PRIVATE-BYTES');
+ expect(
+ server.instance.hocuspocus.documents.get('leak')?.getMap('lifecycle').get('status'),
+ ).toBe('deleted-upstream');
+ },
+ 45_000,
+ );
+});
diff --git a/packages/cli/src/commands/clone-git-config-env.test.ts b/packages/cli/src/commands/clone-git-config-env.test.ts
index 4e09754f6..c7e2a1e75 100644
--- a/packages/cli/src/commands/clone-git-config-env.test.ts
+++ b/packages/cli/src/commands/clone-git-config-env.test.ts
@@ -3,7 +3,9 @@ import {
existsSync,
mkdirSync,
mkdtempSync,
+ readdirSync,
readFileSync,
+ readlinkSync,
realpathSync,
rmSync,
writeFileSync,
@@ -13,6 +15,7 @@ import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { shellSingleQuote } from '@inkeep/open-knowledge-core';
+import { UnsafeIncomingSymlinkError } from '@inkeep/open-knowledge-server';
import simpleGit, { GitPluginError, type SimpleGitOptions } from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import type { GhDetectResult } from '../auth/gh-detect.ts';
@@ -348,3 +351,159 @@ describe('clone honours the environment command-scope git config (GIT_CONFIG_COU
expect(out).not.toContain('GIT_CONFIG_KEY_<n>');
});
});
+
+describe('ok clone checks symlinks before checking anything out', () => {
+ let workspace: string;
+
+ function seedBareRepoWithLinks(bareDir: string, links: Record<string, string>): void {
+ const seedDir = `${bareDir}.seed`;
+ mkdirSync(seedDir, { recursive: true });
+ const git = (args: string[], input?: string) =>
+ execFileSync('git', args, { cwd: seedDir, input, encoding: 'utf-8' });
+ git(['init', '--initial-branch=main']);
+ writeFileSync(join(seedDir, 'README.md'), '# seeded\n', 'utf-8');
+ git(['add', 'README.md']);
+ for (const [path, target] of Object.entries(links)) {
+ const blob = git(['hash-object', '-w', '--stdin'], target).trim();
+ git(['update-index', '--add', '--cacheinfo', `120000,${blob},${path}`]);
+ }
+ git([
+ '-c',
+ 'user.name=Seed',
+ '-c',
+ '-c',
+ 'commit.gpgsign=false',
+ 'commit',
+ '-m',
+ 'seed',
+ ]);
+ execFileSync('git', ['clone', '--bare', seedDir, bareDir], {
+ cwd: dirname(bareDir),
+ stdio: 'ignore',
+ });
+ }
+
+ beforeEach(() => {
+ workspace = realpathSync(mkdtempSync(join(tmpdir(), 'ok-clone-links-')));
+ vi.stubEnv('HOME', workspace);
+ vi.stubEnv('USERPROFILE', workspace);
+ vi.stubEnv('XDG_CONFIG_HOME', join(workspace, '.config'));
+ vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1');
+ vi.stubEnv('GIT_CONFIG_COUNT', '1');
+ vi.stubEnv('GIT_CONFIG_KEY_0', 'url../.insteadOf');
+ vi.stubEnv('GIT_CONFIG_VALUE_0', 'https://127.0.0.1:1/');
+ vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ rmSync(workspace, { recursive: true, force: true });
+ });
+
+ test('a repository with unsafe links is refused and leaves no clone behind', async () => {
+ seedBareRepoWithLinks(join(workspace, 'o', 'r.git'), {
+ 'notes/leak.md': '../.git/config',
+ 'notes/q"uote.md': '../.ok/local/principal.json',
+ });
+ const url = 'https://127.0.0.1:1/o/r.git';
+
+ const error = await runClone(
+ url,
+ { json: true, dir: 'target', _detectGhFn: relayTokenGh },
+ {} as never,
+ workspace,
+ ).catch((err: unknown) => err);
+
+ expect(error).toBeInstanceOf(UnsafeIncomingSymlinkError);
+ expect(existsSync(join(workspace, 'target'))).toBe(false);
+
+ const emitted: Record<string, unknown>[] = [];
+ await handleCloneFailure({
+ error,
+ url,
+ branch: null,
+ json: true,
+ emit: (event) => emitted.push(event),
+ printStderr: () => undefined,
+ });
+ expect(emitted[0]?.type).toBe('error');
+ expect(emitted[0]?.code).toBe('unsafe-symlinks');
+ expect(String(emitted[0]?.message)).not.toContain('notes/');
+ expect(emitted[0]?.refusedSymlinkPaths).toEqual(
+ expect.arrayContaining(['notes/leak.md', 'notes/q\\"uote.md']),
+ );
+
+ const printed: string[] = [];
+ await handleCloneFailure({
+ error,
+ url,
+ branch: null,
+ json: false,
+ emit: () => undefined,
+ printStderr: (text) => printed.push(text),
+ });
+ expect(printed.join('')).toContain(
+ '"notes/leak.md" (points into private .git or OpenKnowledge state)',
+ );
+ expect(printed.join('')).toContain('"notes/q\\"uote.md"');
+ });
+
+ test('refusing keeps an existing empty target directory and empties it again', async () => {
+ seedBareRepoWithLinks(join(workspace, 'o', 'r.git'), { 'notes/root': '..' });
+ mkdirSync(join(workspace, 'target'));
+
+ await expect(
+ runClone(
+ 'https://127.0.0.1:1/o/r.git',
+ { json: true, dir: 'target', _detectGhFn: relayTokenGh },
+ {} as never,
+ workspace,
+ ),
+ ).rejects.toBeInstanceOf(UnsafeIncomingSymlinkError);
+
+ expect(readdirSync(join(workspace, 'target'))).toEqual([]);
+ });
+
+ test('an empty repository still clones', async () => {
+ const bareDir = join(workspace, 'o', 'r.git');
+ mkdirSync(bareDir, { recursive: true });
+ execFileSync('git', ['init', '--bare', '--initial-branch=main'], {
+ cwd: bareDir,
+ stdio: 'ignore',
+ });
+
+ await expect(
+ runClone(
+ 'https://127.0.0.1:1/o/r.git',
+ { json: true, dir: 'target', _detectGhFn: relayTokenGh },
+ {} as never,
+ workspace,
+ ),
+ ).resolves.toBe(join(workspace, 'target'));
+ });
+
+ test.runIf(process.platform !== 'win32')(
+ 'a repository whose links stay inside it is cloned and checked out',
+ async () => {
+ seedBareRepoWithLinks(join(workspace, 'o', 'r.git'), { 'notes/readme.md': '../README.md' });
+ const targetDir = join(workspace, 'target');
+
+ await expect(
+ runClone(
+ 'https://127.0.0.1:1/o/r.git',
+ { json: true, dir: 'target', _detectGhFn: relayTokenGh },
+ {} as never,
+ workspace,
+ ),
+ ).resolves.toBe(targetDir);
+
+ expect(readFileSync(join(targetDir, 'README.md'), 'utf-8')).toBe('# seeded\n');
+ expect(readlinkSync(join(targetDir, 'notes', 'readme.md'))).toBe('../README.md');
+ expect(
+ execFileSync('git', ['status', '--porcelain'], { cwd: targetDir, encoding: 'utf-8' }),
+ ).toBe('');
+ },
+ );
+});
diff --git a/packages/cli/src/commands/clone.test.ts b/packages/cli/src/commands/clone.test.ts
index 085555c2d..947b480f9 100644
--- a/packages/cli/src/commands/clone.test.ts
+++ b/packages/cli/src/commands/clone.test.ts
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
-import type { Config } from '@inkeep/open-knowledge-server';
+import { type Config, UnsafeIncomingSymlinkError } from '@inkeep/open-knowledge-server';
import simpleGit, { type SimpleGitOptions } from 'simple-git';
import { afterEach, beforeEach, describe, expect, it, test } from 'vitest';
import type { ExecFileSyncFn, GhDetectResult } from '../auth/gh-detect.ts';
@@ -1283,6 +1283,26 @@ describe('emitCloneFailure', () => {
expect(c.stderr).toHaveLength(0);
});
+ test('--json: an unsafe-symlink refusal keeps link names out of the message', () => {
+ const c = makeCollectors();
+ emitCloneFailure({
+ error: new UnsafeIncomingSymlinkError([
+ { path: 'docs/permission denied.md', reason: 'private-state' },
+ { path: 'notes/‮gnp.md', reason: 'outside-repository' },
+ ]),
+ url: 'inkeep/playbooks',
+ json: true,
+ emit: c.emit,
+ printStderr: c.printStderr,
+ });
+ expect(c.emitted).toHaveLength(1);
+ const event = c.emitted[0] as { message: string; code: string; refusedSymlinkPaths: string[] };
+ expect(event.code).toBe('unsafe-symlinks');
+ expect(event.message).not.toContain('permission denied');
+ expect(event.message).not.toContain('docs/');
+ expect(event.refusedSymlinkPaths).toEqual(['docs/permission denied.md', 'notes/\\u202egnp.md']);
+ });
+
test('--json: shape unchanged for non-auth failures too', () => {
const c = makeCollectors();
emitCloneFailure({
diff --git a/packages/cli/src/commands/clone.ts b/packages/cli/src/commands/clone.ts
index f1f8fb8e2..ac6ba345d 100644
--- a/packages/cli/src/commands/clone.ts
+++ b/packages/cli/src/commands/clone.ts
@@ -1,5 +1,5 @@
-import { existsSync, readdirSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { existsSync, readdirSync, rmSync } from 'node:fs';
+import { join, resolve } from 'node:path';
import {
type ClassifiedGitAuthError,
classifyGitAuthError,
@@ -8,6 +8,7 @@ import {
shellSingleQuote,
} from '@inkeep/open-knowledge-core';
import {
+ assertCheckoutSymlinksSafe,
assertGitAvailable,
type Config,
type CredentialUrlMatchReader,
@@ -18,6 +19,7 @@ import {
redactShareSubprocessStderr,
resolveGitHubAccountFromUrl,
sameGitHubLogin,
+ UnsafeIncomingSymlinkError,
} from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import simpleGit, { GitPluginError, type SimpleGitOptions } from 'simple-git';
@@ -238,8 +240,9 @@ export async function runClone(
const cloneUrl = resolveCloneUrl(url, parsed);
const targetDir = opts.dir ? resolve(cwd, opts.dir) : resolve(cwd, parsed.name);
+ const targetExisted = existsSync(targetDir);
- if (existsSync(targetDir)) {
+ if (targetExisted) {
const entries = readdirSync(targetDir);
if (entries.length > 0) {
throw new Error(`Target directory is not empty: ${targetDir}`);
@@ -297,7 +300,7 @@ export async function runClone(
typeof opts.branch === 'string' && opts.branch.length > 0 ? opts.branch : null;
await cloneWithBranchFallback({
branch: requestedBranch,
- clone: (args) => git.clone(cloneUrl, targetDir, args),
+ clone: (args) => git.clone(cloneUrl, targetDir, [...args, '--no-checkout']),
onFallback: (branch) => {
emit(opts.json, { type: 'branch-fallback', branch });
if (!opts.json) {
@@ -310,6 +313,17 @@ export async function runClone(
if (!opts.json) process.stderr.write('\n');
+ const cloned = simpleGit({ ...gitOptions, baseDir: targetDir }).env(env);
+ if ((await cloned.raw(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'])).trim() !== '') {
+ try {
+ await assertCheckoutSymlinksSafe(cloned, 'HEAD', env);
+ } catch (err) {
+ rmSync(targetExisted ? join(targetDir, '.git') : targetDir, { recursive: true, force: true });
+ throw err;
+ }
+ await cloned.raw(['checkout', '--force', 'HEAD']);
+ }
+
try {
const { runInit } = await import('./init.ts');
const initResult = await runInit({ cwd: targetDir, mcp: false });
@@ -452,11 +466,23 @@ export function emitCloneFailure(opts: {
principal?: string | null;
resolvedLogin?: string | null;
}): void {
- const rawMessage = redactShareSubprocessStderr(
- opts.error instanceof Error ? opts.error.message : String(opts.error),
- );
+ const rawMessage =
+ opts.error instanceof UnsafeIncomingSymlinkError
+ ? `The repository has symlinks that are unsafe to check out: ${opts.error.describeLinks()}. The clone was removed. Remove or fix these links on the remote, then clone again.`
+ : redactShareSubprocessStderr(
+ opts.error instanceof Error ? opts.error.message : String(opts.error),
+ );
if (opts.json) {
- opts.emit({ type: 'error', message: rawMessage });
+ opts.emit(
+ opts.error instanceof UnsafeIncomingSymlinkError
+ ? {
+ type: 'error',
+ code: 'unsafe-symlinks',
+ message: `The repository has ${opts.error.unsafe.length} symlink(s) that are unsafe to check out. The clone was removed. Remove or fix these links on the remote, then clone again.`,
+ refusedSymlinkPaths: opts.error.displayPaths(),
+ }
+ : { type: 'error', message: rawMessage },
+ );
return;
}
const actionable =
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 5eb18461c..37bf62270 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -674,7 +674,12 @@ export type OkLocalOpCloneEvent =
| { type: 'progress'; phase: string; pct: number }
| { type: 'complete'; dir: string }
| { type: 'branch-fallback'; branch: string }
- | { type: 'error'; message: string };
+ | {
+ type: 'error';
+ message: string;
+ code?: 'unsafe-symlinks';
+ refusedSymlinkPaths?: string[];
+ };
export interface OkLocalOpStream<E> {
readonly events: AsyncIterable<E>;
diff --git a/packages/core/src/git/worktree-selector-model.ts b/packages/core/src/git/worktree-selector-model.ts
index 1f9cc3491..893486b12 100644
--- a/packages/core/src/git/worktree-selector-model.ts
+++ b/packages/core/src/git/worktree-selector-model.ts
@@ -50,6 +50,13 @@ export type WorktreeCreateResult =
readonly helper: string;
readonly message?: string;
}
+ | {
+ readonly ok: false;
+ readonly reason: 'unsafe-symlinks';
+ readonly refusedSymlinkPaths: readonly string[];
+ readonly message?: never;
+ readonly helper?: never;
+ }
| {
readonly ok: false;
readonly reason: 'fetch-failed';
diff --git a/packages/desktop/src/main/worktree-service.test.ts b/packages/desktop/src/main/worktree-service.test.ts
index efbaf9e0c..f58e0b9ba 100644
--- a/packages/desktop/src/main/worktree-service.test.ts
+++ b/packages/desktop/src/main/worktree-service.test.ts
@@ -659,6 +659,93 @@ describe('worktree-service — share-branch checkout', () => {
expect(await repoSnapshot(handle.mainRepo)).toEqual(before);
});
+ async function pushBranchWithLinks(
+ root: string,
+ branch: string,
+ links: Record<string, string>,
+ ): Promise<string> {
+ const scratch = join(root, `scratch-${branch}`);
+ await git(root, 'clone', join(root, 'origin.git'), scratch);
+ await git(scratch, 'config', 'user.email', '[email protected]');
+ await git(scratch, 'config', 'user.name', 'Test');
+ await git(scratch, 'checkout', '-b', branch);
+ for (const [path, target] of Object.entries(links)) {
+ const targetFile = join(root, `link-target-${branch}`);
+ writeFileSync(targetFile, target);
+ const blob = (await git(scratch, 'hash-object', '-w', targetFile)).trim();
+ await git(scratch, 'update-index', '--add', '--cacheinfo', `120000,${blob},${path}`);
+ }
+ await git(scratch, 'commit', '-m', `links on ${branch}`);
+ await git(scratch, 'push', 'origin', branch);
+ return (await git(scratch, 'rev-parse', 'HEAD')).trim();
+ }
+
+ test('checkoutShareBranchWorktree refuses a remote branch carrying an unsafe symlink and creates nothing', async () => {
+ handle = await makeRepo();
+ await addBareRemote(handle.mainRepo, ['main']);
+ await pushBranchWithLinks(handle.root, 'unsafe-share', { 'notes/leak.md': '../.git/config' });
+ const before = await repoSnapshot(handle.mainRepo);
+
+ const res = await checkoutShareBranchWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'unsafe-share',
+ });
+
+ expect(res).toEqual({
+ ok: false,
+ reason: 'unsafe-symlinks',
+ refusedSymlinkPaths: ['notes/leak.md'],
+ });
+ expect(existsSync(join(handle.mainRepo, '.ok', 'worktrees', 'unsafe-share'))).toBe(false);
+ expect((await git(handle.mainRepo, 'branch', '--list', 'unsafe-share')).trim()).toBe('');
+ expect(await repoSnapshot(handle.mainRepo)).toEqual(before);
+ });
+
+ test('checkoutShareBranchWorktree refuses a local branch carrying an unsafe symlink', async () => {
+ handle = await makeRepo();
+ await addBareRemote(handle.mainRepo, ['main']);
+ await pushBranchWithLinks(handle.root, 'local-unsafe', { 'notes/root': '..' });
+ await git(handle.mainRepo, 'fetch', 'origin', 'local-unsafe:local-unsafe');
+
+ const res = await checkoutShareBranchWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'local-unsafe',
+ });
+
+ expect(res).toEqual({
+ ok: false,
+ reason: 'unsafe-symlinks',
+ refusedSymlinkPaths: ['notes/root'],
+ });
+ expect(existsSync(join(handle.mainRepo, '.ok', 'worktrees', 'local-unsafe'))).toBe(false);
+ });
+
+ test('checkoutShareBranchWorktree checks out the remote branch, not a tag that shadows its short name', async () => {
+ handle = await makeRepo();
+ await addBareRemote(handle.mainRepo, ['main']);
+ const safe = await pushBranchWithLinks(handle.root, 'tagged', {
+ 'notes/readme.md': '../README.md',
+ });
+ const unsafe = await pushBranchWithLinks(handle.root, 'evil', {
+ 'notes/leak.md': '../.git/config',
+ });
+ await git(handle.mainRepo, 'fetch', 'origin');
+ await git(handle.mainRepo, 'tag', 'origin/tagged', unsafe);
+
+ const res = await checkoutShareBranchWorktree({
+ anchorPath: handle.mainRepo,
+ branch: 'tagged',
+ });
+
+ expect(res.ok).toBe(true);
+ if (!res.ok) return;
+ expect((await git(res.path, 'rev-parse', 'HEAD')).trim()).toBe(safe);
+ expect(existsSync(join(res.path, 'notes', 'readme.md'))).toBe(true);
+ expect(readdirSync(join(res.path, 'notes'))).toEqual(['readme.md']);
+ const upstream = await git(res.path, 'rev-parse', '--symbolic-full-name', '@{upstream}');
+ expect(upstream.trim()).toBe('refs/remotes/origin/tagged');
+ });
+
test('share fetch pins credential interactivity off so no helper can open a dialog', () => {
const args = buildShareFetchArgs('feat-x');
expect(args).toEqual(['-c', 'credential.interactive=false', 'fetch', 'origin', 'feat-x']);
diff --git a/packages/desktop/src/main/worktree-service.ts b/packages/desktop/src/main/worktree-service.ts
index 9cb332849..946c439ce 100644
--- a/packages/desktop/src/main/worktree-service.ts
+++ b/packages/desktop/src/main/worktree-service.ts
@@ -17,7 +17,11 @@ import {
type WorktreeListResult,
worktreeRelativeDir,
} from '@inkeep/open-knowledge-core';
-import { redactShareSubprocessStderr } from '@inkeep/open-knowledge-server';
+import {
+ assertRepoCheckoutSymlinksSafe,
+ redactShareSubprocessStderr,
+ UnsafeIncomingSymlinkError,
+} from '@inkeep/open-knowledge-server';
import { isPathWithinProject } from '../shared/path-containment.ts';
import { getLogger } from './desktop-logger.ts';
import { gitSpawnEnv } from './git-spawn-env.ts';
@@ -239,18 +243,23 @@ export async function checkoutShareBranchWorktree(
}
const worktrees = await listGitWorktrees(args.anchorPath);
if (worktrees.length === 0) return { ok: false, reason: 'no-git' };
+ const target = {
+ anchorPath: args.anchorPath,
+ branch,
+ projectSubPath: args.projectSubPath,
+ sourceProjectPath: args.sourceProjectPath,
+ };
- if (await refExists(args.anchorPath, `refs/heads/${branch}`)) {
- return createWorktree({
- anchorPath: args.anchorPath,
- branch,
- createBranch: false,
- projectSubPath: args.projectSubPath,
- sourceProjectPath: args.sourceProjectPath,
- });
+ const localRef = `refs/heads/${branch}`;
+ if (await refExists(args.anchorPath, localRef)) {
+ if (!worktrees.some((w) => !w.prunable && w.branch === branch)) {
+ const refused = await refuseUnsafeSymlinks(args.anchorPath, localRef);
+ if (refused !== null) return refused;
+ }
+ return createWorktree({ ...target, createBranch: false });
}
- const remoteRef = `origin/${branch}`;
- if (!(await refExists(args.anchorPath, `refs/remotes/${remoteRef}`))) {
+ const remoteRef = `refs/remotes/origin/${branch}`;
+ if (!(await refExists(args.anchorPath, remoteRef))) {
const failure = await fetchShareBranch(
args.anchorPath,
branch,
@@ -258,14 +267,77 @@ export async function checkoutShareBranchWorktree(
);
if (failure !== null) return failure;
}
- return createWorktree({
- anchorPath: args.anchorPath,
- branch,
- remoteRef,
- createBranch: true,
- projectSubPath: args.projectSubPath,
- sourceProjectPath: args.sourceProjectPath,
- });
+ const commit = await resolveCommit(args.anchorPath, remoteRef);
+ if (commit === null) return { ok: false, reason: 'branch-not-found' };
+ const refused = await refuseUnsafeSymlinks(args.anchorPath, commit);
+ if (refused !== null) return refused;
+ const result = await createWorktree({ ...target, baseRef: commit, createBranch: true });
+ if (result.ok ? result.created : result.reason === 'project-scope-unavailable') {
+ await setOriginUpstream(args.anchorPath, branch);
+ }
+ return result;
+}
+
+async function resolveCommit(anchorPath: string, ref: string): Promise<string | null> {
+ try {
+ const { stdout } = await execFileAsync(
+ 'git',
+ ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`],
+ { cwd: anchorPath, env: gitSpawnEnv(), timeout: 5_000, windowsHide: true },
+ );
+ const commit = String(stdout).trim();
+ return /^[0-9a-f]{40,64}$/u.test(commit) ? commit : null;
+ } catch {
+ return null;
+ }
+}
+
+async function refuseUnsafeSymlinks(
+ anchorPath: string,
+ ref: string,
+): Promise<Extract<WorktreeCreateResult, { ok: false }> | null> {
+ try {
+ await assertRepoCheckoutSymlinksSafe(anchorPath, ref);
+ return null;
+ } catch (err) {
+ if (err instanceof UnsafeIncomingSymlinkError) {
+ getLogger('worktree').warn(
+ { refusedCount: err.unsafe.length },
+ 'refused a share-branch worktree whose branch carries unsafe symlinks',
+ );
+ return {
+ ok: false,
+ reason: 'unsafe-symlinks',
+ refusedSymlinkPaths: err.displayPaths(),
+ };
+ }
+ return {
+ ok: false,
+ reason: 'error',
+ message: redactShareSubprocessStderr(gitErrorText(err)).replace(/\s+/g, ' ').slice(0, 300),
+ };
+ }
+}
+
+async function setOriginUpstream(anchorPath: string, branch: string): Promise<void> {
+ for (const [key, value] of [
+ [`branch.${branch}.remote`, 'origin'],
+ [`branch.${branch}.merge`, `refs/heads/${branch}`],
+ ]) {
+ try {
+ await execFileAsync('git', ['config', key, value], {
+ cwd: anchorPath,
+ env: gitSpawnEnv(),
+ timeout: 5_000,
+ windowsHide: true,
+ });
+ } catch (err) {
+ getLogger('worktree').warn(
+ { key, error: gitErrorText(err).replace(/\s+/g, ' ').slice(0, 200) },
+ 'could not record the share branch upstream',
+ );
+ }
+ }
}
async function refExists(anchorPath: string, ref: string): Promise<boolean> {
diff --git a/packages/server/src/api-document-composition.test.ts b/packages/server/src/api-document-composition.test.ts
index 94ed91288..901b66c3c 100644
--- a/packages/server/src/api-document-composition.test.ts
+++ b/packages/server/src/api-document-composition.test.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
@@ -7,12 +7,13 @@ import type { BootedServer } from './boot.ts';
import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';
let tmpRoot: string;
+let contentDir: string;
let server: BootedServer;
let ephemeral: BootedServer;
beforeAll(async () => {
tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-document-native-'));
- const contentDir = mkdtempSync(resolve(tmpRoot, 'content-'));
+ contentDir = mkdtempSync(resolve(tmpRoot, 'content-'));
writeFileSync(
resolve(contentDir, 'alpha.md'),
'# Alpha Title\n\n## Section One\n\nBody.\n',
@@ -74,6 +75,21 @@ describe('document/pages group over the composed listener — served natively',
expect(((await missing.json()) as { type?: string }).type).toBe('urn:ok:error:doc-not-found');
});
+ test('document read refuses a doc linked into machine-local OpenKnowledge state', async () => {
+ mkdirSync(resolve(contentDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(
+ resolve(contentDir, '.ok', 'local', 'leak-fixture.json'),
+ '{"token":"machine-local-secret"}',
+ 'utf-8',
+ );
+ mkdirSync(resolve(contentDir, 'linked'), { recursive: true });
+ symlinkSync('../.ok/local/leak-fixture.json', resolve(contentDir, 'linked', 'leak.md'));
+
+ const res = await fetch(`http://127.0.0.1:${server.port}/api/document?docName=linked/leak`);
+ expect(res.status).toBe(500);
+ expect(await res.text()).not.toContain('machine-local-secret');
+ });
+
test('documents lists both docs; pages carries derived titles; headings extract', async () => {
const documents = (await (
await fetch(`http://127.0.0.1:${server.port}/api/documents`)
diff --git a/packages/server/src/api-file-ops-composition.test.ts b/packages/server/src/api-file-ops-composition.test.ts
index b4768077a..4eb092386 100644
--- a/packages/server/src/api-file-ops-composition.test.ts
+++ b/packages/server/src/api-file-ops-composition.test.ts
@@ -234,6 +234,22 @@ describe('file-ops group over the composed listener — served natively', () =>
expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:path-escape');
});
+ test('duplicate-path refuses an extensionless file path linked into machine-local state', async () => {
+ mkdirSync(resolve(contentDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(
+ resolve(contentDir, '.ok', 'local', 'dup-fixture.json'),
+ '{"token":"machine-local-secret"}',
+ 'utf-8',
+ );
+ mkdirSync(resolve(contentDir, 'dup-linked'), { recursive: true });
+ symlinkSync('../.ok/local/dup-fixture.json', resolve(contentDir, 'dup-linked', 'leak.md'));
+
+ const res = await postJson('/api/duplicate-path', { kind: 'file', path: 'dup-linked/leak' });
+ expect(res.status).toBe(400);
+ expect(((await res.json()) as { type?: string }).type).toBe('urn:ok:error:path-escape');
+ expect(readdirSync(resolve(contentDir, 'dup-linked'))).toEqual(['leak.md']);
+ });
+
test('duplicate-path maps a symlink escape OUT of the content root to a 400, not a 500', async () => {
const outsideTarget = mkdtempSync(resolve(tmpRoot, 'escape-dup-out-'));
symlinkSync(outsideTarget, resolve(contentDir, 'escape-dup-out'), 'dir');
diff --git a/packages/server/src/asset-serve-middleware.integration.test.ts b/packages/server/src/asset-serve-middleware.integration.test.ts
index b1e0b8de9..a52fab9f5 100644
--- a/packages/server/src/asset-serve-middleware.integration.test.ts
+++ b/packages/server/src/asset-serve-middleware.integration.test.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { createServer, request as httpRequest, type Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
@@ -25,6 +25,7 @@ async function startHarness(contentDir: string): Promise<Harness> {
contentDir,
});
const middleware = createAssetServeMiddleware({
+ contentDir,
contentFilter,
contentSirv: sirv(contentDir, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
@@ -246,6 +247,67 @@ describe('asset-serve middleware (narrow integration)', () => {
});
});
+ describe('Symlinked content stays inside the repository', () => {
+ const SECRET = 'machine-local-secret';
+
+ beforeEach(() => {
+ mkdirSync(join(contentDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(join(contentDir, '.ok', 'local', 'principal.json'), `{"token":"${SECRET}"}`);
+ mkdirSync(join(contentDir, '.git'), { recursive: true });
+ writeFileSync(join(contentDir, '.git', 'config'), `[core]\n\t# ${SECRET}\n`);
+ });
+
+ test('a markdown link into machine-local state is not served', async () => {
+ symlinkSync('../.ok/local/principal.json', join(contentDir, 'docs', 'leak.md'));
+ const res = await fetch(`${harness.baseURL}/docs/leak.md`);
+ const body = await res.text();
+ expect(body).not.toContain(SECRET);
+ expect(body).toContain('spa fallback sentinel');
+ });
+
+ test('an asset link to the git config is not served', async () => {
+ symlinkSync('../.git/config', join(contentDir, 'docs', 'cfg.txt'));
+ const res = await fetch(`${harness.baseURL}/docs/cfg.txt`);
+ expect(res.status).toBe(404);
+ expect(await res.text()).not.toContain(SECRET);
+ });
+
+ test('an asset link outside the content dir is not served', async () => {
+ const outsideDir = mkdtempSync(join(tmpdir(), 'ok-asset-serve-outside-'));
+ try {
+ writeFileSync(join(outsideDir, 'secret.png'), SECRET);
+ symlinkSync(join(outsideDir, 'secret.png'), join(contentDir, 'docs', 'outside.png'));
+ const res = await fetch(`${harness.baseURL}/docs/outside.png`);
+ expect(res.status).toBe(404);
+ expect(await res.text()).not.toContain(SECRET);
+ } finally {
+ rmSync(outsideDir, { recursive: true, force: true });
+ }
+ });
+
+ test('a path is checked as sirv decodes it, not as the extension gate decodes it', async () => {
+ writeFileSync(join(contentDir, 'docs', 'x+.png'), 'harmless-bytes');
+ symlinkSync('../.ok/local/principal.json', join(contentDir, 'docs', 'x%2B.png'));
+ const res = await fetch(`${harness.baseURL}/docs/x%2B.png`);
+ expect(res.status).toBe(404);
+ expect(await res.text()).not.toContain(SECRET);
+ });
+
+ test('a missing asset does not fall back to a linked html sibling', async () => {
+ symlinkSync('../.ok/local/principal.json', join(contentDir, 'docs', 'gone.png.html'));
+ const res = await fetch(`${harness.baseURL}/docs/gone.png`);
+ expect(res.status).toBe(404);
+ expect(await res.text()).not.toContain(SECRET);
+ });
+
+ test('an in-root link to an ordinary asset is still served', async () => {
+ symlinkSync('photo.png', join(contentDir, 'docs', 'alias.png'));
+ const res = await fetch(`${harness.baseURL}/docs/alias.png`);
+ expect(res.status).toBe(200);
+ expect(await res.text()).toBe('fake-png-bytes');
+ });
+ });
+
describe('Content-serve ingress gate (DNS-rebinding defense)', () => {
function getWithHost(path: string, host: string): Promise<{ status: number; body: string }> {
return new Promise((resolve, reject) => {
diff --git a/packages/server/src/asset-serve-middleware.test.ts b/packages/server/src/asset-serve-middleware.test.ts
index 15d6d0164..eecb35a38 100644
--- a/packages/server/src/asset-serve-middleware.test.ts
+++ b/packages/server/src/asset-serve-middleware.test.ts
@@ -1,6 +1,9 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
import { Readable } from 'node:stream';
-import { describe, expect, test } from 'vitest';
+import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import {
type AssetServeFilter,
createAssetServeMiddleware,
@@ -76,8 +79,35 @@ const INLINE = new Set(['png', 'jpg', 'pdf', 'mp4', 'm4v', 'svg']);
const ASSETS = new Set([...INLINE, 'docx', 'csv', 'json', 'txt', 'zip', 'html', 'htm']);
const BLOCKLIST = new Set(['exe', 'dmg', 'sh', 'html', 'htm']);
+const SERVABLE_FIXTURES = [
+ 'photo.png',
+ 'clip.m4v',
+ 'data.csv',
+ 'spec.docx',
+ 'doc.pdf',
+ 'icon.svg',
+ 'trip-viewer.html',
+ 'legacy.htm',
+ 'notes.md',
+ 'Notes.MD',
+ 'doc.mdx',
+ 'my file.m4v',
+];
+
+let fixtureDir: string;
+
+beforeAll(() => {
+ fixtureDir = mkdtempSync(join(tmpdir(), 'ok-asset-serve-unit-'));
+ for (const name of SERVABLE_FIXTURES) writeFileSync(join(fixtureDir, name), 'fixture');
+});
+
+afterAll(() => {
+ rmSync(fixtureDir, { recursive: true, force: true });
+});
+
function buildMiddleware(sirv: SirvLikeMiddleware, filter: AssetServeFilter = admitAll) {
return createAssetServeMiddleware({
+ contentDir: fixtureDir,
contentFilter: filter,
contentSirv: sirv,
inlineExtensions: INLINE,
diff --git a/packages/server/src/asset-serve-middleware.ts b/packages/server/src/asset-serve-middleware.ts
index a3f9ac388..3ac1ec32a 100644
--- a/packages/server/src/asset-serve-middleware.ts
+++ b/packages/server/src/asset-serve-middleware.ts
@@ -1,6 +1,9 @@
+import { realpathSync, statSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
-import { extname } from 'node:path';
+import { extname, join, normalize, relative, resolve, sep } from 'node:path';
import { SANDBOXED_HTML_EXTENSIONS } from '@inkeep/open-knowledge-core';
+import { isWithinContentDir } from './content-path.ts';
+import { resolvesIntoPrivateState } from './fs-safety.ts';
import { errorResponse } from './http/error-response.ts';
import {
HOST_NOT_ADMITTED_REMEDIATION,
@@ -21,6 +24,7 @@ export type SirvLikeMiddleware = (
) => void;
interface AssetServeMiddlewareDeps {
+ contentDir: string;
contentFilter: AssetServeFilter;
contentSirv: SirvLikeMiddleware;
inlineExtensions: ReadonlySet<string>;
@@ -29,10 +33,48 @@ interface AssetServeMiddlewareDeps {
ingressPolicy: IngressPolicy;
}
+function sirvLookupPath(url: string): string {
+ let pathname = url;
+ if (pathname.length > 1) {
+ const hash = pathname.indexOf('#', 1);
+ if (hash !== -1) pathname = pathname.slice(0, hash);
+ const query = pathname.indexOf('?', 1);
+ if (query !== -1) pathname = pathname.slice(0, query);
+ }
+ if (!pathname.includes('%')) return pathname;
+ try {
+ return decodeURI(pathname);
+ } catch {
+ return pathname;
+ }
+}
+
+function isServableContentFile(contentDir: string, url: string): boolean {
+ const root = resolve(contentDir);
+ const requested = normalize(join(`${root}${sep}`, sirvLookupPath(url)));
+ if (!requested.startsWith(`${root}${sep}`)) return false;
+ try {
+ const contentRoot = realpathSync(root);
+ const canonical = realpathSync(requested);
+ return (
+ statSync(canonical).isFile() &&
+ isWithinContentDir(canonical, contentRoot) &&
+ !resolvesIntoPrivateState(
+ join(contentRoot, relative(root, requested)),
+ canonical,
+ contentRoot,
+ )
+ );
+ } catch {
+ return false;
+ }
+}
+
export function createAssetServeMiddleware(
deps: AssetServeMiddlewareDeps,
): (req: IncomingMessage, res: ServerResponse, next: () => void) => void {
const {
+ contentDir,
contentFilter,
contentSirv,
inlineExtensions,
@@ -77,7 +119,7 @@ export function createAssetServeMiddleware(
if (classified.sandboxedHtml) {
res.setHeader('Cache-Control', 'no-store');
}
- contentSirv(req, res, () => {
+ const notServed = () => {
if (res.headersSent) return;
const isHtml = SANDBOXED_HTML_EXTENSIONS.has(ext);
if (!isHtml && (assetExtensions.has(ext) || blocklistExtensions.has(ext))) {
@@ -92,6 +134,11 @@ export function createAssetServeMiddleware(
res.removeHeader('Cache-Control');
}
next();
- });
+ };
+ if (!isServableContentFile(contentDir, req.url ?? '')) {
+ notServed();
+ return;
+ }
+ contentSirv(req, res, notServed);
};
}
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 5946989a8..05a7c9bd0 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -443,6 +443,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
const contentAssetMiddleware =
opts.serveContentAssets !== false
? createAssetServeMiddleware({
+ contentDir: opts.contentDir,
contentFilter: serverInstance.contentFilter,
contentSirv: sirv(opts.contentDir, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
diff --git a/packages/server/src/external-change-private-state.test.ts b/packages/server/src/external-change-private-state.test.ts
new file mode 100644
index 000000000..2b9700776
--- /dev/null
+++ b/packages/server/src/external-change-private-state.test.ts
@@ -0,0 +1,64 @@
+import {
+ mkdirSync,
+ mkdtempSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ unlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Hocuspocus } from '@hocuspocus/server';
+import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import type * as Y from 'yjs';
+import { RECONCILE_TEST_CONFLICTS } from './conflict-authority.test-helper.ts';
+import { DocumentDurabilityState } from './document-durability-state.ts';
+import { reconcileDiskBeforeAgentWrite } from './external-change.ts';
+
+describe('reconcile before an agent write', () => {
+ let contentDir = '';
+
+ beforeEach(() => {
+ contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-reconcile-private-')));
+ mkdirSync(join(contentDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(join(contentDir, '.ok', 'local', 'secret.md'), '# Secret\n\nprivate bytes\n');
+ });
+
+ afterEach(() => {
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ test.runIf(process.platform !== 'win32')(
+ 'leaves a loaded document unchanged when its file becomes a link into private state',
+ async () => {
+ const hp = new Hocuspocus({ quiet: true });
+ const durabilityState = new DocumentDurabilityState();
+ const base = '# Notes\n\nFirst paragraph.\n';
+ const conn = await hp.openDirectConnection('note');
+ const doc = (conn as unknown as { document: Y.Doc }).document;
+ writeFileSync(join(contentDir, 'note.md'), base);
+ durabilityState.setReconciledBase('note', base);
+ doc.transact(() => {
+ doc.getText('source').insert(0, base);
+ }, 'seed');
+
+ unlinkSync(join(contentDir, 'note.md'));
+ symlinkSync('.ok/local/secret.md', join(contentDir, 'note.md'));
+
+ const result = reconcileDiskBeforeAgentWrite(
+ durabilityState,
+ hp,
+ 'note',
+ contentDir,
+ undefined,
+ undefined,
+ RECONCILE_TEST_CONFLICTS,
+ );
+
+ expect(result.reconciled).toBe(false);
+ expect(doc.getText('source').toString()).toBe(base);
+ await conn.disconnect();
+ },
+ );
+});
diff --git a/packages/server/src/external-change.ts b/packages/server/src/external-change.ts
index 7259b007c..841bdfaa7 100644
--- a/packages/server/src/external-change.ts
+++ b/packages/server/src/external-change.ts
@@ -26,12 +26,13 @@ import {
} from './cc1-broadcast.ts';
import { type ConflictAuthority, isDocInConflict } from './conflict-authority.ts';
import type { ReconcileReason } from './conflict-kinds.ts';
-import { isWithinContentDir, safeContentPath } from './content-path.ts';
+import { safeContentPath } from './content-path.ts';
import { recordContributor } from './contributor-tracker.ts';
import { applyDiskContentToDoc, FILE_WATCHER_ORIGIN } from './disk-content-intake.ts';
import type { DocumentDurabilityState } from './document-durability-state.ts';
import { takeExternalChangeAttribution } from './external-change-attribution.ts';
import { recordFrontmatterEditSurface } from './frontmatter-telemetry.ts';
+import { canonicalContentPathIsRefused } from './fs-safety.ts';
import { getLogger } from './logger.ts';
import {
incrementExternalChangeHandlerErrors,
@@ -316,16 +317,17 @@ export function reconcileDiskBeforeAgentWrite(
const base = durabilityState.getReconciledBase(docName);
if (base === undefined) return NOT_RECONCILED;
+ let requestedPath: string;
let canonical: string;
try {
- const requestedPath = safeContentPath(docName, contentDir);
+ requestedPath = safeContentPath(docName, contentDir);
if (!existsSync(requestedPath)) return NOT_RECONCILED;
canonical = realpathSync(requestedPath);
} catch {
return NOT_RECONCILED;
}
- if (!isWithinContentDir(canonical, contentDir)) {
+ if (canonicalContentPathIsRefused(requestedPath, canonical, contentDir)) {
getLogger('reconcile').warn(
{ docName, canonical, contentDir },
`[reconcile] symlink-escape on disk read for ${docName}; skipping reconcile`,
diff --git a/packages/server/src/file-watcher.test.ts b/packages/server/src/file-watcher.test.ts
index b398d0c2c..e74a95fe6 100644
--- a/packages/server/src/file-watcher.test.ts
+++ b/packages/server/src/file-watcher.test.ts
@@ -1806,6 +1806,74 @@ describe('startWatcher symlink handling', () => {
expect(collected).toHaveLength(0);
});
+ describe('links into private repository state', () => {
+ const SECRET = '# machine-local-secret\n';
+
+ beforeEach(() => {
+ mkdirSync(resolve(contentDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(resolve(contentDir, '.ok', 'local', 'secret.md'), SECRET);
+ mkdirSync(resolve(contentDir, '.git'), { recursive: true });
+ writeFileSync(resolve(contentDir, '.git', 'config'), '[core]\n');
+ writeFileSync(resolve(contentDir, '.ok', 'config.yml'), '');
+ });
+
+ const filterFor = () => createContentFilter({ projectDir: contentDir, contentDir });
+
+ test('the startup walk does not follow a directory link into .git', async () => {
+ writeFileSync(resolve(contentDir, '.git', 'notes.md'), SECRET);
+ symlinkSync('.git', resolve(contentDir, 'repo'));
+
+ const handle = await startWatcher(contentDir, async () => {}, filterFor());
+ try {
+ expect(handle.getFolderAliasIndex().has('repo')).toBe(false);
+ for (const docName of handle.getFileIndex().keys()) {
+ expect(docName.startsWith('.git/')).toBe(false);
+ }
+ } finally {
+ await handle.unsubscribe();
+ }
+ });
+
+ test('runtime events for a doc linked into machine-local state are dropped', async () => {
+ const linkPath = resolve(contentDir, 'leak.md');
+ symlinkSync('.ok/local/secret.md', linkPath);
+
+ const collected: DiskEvent[] = [];
+ await handleRawEvents(
+ [{ type: 'create', path: linkPath }],
+ contentDir,
+ filterFor(),
+ new Map(),
+ new Map(),
+ async (e) => {
+ collected.push(e);
+ },
+ new Map(),
+ );
+
+ expect(collected).toHaveLength(0);
+ });
+
+ test('runtime events for an asset linked to the git config are dropped', async () => {
+ const linkPath = resolve(contentDir, 'leak.png');
+ symlinkSync('.git/config', linkPath);
+
+ const collected: DiskEvent[] = [];
+ await handleRawEvents(
+ [{ type: 'create', path: linkPath }],
+ contentDir,
+ filterFor(),
+ new Map(),
+ new Map(),
+ async (e) => {
+ collected.push(e);
+ },
+ );
+
+ expect(collected).toHaveLength(0);
+ });
+ });
+
test('preserves runtime events for symlinks pointing inside contentDir', async () => {
const targetPath = resolve(contentDir, 'real-target.md');
const aliasPath = resolve(contentDir, 'alias.md');
diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.ts
index dd53ed782..dd57da008 100644
--- a/packages/server/src/file-watcher.ts
+++ b/packages/server/src/file-watcher.ts
@@ -21,6 +21,7 @@ import {
registerDocExtension,
stripDocExtension,
} from './doc-extensions.ts';
+import { resolvesIntoPrivateState } from './fs-safety.ts';
import { classifyFsPath, normalizeFsPath } from './fs-traced.ts';
import { errnoCode } from './http/handler-utils.ts';
import { getLogger } from './logger.ts';
@@ -362,7 +363,10 @@ function eventEscapesContentDir(rawPath: string, contentDir: string): boolean {
}
return true;
}
- return !isWithinContentDir(canonical, contentDir);
+ return (
+ !isWithinContentDir(canonical, contentDir) ||
+ resolvesIntoPrivateState(rawPath, canonical, contentDir)
+ );
}
export function pathToDocName(absPath: string, contentDir: string): string {
@@ -685,7 +689,10 @@ async function seedLastKnownHashes(
continue;
}
- if (!isWithinContentDir(canonical, contentDir)) {
+ if (
+ !isWithinContentDir(canonical, contentDir) ||
+ resolvesIntoPrivateState(fullPath, canonical, contentDir)
+ ) {
log.warn(
{ path: fullPath, canonical },
`Symlink escape: ${fullPath} → ${canonical}, skipping`,
diff --git a/packages/server/src/fs-safety.test.ts b/packages/server/src/fs-safety.test.ts
index f6fca8d6c..24adc26b3 100644
--- a/packages/server/src/fs-safety.test.ts
+++ b/packages/server/src/fs-safety.test.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, mkdtempSync, rmSync, symlinkSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, win32 } from 'node:path';
import { describe, expect, test } from 'vitest';
@@ -61,6 +61,96 @@ describe('containment error family classification', () => {
});
});
+describe('assertNoSymlinkEscape refuses links into private repository state', () => {
+ function withRepo(run: (contentDir: string) => void): void {
+ const contentDir = mkdtempSync(join(tmpdir(), 'fs-safety-private-'));
+ try {
+ for (const dir of ['.ok/local', '.ok/templates', '.git', 'notes', 'shared', 'docs/.ok']) {
+ mkdirSync(join(contentDir, dir), { recursive: true });
+ }
+ writeFileSync(join(contentDir, '.ok/local/principal.json'), '{"secret":true}');
+ writeFileSync(join(contentDir, '.ok/config.yml'), '');
+ writeFileSync(join(contentDir, '.ok/templates/t.md'), '# T');
+ writeFileSync(join(contentDir, '.git/config'), '[core]');
+ writeFileSync(join(contentDir, 'shared/a.md'), '# A');
+ run(contentDir);
+ } finally {
+ rmSync(contentDir, { recursive: true, force: true });
+ }
+ }
+
+ const refusal = (path: string, contentDir: string): unknown => {
+ try {
+ assertNoSymlinkEscape(path, contentDir);
+ return null;
+ } catch (e) {
+ return e;
+ }
+ };
+
+ test.each([
+ [
+ 'a file link to machine-local state',
+ 'notes/leak.md',
+ '../.ok/local/principal.json',
+ 'notes/leak.md',
+ ],
+ ['a file link to the git config', 'notes/cfg.md', '../.git/config', 'notes/cfg.md'],
+ ['a link to the config dir itself', 'notes/ok', '../.ok', 'notes/ok'],
+ [
+ 'a descent into .git through a link to the root',
+ 'notes/root',
+ '..',
+ 'notes/root/.git/config',
+ ],
+ ['a new file under a link into .git', 'notes/hooks', '../.git', 'notes/hooks/new.md'],
+ ])('%s is refused', (_label, link, target, requested) => {
+ withRepo((contentDir) => {
+ symlinkSync(target, join(contentDir, link));
+ const caught = refusal(join(contentDir, requested), contentDir);
+ expect(caught).toBeInstanceOf(SymlinkEscapeError);
+ expect(isContainmentRejection(caught)).toBe(true);
+ });
+ });
+
+ test.each([
+ ['the config file', '.ok/config.yml'],
+ ['the templates dir', '.ok/templates'],
+ ['a nested folder config dir', 'docs/.ok'],
+ ['a missing nested folder config dir', 'notes/.ok'],
+ ])('direct access to %s still passes', (_label, requested) => {
+ withRepo((contentDir) => {
+ expect(refusal(join(contentDir, requested), contentDir)).toBeNull();
+ });
+ });
+
+ test('in-root links to ordinary content still pass', () => {
+ withRepo((contentDir) => {
+ symlinkSync('../shared/a.md', join(contentDir, 'notes/alias.md'));
+ symlinkSync('../shared', join(contentDir, 'notes/shared-dir'));
+ expect(refusal(join(contentDir, 'notes/alias.md'), contentDir)).toBeNull();
+ expect(refusal(join(contentDir, 'notes/shared-dir/a.md'), contentDir)).toBeNull();
+ });
+ });
+
+ test("a symlinked folder's own config dir classifies like the folder it links to", () => {
+ withRepo((contentDir) => {
+ symlinkSync('../docs', join(contentDir, 'notes/docs-link'));
+ expect(refusal(join(contentDir, 'notes/docs-link/.ok'), contentDir)).toBeNull();
+ expect(
+ refusal(join(contentDir, 'notes/docs-link/.ok/frontmatter.yml'), contentDir),
+ ).toBeNull();
+ });
+ });
+
+ test('a link whose own target is a config dir stays refused', () => {
+ withRepo((contentDir) => {
+ symlinkSync('../docs/.ok', join(contentDir, 'notes/cfg'));
+ expect(refusal(join(contentDir, 'notes/cfg'), contentDir)).toBeInstanceOf(SymlinkEscapeError);
+ });
+ });
+});
+
describe('canonicalRelPathForNewTarget', () => {
const log = loggerFactory.getLogger('test');
const errno = (code: string): NodeJS.ErrnoException => {
diff --git a/packages/server/src/fs-safety.ts b/packages/server/src/fs-safety.ts
index 7bbbe4e75..219c5ade9 100644
--- a/packages/server/src/fs-safety.ts
+++ b/packages/server/src/fs-safety.ts
@@ -3,6 +3,7 @@ import { dirname, join, relative, sep } from 'node:path';
import { isWithinContentDir } from './content-path.ts';
import { normalizeFsPath } from './fs-traced.ts';
import { errnoCode } from './http/handler-utils.ts';
+import { symlinkReachesPrivateState } from './incoming-symlink-guard.ts';
import type { PinoLogger } from './logger.ts';
export class SymlinkEscapeError extends Error {
@@ -12,6 +13,13 @@ export class SymlinkEscapeError extends Error {
}
}
+export class PrivateStateSymlinkError extends SymlinkEscapeError {
+ constructor() {
+ super('path resolves into private repository state');
+ this.name = 'PrivateStateSymlinkError';
+ }
+}
+
export class ContentRootUnavailableError extends Error {
constructor(message: string) {
super(message);
@@ -19,6 +27,40 @@ export class ContentRootUnavailableError extends Error {
}
}
+function contentRelative(root: string, path: string): string {
+ return relative(root, path).split(sep).join('/');
+}
+
+export function resolvesIntoPrivateState(
+ requestedPath: string,
+ canonicalPath: string,
+ contentRoot: string,
+): boolean {
+ return symlinkReachesPrivateState(
+ contentRelative(contentRoot, requestedPath),
+ contentRelative(contentRoot, canonicalPath),
+ );
+}
+
+export function canonicalContentPathIsRefused(
+ requestedPath: string,
+ canonicalPath: string,
+ contentDir: string,
+): boolean {
+ let contentRoot = contentDir;
+ try {
+ contentRoot = realpathSync(contentDir);
+ } catch {
+ return true;
+ }
+ if (!isWithinContentDir(canonicalPath, contentRoot)) return true;
+ const lexicalRoot = isWithinContentDir(requestedPath, contentDir) ? contentDir : contentRoot;
+ return symlinkReachesPrivateState(
+ contentRelative(lexicalRoot, requestedPath),
+ contentRelative(contentRoot, canonicalPath),
+ );
+}
+
export function assertNoSymlinkEscape(fullPath: string, resolvedContentDir: string): void {
let contentRoot: string;
try {
@@ -38,6 +80,18 @@ export function assertNoSymlinkEscape(fullPath: string, resolvedContentDir: stri
if (!isWithinContentDir(canonical, contentRoot)) {
throw new SymlinkEscapeError('path resolves outside content directory');
}
+ const lexicalRoot = isWithinContentDir(fullPath, resolvedContentDir)
+ ? resolvedContentDir
+ : contentRoot;
+ if (
+ resolvesIntoPrivateState(
+ join(contentRoot, relative(lexicalRoot, fullPath)),
+ join(canonical, relative(cur, fullPath)),
+ contentRoot,
+ )
+ ) {
+ throw new PrivateStateSymlinkError();
+ }
return;
} catch (err) {
const code = errnoCode(err);
diff --git a/packages/server/src/git-checkout.ts b/packages/server/src/git-checkout.ts
index 4b271ff4d..379294dae 100644
--- a/packages/server/src/git-checkout.ts
+++ b/packages/server/src/git-checkout.ts
@@ -9,7 +9,6 @@ import { dirtyFilesOverlapWith } from './git-dirty.ts';
import { createGitInstance } from './git-handle.ts';
import {
assertIncomingSymlinksSafe,
- escapePathForDisplay,
resolveIncomingCommit,
UnsafeIncomingSymlinkError,
} from './incoming-symlink-guard.ts';
@@ -118,9 +117,7 @@ export async function runCheckoutFlow(
return {
ok: false,
reason: 'unsafe-symlinks',
- refusedSymlinkPaths: err.unsafe
- .slice(0, REFUSED_SYMLINK_PATHS_CAP)
- .map(({ path }) => escapePathForDisplay(path)),
+ refusedSymlinkPaths: err.displayPaths(),
};
}
log.warn({ branch, target, err }, `action=symlink-check-failed branch=${branch}`);
diff --git a/packages/server/src/http/file-ops-routes.ts b/packages/server/src/http/file-ops-routes.ts
index fef708630..28ccbf084 100644
--- a/packages/server/src/http/file-ops-routes.ts
+++ b/packages/server/src/http/file-ops-routes.ts
@@ -50,7 +50,11 @@ import {
stripDocExtension,
} from '../doc-extensions.ts';
import { extractActorIdentity } from '../extract-actor-identity.ts';
-import { canonicalRelPathForNewTarget, isContainmentRejection } from '../fs-safety.ts';
+import {
+ canonicalRelPathForNewTarget,
+ isContainmentRejection,
+ PrivateStateSymlinkError,
+} from '../fs-safety.ts';
import { classifyFsPath, normalizeFsPath } from '../fs-traced.ts';
import type { PinoLogger } from '../logger.ts';
import { createMultipartParser, type MultipartParser } from '../multipart.ts';
@@ -372,8 +376,8 @@ export function createFileOpsRoutes(deps: FileOpsRouteDeps): ApiRouteGroup {
let fullPath: string;
try {
fullPath = resolveContentEntryPath(contentDir, 'folder', lexicalRelPath);
- } catch {
- return false;
+ } catch (err) {
+ return err instanceof PrivateStateSymlinkError;
}
return isReservedProjectStatePath(
canonicalRelPathForNewTarget(fullPath, resolve(contentDir), log),
diff --git a/packages/server/src/http/local-op-routes.ts b/packages/server/src/http/local-op-routes.ts
index e9248dad1..b2c0c50dc 100644
--- a/packages/server/src/http/local-op-routes.ts
+++ b/packages/server/src/http/local-op-routes.ts
@@ -200,6 +200,14 @@ export function createLocalOpRoutes(
cloneCompleteDir = event.dir;
return;
}
+ if (event.type === 'error' && event.code === 'unsafe-symlinks') {
+ log.warn(
+ { url, dir, refusedSymlinkPaths: event.refusedSymlinkPaths ?? [] },
+ '[local-op/clone] clone refused: the repository has unsafe symlinks',
+ );
+ writeStreamError(500, 'urn:ok:error:clone-failed', event.message);
+ return;
+ }
if (event.type === 'error') {
if (event.message) {
log.warn(
diff --git a/packages/server/src/incoming-symlink-guard.ts b/packages/server/src/incoming-symlink-guard.ts
index e326f914d..fc24195ed 100644
--- a/packages/server/src/incoming-symlink-guard.ts
+++ b/packages/server/src/incoming-symlink-guard.ts
@@ -6,9 +6,11 @@ import {
OK_MACHINE_LOCAL_ROOT_DIRS,
OK_MACHINE_LOCAL_ROOT_FILES,
OK_USER_HOME_CREDENTIAL_FILES,
+ REFUSED_SYMLINK_PATHS_CAP,
} from '@inkeep/open-knowledge-core';
import type { SimpleGit } from 'simple-git';
import { isSecretBearingFile, pathHasSecretBearingDirSegment } from './content-filter.ts';
+import { createGitInstance } from './git-handle.ts';
import { compareSemver, parseGitVersion } from './git-preflight.ts';
import { errnoCode } from './http/handler-utils.ts';
@@ -151,8 +153,8 @@ interface WalkOutcome {
complete: boolean;
}
-function touchesPrivateState(folded: readonly string[]): boolean {
- return folded.some(
+function privateStateIndex(folded: readonly string[]): number {
+ return folded.findIndex(
(segment, index) =>
isGitDirName(segment) ||
(isConfigDirName(segment) &&
@@ -160,6 +162,24 @@ function touchesPrivateState(folded: readonly string[]): boolean {
);
}
+function touchesPrivateState(folded: readonly string[]): boolean {
+ return privateStateIndex(folded) >= 0;
+}
+
+export function symlinkReachesPrivateState(lexicalRel: string, canonicalRel: string): boolean {
+ const lexical = foldPath(lexicalRel).split('/');
+ const canonical = foldPath(canonicalRel).split('/');
+ if (lexical.join('/') === canonical.join('/')) return false;
+ const index = privateStateIndex(canonical);
+ if (index < 0) return false;
+ const last = canonical.length - 1;
+ const spelledFolderConfigDir =
+ index === last &&
+ isConfigDirName(canonical[last] ?? '') &&
+ lexical[lexical.length - 1] === canonical[last];
+ return !spelledFolderConfigDir;
+}
+
function isUnverifiableTarget(target: string): boolean {
return (
target === '' ||
@@ -541,10 +561,14 @@ async function findUnsafeIncomingSymlinks(
incoming: string,
landing: IncomingLanding,
env: NodeJS.ProcessEnv | undefined,
+ base: 'head' | 'empty-tree' = 'head',
): Promise<UnsafeIncomingSymlink[]> {
const repoRoot = (await git.raw(['rev-parse', '--show-toplevel'])).trim();
if (repoRoot === '') throw new Error('could not resolve the repository root');
- const head = (await git.raw(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'])).trim();
+ const head =
+ base === 'empty-tree'
+ ? ''
+ : (await git.raw(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'])).trim();
const inspection = await inspect(
git,
repoRoot,
@@ -680,7 +704,7 @@ function describeSymlinkReason(reason: UnsafeSymlinkReason): string {
}
}
-export function escapePathForDisplay(path: string): string {
+function escapePathForDisplay(path: string): string {
return JSON.stringify(path)
.slice(1, -1)
.replace(INVISIBLE_CHARACTERS, (character) =>
@@ -700,6 +724,12 @@ export class UnsafeIncomingSymlinkError extends Error {
this.unsafe = unsafe;
}
+ displayPaths(): string[] {
+ return this.unsafe
+ .slice(0, REFUSED_SYMLINK_PATHS_CAP)
+ .map(({ path }) => escapePathForDisplay(path));
+ }
+
describeLinks(): string {
const shown = this.unsafe
.slice(0, REPORTED_PATH_LIMIT)
@@ -727,6 +757,21 @@ export async function assertIncomingSymlinksSafe(
if (unsafe.length > 0) throw new UnsafeIncomingSymlinkError(unsafe);
}
+export async function assertCheckoutSymlinksSafe(
+ git: SimpleGit,
+ ref: string,
+ env?: NodeJS.ProcessEnv,
+): Promise<void> {
+ const commit = await resolveIncomingCommit(git, ref);
+ const unsafe = await findUnsafeIncomingSymlinks(git, commit, 'checkout', env, 'empty-tree');
+ if (unsafe.length > 0) throw new UnsafeIncomingSymlinkError(unsafe);
+}
+
+export async function assertRepoCheckoutSymlinksSafe(repoDir: string, ref: string): Promise<void> {
+ const handle = createGitInstance(repoDir, { credentialConfig: [] });
+ await assertCheckoutSymlinksSafe(handle.git, ref, handle.env);
+}
+
export class IncomingRefMovedError extends Error {
readonly ref: string;
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 065dc6fad..212b58558 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -279,8 +279,10 @@ export {
type IdleShutdownHandle,
} from './idle-shutdown.ts';
export {
+ assertCheckoutSymlinksSafe,
assertIncomingSymlinksSafe,
assertMergeNameResolvesTo,
+ assertRepoCheckoutSymlinksSafe,
SYMLINK_MERGE_MIN_GIT_LABEL,
SYMLINK_MERGE_MIN_GIT_VERSION,
type UnsafeIncomingSymlink,
diff --git a/packages/server/src/local-ops/clone-flow.test.ts b/packages/server/src/local-ops/clone-flow.test.ts
index 0b279bf23..b9241bcff 100644
--- a/packages/server/src/local-ops/clone-flow.test.ts
+++ b/packages/server/src/local-ops/clone-flow.test.ts
@@ -1,10 +1,12 @@
import { homedir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
+import { classifyCloneError } from './clone-error-classify.ts';
import {
type RawCloneEvent,
type RunCloneController,
runCloneSubprocess,
+ UNSAFE_SYMLINKS_CLONE_MESSAGE,
validateCloneInputs,
} from './clone-flow.ts';
@@ -147,6 +149,33 @@ describe('runCloneSubprocess', () => {
expect(events[0]).toEqual({ type: 'error', message: 'permission denied' });
});
+ test('an unsafe-symlink refusal reaches the consumer with fixed wording and a structured path list', async () => {
+ const events: RawCloneEvent[] = [];
+ const ctrl = runCloneSubprocess({
+ cliArgs: fixtureCli(`
+ console.log(JSON.stringify({
+ type: 'error',
+ code: 'unsafe-symlinks',
+ message: 'permission denied: docs/permission denied.md',
+ refusedSymlinkPaths: ['docs/permission denied.md', 42, ''],
+ }));
+ `),
+ url: 'https://github.com/octocat/linked.git',
+ dir: '/tmp/linked',
+ onEvent: (e) => events.push(e),
+ });
+ await ctrl.done;
+ expect(events).toEqual([
+ {
+ type: 'error',
+ code: 'unsafe-symlinks',
+ message: UNSAFE_SYMLINKS_CLONE_MESSAGE,
+ refusedSymlinkPaths: ['docs/permission denied.md'],
+ },
+ ]);
+ expect(classifyCloneError(UNSAFE_SYMLINKS_CLONE_MESSAGE).title).not.toMatch(/access/i);
+ });
+
test('CLI-emitted error message is redacted and capped before it reaches the consumer', async () => {
const events: RawCloneEvent[] = [];
const token = `ghp_${'b'.repeat(36)}`;
diff --git a/packages/server/src/local-ops/clone-flow.ts b/packages/server/src/local-ops/clone-flow.ts
index 9540687c3..4031c857b 100644
--- a/packages/server/src/local-ops/clone-flow.ts
+++ b/packages/server/src/local-ops/clone-flow.ts
@@ -1,4 +1,5 @@
import { dirname, isAbsolute } from 'node:path';
+import { REFUSED_SYMLINK_PATHS_CAP } from '@inkeep/open-knowledge-core';
import {
assertGitAvailable,
type GitDetected,
@@ -13,11 +14,19 @@ import { type LocalOpCliInvocation, runSubprocess } from './subprocess.ts';
const log = getLogger('clone-flow');
+export const UNSAFE_SYMLINKS_CLONE_MESSAGE =
+ 'The repository has symlinks that are unsafe to check out, so the clone was removed. Fix or remove those links on the remote, then clone again.';
+
export type RawCloneEvent =
| { type: 'progress'; phase: string; pct: number }
| { type: 'complete'; dir: string }
| { type: 'branch-fallback'; branch: string }
- | { type: 'error'; message: string };
+ | {
+ type: 'error';
+ message: string;
+ code?: 'unsafe-symlinks';
+ refusedSymlinkPaths?: string[];
+ };
export interface RunCloneOptions extends LocalOpCliInvocation {
url: string;
@@ -62,6 +71,17 @@ function asRawCloneEvent(parsed: Record<string, unknown>): RawCloneEvent | null
}
return null;
}
+ if (type === 'error' && parsed.code === 'unsafe-symlinks') {
+ const paths = Array.isArray(parsed.refusedSymlinkPaths) ? parsed.refusedSymlinkPaths : [];
+ return {
+ type: 'error',
+ code: 'unsafe-symlinks',
+ message: UNSAFE_SYMLINKS_CLONE_MESSAGE,
+ refusedSymlinkPaths: paths
+ .filter((path): path is string => typeof path === 'string' && path.length > 0)
+ .slice(0, REFUSED_SYMLINK_PATHS_CAP),
+ };
+ }
if (type === 'error') {
const message = typeof parsed.message === 'string' ? redactedStderrDetail(parsed.message) : '';
return { type: 'error', message: message || 'Unknown error' };
diff --git a/packages/server/src/mcp-mount.test.ts b/packages/server/src/mcp-mount.test.ts
index 3a4f88027..e01759cc6 100644
--- a/packages/server/src/mcp-mount.test.ts
+++ b/packages/server/src/mcp-mount.test.ts
@@ -399,6 +399,7 @@ describe('mountMcpAndApi content-asset middleware', () => {
hocuspocus,
log,
contentAssetMiddleware: createAssetServeMiddleware({
+ contentDir,
contentFilter: filter,
contentSirv: sirv(contentDir, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
@@ -499,6 +500,7 @@ describe('mountMcpAndApi ephemeral content-asset gate', () => {
log,
ephemeral,
contentAssetMiddleware: createAssetServeMiddleware({
+ contentDir,
contentFilter: { isPathIgnored: () => false },
contentSirv: sirv(contentDir, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
@@ -598,6 +600,7 @@ describe('mountMcpAndApi react-shell middleware', () => {
tmpDirs.push(contentDir);
const filter = { isPathIgnored: () => false };
const contentAssetMiddleware = createAssetServeMiddleware({
+ contentDir,
contentFilter: filter,
contentSirv: sirv(contentDir, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
@@ -634,6 +637,7 @@ describe('mountMcpAndApi react-shell middleware', () => {
writeFileSync(join(contentDir, 'assets', 'user-upload.png'), bytes);
const filter = { isPathIgnored: () => false };
const contentAssetMiddleware = createAssetServeMiddleware({
+ contentDir,
contentFilter: filter,
contentSirv: sirv(contentDir, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
@@ -657,6 +661,7 @@ describe('mountMcpAndApi react-shell middleware', () => {
writeFileSync(join(contentDir, 'assets', 'inter-cafebabe.woff2'), contentBytes);
const filter = { isPathIgnored: () => false };
const contentAssetMiddleware = createAssetServeMiddleware({
+ contentDir,
contentFilter: filter,
contentSirv: sirv(contentDir, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
@@ -677,6 +682,7 @@ describe('mountMcpAndApi react-shell middleware', () => {
tmpDirs.push(contentDir);
const filter = { isPathIgnored: () => false };
const contentAssetMiddleware = createAssetServeMiddleware({
+ contentDir,
contentFilter: filter,
contentSirv: sirv(contentDir, { dev: true, dotfiles: false }),
inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
diff --git a/packages/server/src/mermaid-persistence.ts b/packages/server/src/mermaid-persistence.ts
index 83a847ead..cca8c339f 100644
--- a/packages/server/src/mermaid-persistence.ts
+++ b/packages/server/src/mermaid-persistence.ts
@@ -10,6 +10,7 @@ import { LINEAGE_EPOCH_KEY } from '@inkeep/open-knowledge-core';
import { atomicWriteFile } from '@inkeep/open-knowledge-core/server';
import type * as Y from 'yjs';
import { docNameToRelativePath } from './doc-extensions.ts';
+import { assertNoSymlinkEscape } from './fs-safety.ts';
import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
import { getLogger } from './logger.ts';
import { isWithinDir } from './path-utils.ts';
@@ -64,6 +65,7 @@ export function loadMermaidDoc(
let raw: string;
try {
+ assertNoSymlinkEscape(filePath, ctx.contentDir);
raw = readFileSync(filePath, 'utf-8');
} catch (e) {
log.warn({ documentName, err: e }, 'load: could not read; seeding empty');
@@ -88,6 +90,7 @@ export async function storeMermaidDoc(
const filePath = mermaidAbsPath(documentName, ctx.contentDir);
try {
+ assertNoSymlinkEscape(filePath, ctx.contentDir);
await tracedMkdir(resolve(filePath, '..'), { recursive: true });
if (existsSync(filePath)) {
diff --git a/packages/server/src/persistence-tripwire-symlink.test.ts b/packages/server/src/persistence-tripwire-symlink.test.ts
index 353f7688f..04b64e99e 100644
--- a/packages/server/src/persistence-tripwire-symlink.test.ts
+++ b/packages/server/src/persistence-tripwire-symlink.test.ts
@@ -1,4 +1,5 @@
import {
+ mkdirSync,
mkdtempSync,
readFileSync,
realpathSync,
@@ -96,4 +97,44 @@ describe('tripwire reset symlink-escape', () => {
expect(readFileSync(secretPath, 'utf-8')).toBe(secretContent);
});
+
+ test('refuses to load an in-root link into machine-local state into Y.Doc', async () => {
+ const docName = 'incident-tripwire-private-link';
+ const baseMarkdown = loadFixture('incident-changeset-readme-doubled.base.md');
+ const doubledMarkdown = loadFixture('incident-changeset-readme-doubled.candidate.md');
+
+ mkdirSync(join(contentDir, '.ok', 'local'), { recursive: true });
+ const principalPath = join(contentDir, '.ok', 'local', 'principal.json');
+ writeFileSync(principalPath, secretContent, 'utf-8');
+ symlinkSync('.ok/local/principal.json', join(contentDir, `${docName}.md`));
+
+ const persistence = createPersistenceExtension({
+ contentDir,
+ projectDir: contentDir,
+ gitEnabled: false,
+ durabilityState,
+ });
+
+ const document = new Y.Doc();
+ composeAndWriteRawBody(document, doubledMarkdown, 'agent');
+ durabilityState.setReconciledBase(docName, baseMarkdown);
+
+ const warnSpy = vi.spyOn(getLogger('persistence'), 'warn');
+ try {
+ await storeDocument(persistence, document, docName).catch(() => {});
+
+ const ytextAfter = document.getText('source').toString();
+ expect(ytextAfter).not.toContain('SECRET');
+ expect(ytextAfter).not.toContain('lives outside the content root');
+
+ const escapeWarning = warnSpy.mock.calls
+ .map((call) => String(call[1] ?? ''))
+ .find((s) => s.includes('symlink-escape on tripwire reset'));
+ expect(escapeWarning).toBeDefined();
+ } finally {
+ warnSpy.mockRestore();
+ }
+
+ expect(readFileSync(principalPath, 'utf-8')).toBe(secretContent);
+ });
});
diff --git a/packages/server/src/persistence.test.ts b/packages/server/src/persistence.test.ts
index 85aa65ef8..307c929c2 100644
--- a/packages/server/src/persistence.test.ts
+++ b/packages/server/src/persistence.test.ts
@@ -3,6 +3,7 @@ import {
lstatSync,
mkdirSync,
mkdtempSync,
+ readdirSync,
readFileSync,
realpathSync,
rmSync,
@@ -232,6 +233,182 @@ describe('symlink-safe atomic write', () => {
});
});
+describe('persistence refuses links into private repository state', () => {
+ const SECRET = '{"token":"machine-local-secret"}';
+ const GIT_CONFIG = '[core]\n\tbare = false\n';
+ let contentDir: string;
+
+ beforeEach(() => {
+ contentDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-private-link-persistence-')));
+ mkdirSync(join(contentDir, '.ok', 'local'), { recursive: true });
+ mkdirSync(join(contentDir, '.git'), { recursive: true });
+ mkdirSync(join(contentDir, 'notes'), { recursive: true });
+ mkdirSync(join(contentDir, 'shared'), { recursive: true });
+ writeFileSync(join(contentDir, '.ok', 'local', 'principal.json'), SECRET);
+ writeFileSync(join(contentDir, '.git', 'config'), GIT_CONFIG);
+ });
+
+ afterEach(() => {
+ rmSync(contentDir, { recursive: true, force: true });
+ });
+
+ function createPersistence(durabilityState = new DocumentDurabilityState()) {
+ return createPersistenceExtension({
+ contentDir,
+ projectDir: contentDir,
+ gitEnabled: false,
+ durabilityState,
+ });
+ }
+
+ async function storeDocument(
+ persistence: ReturnType<typeof createPersistenceExtension>,
+ document: Y.Doc,
+ documentName: string,
+ ): Promise<void> {
+ await persistence.extension.onStoreDocument?.({
+ document,
+ documentName,
+ lastTransactionOrigin: {
+ source: 'connection',
+ connection: { context: { principalId: 'principal-test' } },
+ },
+ lastContext: {},
+ } as never);
+ }
+
+ test('load leaves a doc linked to machine-local state empty', async () => {
+ symlinkSync('../.ok/local/principal.json', join(contentDir, 'notes', 'leak.md'));
+ const persistence = createPersistence();
+ const document = new Y.Doc();
+
+ await persistence.extension.onLoadDocument?.({
+ document,
+ documentName: 'notes/leak',
+ context: {},
+ } as never);
+
+ expect(document.getText('source').toString()).toBe('');
+ document.destroy();
+ });
+
+ test('store refuses to write through a link to the git config', async () => {
+ const linkPath = join(contentDir, 'notes', 'cfg.md');
+ symlinkSync('../.git/config', linkPath);
+ const durabilityState = new DocumentDurabilityState();
+ durabilityState.setReconciledBase('notes/cfg', '# Loaded before the link appeared\n');
+ const persistence = createPersistence(durabilityState);
+ const document = new Y.Doc();
+ composeAndWriteRawBody(document, '# Overwrite\n', 'test');
+
+ await expect(storeDocument(persistence, document, 'notes/cfg')).rejects.toThrow(
+ 'symlink-escape',
+ );
+
+ expect(readFileSync(join(contentDir, '.git', 'config'), 'utf-8')).toBe(GIT_CONFIG);
+ expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);
+ document.destroy();
+ });
+
+ test('store refuses a new doc under a directory link into .git', async () => {
+ symlinkSync('../.git', join(contentDir, 'notes', 'repo'));
+ const persistence = createPersistence();
+ const document = new Y.Doc();
+ composeAndWriteRawBody(document, '# Planted\n', 'test');
+
+ await expect(storeDocument(persistence, document, 'notes/repo/planted')).rejects.toThrow(
+ 'symlink-escape',
+ );
+
+ expect(existsSync(join(contentDir, '.git', 'planted.md'))).toBe(false);
+ document.destroy();
+ });
+
+ test('load leaves a Mermaid doc linked to the git config empty', async () => {
+ symlinkSync('../.git/config', join(contentDir, 'notes', 'cfg.mmd'));
+ const persistence = createPersistence();
+ const document = new Y.Doc();
+
+ await persistence.extension.onLoadDocument?.({
+ document,
+ documentName: 'notes/cfg.mmd',
+ context: {},
+ } as never);
+
+ expect(document.getText('source').toString()).toBe('');
+ document.destroy();
+ });
+
+ test('load leaves an editable text doc linked outside the content dir empty', async () => {
+ const outsideDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-private-link-outside-')));
+ try {
+ writeFileSync(join(outsideDir, 'secret.ts'), 'export const secret = 1;\n');
+ symlinkSync(join(outsideDir, 'secret.ts'), join(contentDir, 'notes', 'outside.ts'));
+ const persistence = createPersistence();
+ const document = new Y.Doc();
+
+ await persistence.extension.onLoadDocument?.({
+ document,
+ documentName: 'notes/outside.ts',
+ context: {},
+ } as never);
+
+ expect(document.getText('source').toString()).toBe('');
+ document.destroy();
+ } finally {
+ rmSync(outsideDir, { recursive: true, force: true });
+ }
+ });
+
+ test('store neither reads nor replaces a Mermaid doc linked into machine-local state', async () => {
+ const linkPath = join(contentDir, 'notes', 'leak.mmd');
+ symlinkSync('../.ok/local/principal.json', linkPath);
+ const persistence = createPersistence();
+ const document = new Y.Doc();
+ document.getText('source').insert(0, 'graph TD; A-->B;\n');
+
+ await storeDocument(persistence, document, 'notes/leak.mmd');
+
+ expect(document.getText('source').toString()).toBe('graph TD; A-->B;\n');
+ expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);
+ expect(readFileSync(join(contentDir, '.ok', 'local', 'principal.json'), 'utf-8')).toBe(SECRET);
+ document.destroy();
+ });
+
+ test('store does not write a Mermaid doc under a directory link outside the content dir', async () => {
+ const outsideDir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-private-link-outside-')));
+ try {
+ symlinkSync(outsideDir, join(contentDir, 'notes', 'away'));
+ const persistence = createPersistence();
+ const document = new Y.Doc();
+ document.getText('source').insert(0, 'graph TD; A-->B;\n');
+
+ await storeDocument(persistence, document, 'notes/away/flow.mmd');
+
+ expect(readdirSync(outsideDir)).toEqual([]);
+ document.destroy();
+ } finally {
+ rmSync(outsideDir, { recursive: true, force: true });
+ }
+ });
+
+ test('store still writes through an in-root link to ordinary content', async () => {
+ const targetPath = join(contentDir, 'shared', 'a.md');
+ const linkPath = join(contentDir, 'notes', 'alias.md');
+ writeFileSync(targetPath, '# Before\n');
+ symlinkSync('../shared/a.md', linkPath);
+ const persistence = createPersistence();
+ const document = new Y.Doc();
+ composeAndWriteRawBody(document, '# After\n', 'test');
+
+ await storeDocument(persistence, document, 'notes/alias');
+
+ expect(readFileSync(targetPath, 'utf-8')).toBe('# After\n');
+ expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);
+ document.destroy();
+ });
+});
+
describe('durable derived-index projection', () => {
let contentDir: string;
diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.ts
index bc00c2ddf..73e0d58d9 100644
--- a/packages/server/src/persistence.ts
+++ b/packages/server/src/persistence.ts
@@ -1,6 +1,6 @@
import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
import { realpath } from 'node:fs/promises';
-import { dirname, relative, resolve } from 'node:path';
+import { basename, dirname, join, relative, resolve } from 'node:path';
import type { Extension } from '@hocuspocus/server';
import type { MarkdownManager } from '@inkeep/open-knowledge-core';
import {
@@ -66,6 +66,7 @@ import {
} from './document-durability-state.ts';
import { refuseStaleExternalWrite } from './external-change.ts';
import { contentHash, registerWrite } from './file-watcher.ts';
+import { resolvesIntoPrivateState } from './fs-safety.ts';
import { tracedMkdir, tracedRenameSync, tracedUnlinkSync, tracedWriteFile } from './fs-traced.ts';
import { errnoCode } from './http/handler-utils.ts';
import { getLogger } from './logger.ts';
@@ -929,7 +930,10 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
);
return { kind: 'unavailable', reason: 'read-failed' };
}
- if (!isWithinContentDir(canonical, contentDir)) {
+ if (
+ !isWithinContentDir(canonical, contentDir) ||
+ resolvesIntoPrivateState(requestedDiskPath, canonical, contentDir)
+ ) {
log.warn(
{ docName: documentName, originalPath: requestedDiskPath, canonical, contentDir },
`[persistence] symlink-escape on tripwire reset: ${requestedDiskPath} → ${canonical}, skipping tripwire baseline read`,
@@ -1637,13 +1641,18 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
}
}
- if (!isWithinContentDir(canonicalPath, contentDir)) {
- const msg = `symlink-escape: ${requestedPath} resolves to ${canonicalPath} outside ${contentDir}`;
+ const checkedPath =
+ canonicalPath === requestedPath
+ ? join(await realpath(dirname(requestedPath)), basename(requestedPath))
+ : canonicalPath;
+ const outsideContent = !isWithinContentDir(checkedPath, contentDir);
+ if (outsideContent || resolvesIntoPrivateState(requestedPath, checkedPath, contentDir)) {
+ const msg = `symlink-escape: ${requestedPath} resolves to ${checkedPath} ${outsideContent ? `outside ${contentDir}` : 'inside private repository state'}`;
log.error(
{
docName: documentName,
originalPath: requestedPath,
- canonical: canonicalPath,
+ canonical: checkedPath,
contentDir,
},
`[persistence] ${msg}`,
@@ -2027,7 +2036,10 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
let canonical = filePath;
try {
const resolvedCanonical = realpathSync(filePath);
- if (!isWithinContentDir(resolvedCanonical, contentDir)) {
+ if (
+ !isWithinContentDir(resolvedCanonical, contentDir) ||
+ resolvesIntoPrivateState(filePath, resolvedCanonical, contentDir)
+ ) {
log.warn(
{ path: filePath, canonical: resolvedCanonical },
`[persistence] symlink-escape on load: ${filePath} → ${resolvedCanonical}, refusing`,
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 662a92a48..b697b4597 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -153,6 +153,7 @@ import {
startWatcher,
type WatcherHandle,
} from './file-watcher.ts';
+import { canonicalContentPathIsRefused } from './fs-safety.ts';
import {
normalizeFsPath,
tracedAtomicFs,
@@ -1873,9 +1874,9 @@ export function createServer(options: ServerOptions): ServerInstance {
}
throw err;
}
- if (!isWithinContentDir(canonical, contentDir)) {
+ if (canonicalContentPathIsRefused(requestedPath, canonical, contentDir)) {
throw new StructuralDiskReadError(
- `symlink-escape: ${requestedPath} resolves outside the content dir`,
+ `symlink-escape: ${requestedPath} resolves outside the content dir or into private state`,
);
}
if (size > DOCUMENT_OPEN_BYTE_LIMIT) {
@@ -4212,6 +4213,15 @@ export function createServer(options: ServerOptions): ServerInstance {
continue;
}
+ if (canonicalContentPathIsRefused(filePath, realpathSync(filePath), contentDir)) {
+ rescueUnflushedEditsBeforeTeardown(docName, newBranch, 'branch-switch');
+ document.getMap('lifecycle').set('status', 'deleted-upstream');
+ log.warn(
+ { docName, branch: newBranch },
+ `[branch-switch] tombstone: ${docName} resolves outside the content dir or into private state on ${newBranch}`,
+ );
+ continue;
+ }
const diskContent = readFileSync(filePath, 'utf-8');
if (getReconciledBase(docName) === undefined) {
const ours = serializeDoc(docName) ?? '';
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 3e947ba09..c01fb1ca1 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -66,7 +66,6 @@ import {
import {
assertIncomingSymlinksSafe,
assertMergeNameResolvesTo,
- escapePathForDisplay,
IncomingRefMovedError,
IncomingRefShadowedError,
resolveIncomingCommit,
@@ -2706,7 +2705,7 @@ export class SyncEngine {
op: 'push' | 'pull',
): void {
this.pausedReason = 'unsafe-incoming-symlinks';
- this.refusedSymlinkPaths = error.unsafe.map(({ path }) => escapePathForDisplay(path));
+ this.refusedSymlinkPaths = error.displayPaths();
if (op === 'push') this.clearPushError();
else this.clearPullError();
if (this.state === 'pushing' || this.state === 'pulling' || this.state === 'fetching') {