Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
bound the GitLab namespace depth so an asset URL can't parse as a deeper namespace
[._.]/ Adam Eivye4dfa6992587
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxindex 5bafd12b04..b30b486a65 100644--- a/client/src/components/brain/tabs/LinksTab.jsx+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -60,7 +60,7 @@ const REPO_TYPE_COLOR = 'bg-purple-500/20 text-purple-400 border-purple-500/30';const LINK_TYPE_COLORS = {repo: REPO_TYPE_COLOR,- // Pre-multi-host records still carry `github`; migration 328 renames the+ // Pre-multi-host records still carry `github`; migration 330 renames the// stored value but a peer on older code can still federate one in.github: REPO_TYPE_COLOR,article: 'bg-blue-500/20 text-blue-400 border-blue-500/30',@@ -691,6 +691,11 @@ export default function LinksTab({ onRefresh }) {className="px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm"><option value="repo">Repository</option>+ {/* Pre-multi-host records (and any federated in from a peer on+ older code) still carry `github`. Without an option to match,+ the select renders BLANK on those rows — the value is intact+ but it reads as data loss. */}+ {editForm.linkType === 'github' && <option value="github">GitHub (legacy)</option>}<option value="article">Article</option><option value="documentation">Documentation</option><option value="tool">Tool</option>diff --git a/client/src/components/brain/tabs/LinksTab.test.jsx b/client/src/components/brain/tabs/LinksTab.test.jsxindex 2f763c840f..14594e395e 100644--- a/client/src/components/brain/tabs/LinksTab.test.jsx+++ b/client/src/components/brain/tabs/LinksTab.test.jsx@@ -328,11 +328,39 @@ describe('LinksTab on-demand repo re-study', () => {expect(studyBrainLink).toHaveBeenCalledWith('a',- expect.objectContaining({ pull: true, studyContext: 'look at its offline sync' }),+ // targetAppId is asserted explicitly: dropping it from studyPayload() would+ // silently fall the server back to PortOS rather than fail.+ { pull: true, studyContext: 'look at its offline sync', targetAppId: 'portos-default' },{ silent: true },);});+ it('pre-fills the brief with the one the last study was given', async () => {+ getBrainLinks.mockResolvedValue({+ links: [link('a', 'cloned', {+ localPath: '/repos/example/a',+ repoStudy: { taskId: 'old', studyContext: 'the previous brief' },+ })],+ });+ const { container } = await renderTab();+ await act(async () => { screen.getByRole('button', { name: /update & study/i }).click(); });++ expect(container.querySelector('#restudy-a-study-context').value).toBe('the previous brief');+ });++ it('patches the row with the updated link so the queued chip survives a re-render', async () => {+ const queued = { ...cloned(), repoStudy: { taskId: 'task-1', queuedAt: '2026-01-02T00:00:00.000Z' } };+ studyBrainLink.mockResolvedValue({ taskId: 'task-1', pulled: { ok: true }, link: queued });+ await openStudyForm();++ await act(async () => { screen.getAllByRole('button', { name: /update & study/i }).at(-1).click(); });++ // The form closes and the row now links the queued study — from local state,+ // with no refetch.+ expect(screen.getByRole('link', { name: /repo study/i })).toBeTruthy();+ expect(getBrainLinks).toHaveBeenCalledTimes(1);+ });+it('warns rather than claiming success when the pull failed but the study queued', async () => {studyBrainLink.mockResolvedValue({ taskId: 'task-1', pulled: { ok: false, error: 'diverged' }, link: cloned() });await openStudyForm();diff --git a/client/src/lib/repoUrl.js b/client/src/lib/repoUrl.jsindex e608fe65e6..9a16310f45 100644--- a/client/src/lib/repoUrl.js+++ b/client/src/lib/repoUrl.js@@ -18,31 +18,51 @@// has to be decided deliberately for the new host rather than inherited from// whichever existing host the branch happened to compare against.//-// provider stable id stored on a link record (`repoHost` holds the-// hostname itself)-// nestedNamespaces the host nests groups arbitrarily (GitLab subgroups), so-// everything before the last path segment is the namespace.-// GitHub has no subgroups: anything past owner/repo is a-// deep link.-// flatClonePath LEGACY CARVE-OUT — clone to `<owner>/<repo>` with no-// hostname level, so clones made before PortOS supported a-// second host stay exactly where their link record says they-// are. Never set this for a newly added host.+// provider stable id stored on a link record (`repoHost` holds the+// hostname itself)+// namespace.maxDepth how many path segments before the project may be the+// namespace. 1 = no subgroups (GitHub: anything past+// owner/repo is a deep link). GitLab nests subgroups, but+// the depth is CAPPED rather than unbounded: a bare GitLab+// URL carries no marker separating `group/sub/project` from+// `group/project/route/...`, so an unbounded walk reads a+// project asset URL as a deep namespace and manufactures+// directories INSIDE an existing clone. The cap also bounds+// the on-disk layout, which `repoCloner`'s staging sweep+// derives its recursion depth from.+// namespace.allowDots whether a namespace segment may contain a dot. GitHub+// logins may not; GitLab group paths may. Keeping it off+// for the flat-clone host is also what makes a hostname+// collision impossible (`github.com/gitlab.com/x` cannot+// parse, so it cannot land on another host's clone root).+// flatClonePath LEGACY CARVE-OUT — clone to `<owner>/<repo>` with no+// hostname level, so clones made before PortOS supported a+// second host stay exactly where their link record says+// they are. Never set this for a newly added host.export const REPO_HOSTS = Object.freeze({- 'github.com': { provider: 'github', nestedNamespaces: false, flatClonePath: true },- 'gitlab.com': { provider: 'gitlab', nestedNamespaces: true, flatClonePath: false },+ 'github.com': { provider: 'github', namespace: { maxDepth: 1, allowDots: false }, flatClonePath: true },+ 'gitlab.com': { provider: 'gitlab', namespace: { maxDepth: 3, allowDots: true }, flatClonePath: false },});+/** The deepest `<host>/<namespace…>/<repo>` layout any host in the table produces. */+export const MAX_REPO_PATH_DEPTH = Object.values(REPO_HOSTS).reduce(+ (deepest, { namespace, flatClonePath }) => Math.max(deepest, (flatClonePath ? 0 : 1) + namespace.maxDepth + 1),+ 0,+);+// The owner/repo pair is a PATH OPERAND, not just a label: the cloner clones// into `join(reposDir, …owner, repo)` and the resulting `localPath` is later// handed to an agent as the directory to scan/study. So every segment is// matched against the character sets the hosts actually allow, NOT "anything// but a slash" — the loose form parsed `https://github.com/../evil` as owner// `..`, which resolves OUTSIDE the managed clone root.-// owner: a login (or a GitLab group/subgroup) — alphanumeric with internal-// hyphens, no dots, so no segment can ever be `.` or `..`-// repo: alphanumerics plus `_`, `.`, `-`+// owner: a login (or a GitLab group/subgroup). Both forms REQUIRE a leading+// alphanumeric, which is what makes `.` and `..` unrepresentable; the+// dotted form is gated per host (see `namespace.allowDots`).+// repo: alphanumerics plus `_`, `.`, `-` — a leading dot is legal (`.github`+// is a real repository), so dot segments are rejected explicitly below.const OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;+const DOTTED_OWNER_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;const REPO_RE = /^[A-Za-z0-9_.-]+$/;// `REPO_RE`'s character class admits the dot segments `.` and `..`, which would@@ -66,6 +86,11 @@ const RESERVED_PATH_SEGMENTS = new Set(['tree', 'blob', 'raw', 'commit', 'commits', 'compare', 'branches', 'tags','releases', 'issues', 'pull', 'pulls', 'merge_requests', 'wiki', 'wikis','actions', 'pipelines', 'settings', 'activity', 'network', 'graphs', 'blame',+ // GitLab serves these directly off the project path with no `/-/` marker, so+ // without them a badge or upload URL parses as a deeper namespace.+ 'badges', 'uploads', 'archive', 'edit', 'forks', 'starrers', 'members',+ 'artifacts', 'jobs', 'boards', 'milestones', 'labels', 'snippets',+ 'environments', 'analytics', 'insights', 'hooks', 'container_registry',]);/**@@ -82,6 +107,13 @@ const RESERVED_PATH_SEGMENTS = new Set([export function parseRepoUrl(url) {if (!url) return null;const normalized = String(url).trim();+ // A backslash defeats the host anchor: WHATWG maps `\` to `/` inside the+ // authority, so `https://evil.example.com\@github.com/o/r` resolves to+ // evil.example.com in a browser while the regex below reads github.com. The+ // clone would still go to the real github.com (repoCloneUrl rebuilds from the+ // parsed host), but the link would be STORED and rendered as a trusted repo+ // whose href points at the attacker.+ if (normalized.includes('\\')) return null;const match = normalized.match(SSH_RE) || normalized.match(HTTP_RE);if (!match) return null;@@ -104,11 +136,17 @@ export function parseRepoUrl(url) {}if (segments.length < 2) return null;- const ownerSegments = hostConfig.nestedNamespaces ? segments.slice(0, -1) : segments.slice(0, 1);- const repo = (hostConfig.nestedNamespaces ? segments[segments.length - 1] : segments[1])- .replace(/\.git$/i, '');+ const { maxDepth, allowDots } = hostConfig.namespace;+ // Past the cap the path is a deep link into the project, not a deeper+ // namespace — reading it as one would clone into (and create directories+ // inside) an existing checkout.+ if (segments.length > maxDepth + 1) return null;++ const ownerSegments = segments.slice(0, -1);+ const repo = segments[segments.length - 1].replace(/\.git$/i, '');- if (!ownerSegments.every(segment => OWNER_RE.test(segment))) return null;+ const ownerPattern = allowDots ? DOTTED_OWNER_RE : OWNER_RE;+ if (!ownerSegments.every(segment => ownerPattern.test(segment))) return null;if (!repo || DOT_SEGMENTS.has(repo) || !REPO_RE.test(repo)) return null;return {diff --git a/scripts/migrations/328-brain-link-repo-fields.js b/scripts/migrations/330-brain-link-repo-fields.jssimilarity index 99%rename from scripts/migrations/328-brain-link-repo-fields.jsrename to scripts/migrations/330-brain-link-repo-fields.jsindex 99f3d21f62..a556d63a9a 100644--- a/scripts/migrations/328-brain-link-repo-fields.js+++ b/scripts/migrations/330-brain-link-repo-fields.js@@ -32,7 +32,7 @@ import { join } from 'path';import { readJSONFile } from '../../server/lib/fileUtils.js';import { writeJsonAtomic } from './_lib.js';-const LABEL = 'migration 328';+const LABEL = 'migration 330';/** The upgraded record, or null when nothing needs to change. */export function upgradeLinkRecord(record) {diff --git a/scripts/migrations/328-brain-link-repo-fields.test.js b/scripts/migrations/330-brain-link-repo-fields.test.jssimilarity index 96%rename from scripts/migrations/328-brain-link-repo-fields.test.jsrename to scripts/migrations/330-brain-link-repo-fields.test.jsindex 9602b39a27..8af9d300b3 100644--- a/scripts/migrations/328-brain-link-repo-fields.test.js+++ b/scripts/migrations/330-brain-link-repo-fields.test.js@@ -2,12 +2,12 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';-import migration from './328-brain-link-repo-fields.js';+import migration from './330-brain-link-repo-fields.js';const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));-describe('migration 328 — brain link repository fields', () => {+describe('migration 330 — brain link repository fields', () => {let rootDir;let linksDir;diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex ebb6ef2865..7a64f97a27 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -439,7 +439,7 @@ export const reviewOutputSchema = z.object({// =============================================================================// Link type enum. `github` predates multi-host repo support and is retained so-// links stored (or federated from a peer) before migration 328 still validate;+// links stored (or federated from a peer) before migration 330 still validate;// `repo` is what new links are written with.export const linkTypeEnum = z.enum(['repo', 'github', 'article', 'documentation', 'tool', 'reference', 'other']);diff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.jsindex 4fa8a614ab..de9b881f0d 100644--- a/server/lib/brainValidation.test.js+++ b/server/lib/brainValidation.test.js@@ -509,11 +509,12 @@ describe('brainValidation.js', () => {title: 'Example Repository',description: 'A great example repo',note: 'Review before sharing with the team',- linkType: 'github',+ linkType: 'repo',tags: ['reference'],isRepo: true,- gitHubOwner: 'example',- gitHubRepo: 'repo',+ repoHost: 'gitlab.com',+ repoOwner: 'example/group',+ repoName: 'repo',cloneStatus: 'cloned',createdAt: '2026-01-01T00:00:00.000Z',updatedAt: '2026-01-01T00:00:00.000Z'@@ -522,6 +523,25 @@ describe('brainValidation.js', () => {expect(result.success).toBe(true);});+ // The federation contract the compatibility shim exists for: a record+ // written before migration 330 — or arriving from a peer still on the+ // GitHub-only field names — must still validate here.+ it('should validate a pre-migration GitHub-only link record', () => {+ const result = linkRecordSchema.safeParse({+ id: '550e8400-e29b-41d4-a716-446655440000',+ url: 'https://github.com/example/repo',+ title: 'Example Repository',+ linkType: 'github',+ isGitHubRepo: true,+ gitHubOwner: 'example',+ gitHubRepo: 'repo',+ cloneStatus: 'cloned',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z'+ });+ expect(result.success).toBe(true);+ });+it('should reject invalid URL', () => {const record = {id: '550e8400-e29b-41d4-a716-446655440000',diff --git a/server/lib/repoLinkFields.js b/server/lib/repoLinkFields.jsindex b840fcbb69..25106d348d 100644--- a/server/lib/repoLinkFields.js+++ b/server/lib/repoLinkFields.js@@ -4,7 +4,7 @@** The fields used to be GitHub-only (`isGitHubRepo` / `gitHubOwner` /* `gitHubRepo`). They are now host-generic (`isRepo` / `repoHost` / `repoOwner`- * / `repoName`) so gitlab.com repos are first-class, and migration 328 rewrites+ * / `repoName`) so gitlab.com repos are first-class, and migration 330 rewrites* every stored link.** PortOS is DISTRIBUTED and brain links FEDERATE verbatim between peers, so adiff --git a/server/lib/repoUrl.js b/server/lib/repoUrl.jsindex 7602a245e2..25d48ba623 100644--- a/server/lib/repoUrl.js+++ b/server/lib/repoUrl.js@@ -19,31 +19,51 @@// has to be decided deliberately for the new host rather than inherited from// whichever existing host the branch happened to compare against.//-// provider stable id stored on a link record (`repoHost` holds the-// hostname itself)-// nestedNamespaces the host nests groups arbitrarily (GitLab subgroups), so-// everything before the last path segment is the namespace.-// GitHub has no subgroups: anything past owner/repo is a-// deep link.-// flatClonePath LEGACY CARVE-OUT — clone to `<owner>/<repo>` with no-// hostname level, so clones made before PortOS supported a-// second host stay exactly where their link record says they-// are. Never set this for a newly added host.+// provider stable id stored on a link record (`repoHost` holds the+// hostname itself)+// namespace.maxDepth how many path segments before the project may be the+// namespace. 1 = no subgroups (GitHub: anything past+// owner/repo is a deep link). GitLab nests subgroups, but+// the depth is CAPPED rather than unbounded: a bare GitLab+// URL carries no marker separating `group/sub/project` from+// `group/project/route/...`, so an unbounded walk reads a+// project asset URL as a deep namespace and manufactures+// directories INSIDE an existing clone. The cap also bounds+// the on-disk layout, which `repoCloner`'s staging sweep+// derives its recursion depth from.+// namespace.allowDots whether a namespace segment may contain a dot. GitHub+// logins may not; GitLab group paths may. Keeping it off+// for the flat-clone host is also what makes a hostname+// collision impossible (`github.com/gitlab.com/x` cannot+// parse, so it cannot land on another host's clone root).+// flatClonePath LEGACY CARVE-OUT — clone to `<owner>/<repo>` with no+// hostname level, so clones made before PortOS supported a+// second host stay exactly where their link record says+// they are. Never set this for a newly added host.export const REPO_HOSTS = Object.freeze({- 'github.com': { provider: 'github', nestedNamespaces: false, flatClonePath: true },- 'gitlab.com': { provider: 'gitlab', nestedNamespaces: true, flatClonePath: false },+ 'github.com': { provider: 'github', namespace: { maxDepth: 1, allowDots: false }, flatClonePath: true },+ 'gitlab.com': { provider: 'gitlab', namespace: { maxDepth: 3, allowDots: true }, flatClonePath: false },});+/** The deepest `<host>/<namespace…>/<repo>` layout any host in the table produces. */+export const MAX_REPO_PATH_DEPTH = Object.values(REPO_HOSTS).reduce(+ (deepest, { namespace, flatClonePath }) => Math.max(deepest, (flatClonePath ? 0 : 1) + namespace.maxDepth + 1),+ 0,+);+// The owner/repo pair is a PATH OPERAND, not just a label: the cloner clones// into `join(reposDir, …owner, repo)` and the resulting `localPath` is later// handed to an agent as the directory to scan/study. So every segment is// matched against the character sets the hosts actually allow, NOT "anything// but a slash" — the loose form parsed `https://github.com/../evil` as owner// `..`, which resolves OUTSIDE the managed clone root.-// owner: a login (or a GitLab group/subgroup) — alphanumeric with internal-// hyphens, no dots, so no segment can ever be `.` or `..`-// repo: alphanumerics plus `_`, `.`, `-`+// owner: a login (or a GitLab group/subgroup). Both forms REQUIRE a leading+// alphanumeric, which is what makes `.` and `..` unrepresentable; the+// dotted form is gated per host (see `namespace.allowDots`).+// repo: alphanumerics plus `_`, `.`, `-` — a leading dot is legal (`.github`+// is a real repository), so dot segments are rejected explicitly below.const OWNER_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;+const DOTTED_OWNER_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;const REPO_RE = /^[A-Za-z0-9_.-]+$/;// `REPO_RE`'s character class admits the dot segments `.` and `..`, which would@@ -67,6 +87,11 @@ const RESERVED_PATH_SEGMENTS = new Set(['tree', 'blob', 'raw', 'commit', 'commits', 'compare', 'branches', 'tags','releases', 'issues', 'pull', 'pulls', 'merge_requests', 'wiki', 'wikis','actions', 'pipelines', 'settings', 'activity', 'network', 'graphs', 'blame',+ // GitLab serves these directly off the project path with no `/-/` marker, so+ // without them a badge or upload URL parses as a deeper namespace.+ 'badges', 'uploads', 'archive', 'edit', 'forks', 'starrers', 'members',+ 'artifacts', 'jobs', 'boards', 'milestones', 'labels', 'snippets',+ 'environments', 'analytics', 'insights', 'hooks', 'container_registry',]);/**@@ -83,6 +108,13 @@ const RESERVED_PATH_SEGMENTS = new Set([export function parseRepoUrl(url) {if (!url) return null;const normalized = String(url).trim();+ // A backslash defeats the host anchor: WHATWG maps `\` to `/` inside the+ // authority, so `https://evil.example.com\@github.com/o/r` resolves to+ // evil.example.com in a browser while the regex below reads github.com. The+ // clone would still go to the real github.com (repoCloneUrl rebuilds from the+ // parsed host), but the link would be STORED and rendered as a trusted repo+ // whose href points at the attacker.+ if (normalized.includes('\\')) return null;const match = normalized.match(SSH_RE) || normalized.match(HTTP_RE);if (!match) return null;@@ -105,11 +137,17 @@ export function parseRepoUrl(url) {}if (segments.length < 2) return null;- const ownerSegments = hostConfig.nestedNamespaces ? segments.slice(0, -1) : segments.slice(0, 1);- const repo = (hostConfig.nestedNamespaces ? segments[segments.length - 1] : segments[1])- .replace(/\.git$/i, '');+ const { maxDepth, allowDots } = hostConfig.namespace;+ // Past the cap the path is a deep link into the project, not a deeper+ // namespace — reading it as one would clone into (and create directories+ // inside) an existing checkout.+ if (segments.length > maxDepth + 1) return null;++ const ownerSegments = segments.slice(0, -1);+ const repo = segments[segments.length - 1].replace(/\.git$/i, '');- if (!ownerSegments.every(segment => OWNER_RE.test(segment))) return null;+ const ownerPattern = allowDots ? DOTTED_OWNER_RE : OWNER_RE;+ if (!ownerSegments.every(segment => ownerPattern.test(segment))) return null;if (!repo || DOT_SEGMENTS.has(repo) || !REPO_RE.test(repo)) return null;return {diff --git a/server/lib/repoUrl.test.js b/server/lib/repoUrl.test.jsindex 421f988c79..d5c91ba475 100644--- a/server/lib/repoUrl.test.js+++ b/server/lib/repoUrl.test.js@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest';import { posixPath } from './testHelper.js';import { join } from 'path';-import { parseRepoUrl, isRepoUrl, repoCloneUrl, repoBrowseUrl, parseGitHubUrl, isGitHubRepoUrl } from './repoUrl.js';+import { MAX_REPO_PATH_DEPTH, parseRepoUrl, isRepoUrl, repoCloneUrl, repoBrowseUrl, parseGitHubUrl, isGitHubRepoUrl } from './repoUrl.js';const REPOS_ROOT = '/data/repos';const clonePath = (url) => {@@ -137,6 +137,48 @@ describe('parseRepoUrl across hosts', () => {.toMatchObject({ owner: 'example-owner', repo: 'example-repo' });});+ // Without a depth cap, a project asset URL reads as a DEEPER NAMESPACE, and+ // the cloner then manufactures directories inside the existing acme/widgets+ // checkout before the clone of "pipeline.svg" fails.+ it('reads a GitLab project asset path as the project, not a deeper namespace', () => {+ for (const url of [+ 'https://gitlab.com/acme/widgets/badges/main/pipeline.svg',+ 'https://gitlab.com/acme/widgets/uploads/abc/screenshot.png',+ 'https://gitlab.com/acme/widgets/edit',+ ]) {+ expect(parseRepoUrl(url), url).toMatchObject({ owner: 'acme', repo: 'widgets' });+ }+ });++ it('caps the GitLab namespace depth instead of walking an unbounded path', () => {+ expect(parseRepoUrl('https://gitlab.com/g1/g2/g3/example-repo'))+ .toMatchObject({ owner: 'g1/g2/g3', repo: 'example-repo' });+ // Past the cap the extra segments are a deep link, not a namespace — and an+ // unbounded owner would also push the clone below the staging sweep's reach.+ expect(parseRepoUrl('https://gitlab.com/g1/g2/g3/g4/example-repo')).toBeNull();+ });++ it('allows a dot in a GitLab group path but never in a GitHub owner', () => {+ expect(parseRepoUrl('https://gitlab.com/foo.bar/widgets'))+ .toMatchObject({ owner: 'foo.bar', repo: 'widgets' });+ // A dotted GitHub owner is not a real login, and admitting one would let+ // `github.com/gitlab.com/x` land on the gitlab clone root (GitHub clones use+ // the flat layout, so its owner segment IS the top level).+ expect(parseRepoUrl('https://github.com/gitlab.com/foo')).toBeNull();+ });++ // WHATWG maps a backslash to a slash inside the authority, so a browser+ // resolves this to evil.example.com while a naive regex reads github.com.+ it('refuses a backslash that would spoof the host past the anchor', () => {+ expect(parseRepoUrl(String.raw`https://evil.example.com\@github.com/example-owner/example-repo`)).toBeNull();+ expect(parseRepoUrl(String.raw`https://github.com\evil.example.com/o/r`)).toBeNull();+ });++ it('derives the clone-path depth bound from the host table', () => {+ // repos/<host>/<group>/<subgroup>/<subsubgroup>/<repo>+ expect(MAX_REPO_PATH_DEPTH).toBe(5);+ });+it('refuses an unsupported host and a path-unsafe GitLab namespace', () => {expect(parseRepoUrl('https://bitbucket.org/example-owner/example-repo')).toBeNull();expect(parseRepoUrl('https://gitlab.com/../example-group/example-repo')).toBeNull();diff --git a/server/routes/brainLinks.test.js b/server/routes/brainLinks.test.jsindex b38efb4574..4df35e7081 100644--- a/server/routes/brainLinks.test.js+++ b/server/routes/brainLinks.test.js@@ -248,6 +248,21 @@ describe('POST /api/brain/links/:id/study', () => {expect(brainService.updateLink).not.toHaveBeenCalled();});+ it('maps a missing target app and an unknown reason to distinct errors', async () => {+ restudyRepoLink.mockResolvedValue({ queued: false, reason: 'app-not-found' });+ const missingApp = await request(app).post('/api/brain/links/repo-link/study').send({});+ expect(missingApp.status).toBe(400);+ expect(missingApp.body.code).toBe('APP_NOT_FOUND');++ // Anything the table doesn't name falls back to the clone-gone error rather+ // than to whichever branch happened to be last.+ restudyRepoLink.mockResolvedValue({ queued: false, reason: 'not-cloned' });+ const gone = await request(app).post('/api/brain/links/repo-link/study').send({});+ expect(gone.status).toBe(400);+ expect(gone.body.code).toBe('PATH_NOT_FOUND');+ expect(brainService.updateLink).not.toHaveBeenCalled();+ });+it('rejects a link that has no clone to study', async () => {brainService.getLinkById.mockResolvedValue({ ...cloned(), cloneStatus: 'none', localPath: null });diff --git a/server/services/repoCloner.js b/server/services/repoCloner.jsindex b4de167d0c..74d2d437af 100644--- a/server/services/repoCloner.js+++ b/server/services/repoCloner.js@@ -11,7 +11,7 @@ import { existsSync } from 'fs';import { access, mkdtemp, readdir, rename, rm } from 'fs/promises';import { dirname, join } from 'path';import { ensureDir, PATHS } from '../lib/fileUtils.js';-import { REPO_HOSTS, parseRepoUrl, repoCloneUrl } from '../lib/repoUrl.js';+import { MAX_REPO_PATH_DEPTH, REPO_HOSTS, parseRepoUrl, repoCloneUrl } from '../lib/repoUrl.js';// Default directory for cloned repos (can be configured in settings)const DEFAULT_CLONE_DIR = PATHS.repos;@@ -171,11 +171,18 @@ export async function cloneRepo(url, options = {}) {** The sweep RECURSES because staging sits beside the checkout it will become,* and that is no longer always one level down: a namespaced host adds a- * hostname level and a GitLab subgroup adds another. `MAX_STAGING_DEPTH` bounds- * it to the deepest layout `repoSubPath` can produce, so the sweep never walks- * into the clones themselves.+ * hostname level and each GitLab subgroup adds another. The bound is DERIVED+ * from the host table's namespace caps rather than hardcoded — a hand-picked+ * number silently stops reaping the moment a host's `maxDepth` is raised, and+ * an unreaped interrupted clone is hundreds of MB that nothing ever frees.+ *+ * Staging sits beside the repo segment, so the sweep must be able to LIST the+ * directory one level above the deepest repo — and `sweep` is called with+ * `depth = level + 1` (the repos root itself is depth 1). Recursing into that+ * directory therefore needs the guard to still pass at depth+ * `MAX_REPO_PATH_DEPTH - 1`, which makes the bound `MAX_REPO_PATH_DEPTH` exactly.*/-const MAX_STAGING_DEPTH = 4;+const MAX_STAGING_DEPTH = MAX_REPO_PATH_DEPTH;// A directory holding `.git` is a finished clone, not a namespace level —// descending into it would walk the studied repo's whole source tree.diff --git a/server/services/repoCloner.test.js b/server/services/repoCloner.test.jsindex 89d64445c0..dee47db9bb 100644--- a/server/services/repoCloner.test.js+++ b/server/services/repoCloner.test.js@@ -188,14 +188,18 @@ describe('reapStaleCloneStaging', () => {expect(readdir).not.toHaveBeenCalledWith(LOCAL_PATH, expect.anything());});- it('reaps staging nested under a namespaced host and a GitLab subgroup', async () => {+ // The DEEPEST layout the host table allows: hostname + the full subgroup cap.+ // A hardcoded sweep bound stops one level short of this and leaks the staging+ // tree of every interrupted clone in a deeply-nested group.+ it('reaps staging nested under a namespaced host and the deepest allowed subgroup path', async () => {const hostDir = join(REPOS_DIR, 'gitlab.com');const groupDir = join(hostDir, 'example-group');- const subgroupDir = join(groupDir, 'example-sub');+ const subgroupDir = join(groupDir, 'example-sub', 'example-sub-sub');mockTree({[REPOS_DIR]: [directory('gitlab.com')],[hostDir]: [directory('example-group')],[groupDir]: [directory('example-sub')],+ [join(groupDir, 'example-sub')]: [directory('example-sub-sub')],[subgroupDir]: [directory('.portos-clone-1000000000000-old123')],});