diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ecbd1c15..16d72d5f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,11 @@ jobs: timeout-minutes: 5 run: node scripts/workbench/e2e-deliveries.mjs + - name: Verify opt-in tracked Git inspection after repository packing + if: ${{ !cancelled() && steps.host_tests.outcome == 'success' }} + timeout-minutes: 5 + run: node scripts/workbench/e2e-git-view.mjs + - name: Select the same installed Chrome for UI and worker run: bash scripts/workbench/ci-select-chromium.sh diff --git a/README.en.md b/README.en.md index 17f60e8d..4092eac9 100644 --- a/README.en.md +++ b/README.en.md @@ -341,7 +341,7 @@ When memory is full, the next write by the model first consolidates the existing ## Headless server workbench (fork development) -The [amd64 Docker Compose workbench](apps/headless/README.md) supports browser enrollment, the original desktop model settings, and general text conversations with shared desktop UI, streaming, cancellation and reconnect. It also includes profile and role editing, avatar management, and notes scoped to the owner, a role, or a registered project. Manual workspaces and explicit chat attachments are separate: browsing a project does not send its files to a model. The workbench accepts supported UTF-8 text, static images and PDFs for compatible adapters. Confirmed replies can be exported as Markdown or plain text. Desktop delivery cards are reused for scoped downloads and project file reveal. An [optional human-operated browser](apps/browser-worker/README.md) uses a separate sandboxed worker and an explicit list of sites. The base app requires neither that worker nor a running desktop. This is separate from the mobile relay; see the [parity inventory](docs/development/web-workbench/README.md) for the remaining desktop workflows. +The [amd64 Docker Compose workbench](apps/headless/README.md) supports browser enrollment, the original desktop model settings, and general text conversations with shared desktop UI, streaming, cancellation and reconnect. It also includes profile and role editing, avatar management, and notes scoped to the owner, a role, or a registered project. Manual workspaces and explicit chat attachments are separate: browsing a project does not send its files to a model. Separately approved projects also have a manually activated Git view for tracked changes, branches, first-parent history and staged versus working-tree comparisons. The workbench accepts supported UTF-8 text, static images and PDFs for compatible adapters. Confirmed replies can be exported as Markdown or plain text. Desktop delivery cards are reused for scoped downloads and project file reveal. An [optional human-operated browser](apps/browser-worker/README.md) uses a separate sandboxed worker and an explicit list of sites. The base app requires neither that worker nor a running desktop. This is separate from the mobile relay; see the [parity inventory](docs/development/web-workbench/README.md) for the remaining desktop workflows. ## Build from Source diff --git a/README.md b/README.md index 0630705f..9d6973ce 100644 --- a/README.md +++ b/README.md @@ -332,7 +332,7 @@ IM 机器人支持 `/new [角色名]`、`/list`、`/stop`、`/status`、`/help` ## 无 GUI 服务器工作台(本分支开发中) -[amd64 Docker Compose 与 Web 工作台说明](apps/headless/README.md):当前可在浏览器认领服务器、配置模型,并使用桌面同源的会话列表、编辑器及消息区进行通用文本对话;支持停止与刷新续接。网页还可以编辑个人资料、普通角色及其头像,并分别管理全局、角色和已授权项目的记忆。可手动浏览获准项目的文件,也可显式把所选文本、静态图片或兼容协议的 PDF 作为会话附件发送;浏览项目不会自动上传。已确认的回复可导出为 Markdown 或纯文本;桌面交付卡复用于 Web,支持按授权项目下载文件和定位。还可配置[独立人工浏览器面板](apps/browser-worker/README.md),由当前登录者接管已登记站点;实际工作器须通过 Chromium 沙箱就绪检查。它和手机版中转是两个不同部署目标;完整业务进度见[对等清单](docs/development/web-workbench/README.md)。 +[amd64 Docker Compose 与 Web 工作台说明](apps/headless/README.md):当前可在浏览器认领服务器、配置模型,并使用桌面同源的会话列表、编辑器及消息区进行通用文本对话;支持停止与刷新续接。网页还可以编辑个人资料、普通角色及其头像,并分别管理全局、角色和已授权项目的记忆。可手动浏览获准项目的文件,也可显式把所选文本、静态图片或兼容协议的 PDF 作为会话附件发送;浏览项目不会自动上传。管理员另外批准的仓库可手动查看已跟踪文件的改动、分支、首父提交历史,以及暂存和工作树的差异。已确认的回复可导出为 Markdown 或纯文本;桌面交付卡复用于 Web,支持按授权项目下载文件和定位。还可配置[独立人工浏览器面板](apps/browser-worker/README.md),由当前登录者接管已登记站点;实际工作器须通过 Chromium 沙箱就绪检查。它和手机版中转是两个不同部署目标;完整业务进度见[对等清单](docs/development/web-workbench/README.md)。 ## 从源码构建 diff --git a/apps/desktop/src/renderer/src/redesign/GitBranchPill.tsx b/apps/desktop/src/renderer/src/redesign/GitBranchPill.tsx new file mode 100644 index 00000000..0054c4c5 --- /dev/null +++ b/apps/desktop/src/renderer/src/redesign/GitBranchPill.tsx @@ -0,0 +1,18 @@ +import { forwardRef, type ComponentPropsWithoutRef, type ReactNode } from 'react' +import { GitBranch } from 'lucide-react' + +type GitBranchPillProps = ComponentPropsWithoutRef<'button'> & { + label: string; mergeLabel?: string; busy?: boolean; children?: ReactNode +} + +/** The desktop branch chip, without workspace access or Git behavior. */ +export const GitBranchPill = forwardRef(function GitBranchPill( + { label, mergeLabel, busy, className, children, ...button }, ref +) { + return +}) diff --git a/apps/desktop/src/renderer/src/redesign/GitWidget.tsx b/apps/desktop/src/renderer/src/redesign/GitWidget.tsx index 33fc9dc5..1f909bb9 100644 --- a/apps/desktop/src/renderer/src/redesign/GitWidget.tsx +++ b/apps/desktop/src/renderer/src/redesign/GitWidget.tsx @@ -38,6 +38,7 @@ import { useToast, type ToastOptions } from '../components/ToastProvider' import { Modal } from '../components/Modal' import { basename } from './shell-common' import { type CtxEntry, ContextMenu } from './ContextMenu' +import { GitBranchPill } from './GitBranchPill' /* ─────────────────────────── Git 快捷面板(IDEA 式点击浮出) ─────────────────────────── * 挂载工作区若是 git 仓库,则在挂载 chip 里跟一枚分支 pill,点击浮出常用操作。 @@ -455,20 +456,16 @@ export function GitWidget({ root, streaming }: { root: string; streaming: boolea return ( <> - + {menu && ( void) { + let view = baseline() + let active: AbortController | undefined + let block: Block | undefined + const listeners = new Set<() => void>() + function publish(next: GitViewState): void { + view = next + listeners.forEach((listener) => listener()) + } + function cancel(): void { + const previous = active + active = undefined + previous?.abort() + } + function selectWorkspace(workspaceId?: string): void { + if (workspaceId === view.workspaceId) return + cancel() + block = undefined + publish(baseline(workspaceId)) + } + function dismiss(): void { + cancel() + publish(baseline(view.workspaceId)) + } + async function run(action: Action, next: GitViewState, + request: (id: string, signal: AbortSignal) => Promise, complete: (data: T) => Partial): Promise { + const id = view.workspaceId + if (!id || block) return + cancel() + const ticket = new AbortController() + active = ticket + publish({ ...next, pending: action, issue: undefined }) + if (active !== ticket) return + try { + const data = await request(id, ticket.signal) + if (active !== ticket) return + const patch = complete(data) + active = undefined + publish({ ...view, ...patch, pending: undefined }) + } catch (error) { + if (active !== ticket) return + active = undefined + const issue = classify(error, action) + if (blocked(issue)) { + block = issue + publish({ ...baseline(id, true), issue }) + if (issue === 'auth') onExpired() + } else if (issue === 'stale') { + publish({ ...view, status: view.status && { ...view.status, viewId: null }, pending: undefined, issue, stale: true }) + } else { + publish({ ...view, pending: undefined, issue }) + } + } + } + function refresh(): Promise | undefined { + if (!view.open || view.pending === 'status') return + return run('status', baseline(view.workspaceId, true), api.status, (status) => ({ status })) + } + function open(): Promise | undefined { + if (!view.workspaceId || view.open) return + if (block) { publish({ ...baseline(view.workspaceId, true), issue: block }); return } + return run('status', baseline(view.workspaceId, true), api.status, (status) => ({ status })) + } + function canInspect(): boolean { return view.open && hasGitData(view.status?.state) && !view.stale && !block } + function changes(): void { + if (!canInspect() || view.tab === 'changes') return + cancel() + publish({ ...view, tab: 'changes', branches: undefined, log: undefined, pending: undefined, issue: undefined }) + } + function branches(): Promise | undefined { + if (!canInspect() || view.pending === 'branches') return + return run('branches', { ...view, tab: 'branches', branches: undefined, log: undefined, selection: undefined, diff: undefined }, + api.branches, (branches) => ({ branches })) + } + function history(more = false): Promise | undefined { + if (!canInspect() || view.pending === 'log' || (more && (view.tab !== 'history' || !view.log?.more || view.limit >= GIT_LOG_MAX))) return + const limit = more ? Math.min(view.limit + GIT_LOG_STEP, GIT_LOG_MAX) : GIT_LOG_STEP + return run('log', { ...view, tab: 'history', branches: undefined, log: more ? view.log : undefined, limit: more ? view.limit : limit, + selection: undefined, diff: undefined }, (id, signal) => api.log(id, limit, signal), (log) => ({ log, limit })) + } + function diff(entryId: string, side: GitSide): Promise | undefined { + const viewId = view.status?.viewId + const entry = view.status?.entries.find((item) => item.entryId === entryId) + if (!canInspect() || view.tab !== 'changes' || !viewId || !entry?.diffSides.includes(side) || + (view.pending === 'diff' && view.selection?.entryId === entryId && view.selection.side === side)) return + const selection = { viewId, entryId, side } + return run('diff', { ...view, selection, diff: undefined }, (id, signal) => api.diff(id, selection, signal), (diff) => { + if (diff.rel !== entry.rel || diff.side !== side) throw new Error('Unexpected Git diff projection') + return { diff } + }) + } + return { + snapshot: () => view, + subscribe(notify: () => void): () => void { listeners.add(notify); return () => { listeners.delete(notify) } }, + selectWorkspace, open, dismiss, refresh, changes, branches, history, diff + } +} +export type WorkspaceGitView = ReturnType + +export function authorizedWorkspaceId(view: WorkspaceFilesView): string | undefined { + return !view.issue && view.projects.data?.some((project) => project.id === view.projectId) ? view.projectId : undefined +} + +/** Subscribe to the selector itself so a change (including delivery reveal) aborts immediately. */ +export function bindWorkspaceGitView(git: WorkspaceGitView, files: WorkspaceFiles): () => void { + const sync = (): void => git.selectWorkspace(authorizedWorkspaceId(files.snapshot())) + const unsubscribe = files.subscribe(sync) + sync() + return () => { unsubscribe(); git.selectWorkspace(undefined) } +} diff --git a/apps/desktop/src/workbench/git-view-copy.ts b/apps/desktop/src/workbench/git-view-copy.ts new file mode 100644 index 00000000..558a9151 --- /dev/null +++ b/apps/desktop/src/workbench/git-view-copy.ts @@ -0,0 +1,73 @@ +import type { GitIssue } from './git-view-controller' + +const en = { + inspect: 'Git View', readOnly: 'Git · Read-only', unborn: 'No initial commit yet', unknownBranch: 'Branch unknown', worktree: 'Working tree', conflict: 'Conflict', + scope: 'Ordinary SHA-1 repositories; tracked changes only. History follows first parents. Remote branches come from the local cache; upstream, ahead/behind and live remote state are unknown.', + not_repo: 'The selected workspace is not a Git repository.', unsupported_layout: 'This repository layout is outside the supported scope.', + partial: 'Git information is incomplete. Only the available results are shown.', unavailable: 'Git information is unavailable for this workspace.', + clean: 'No tracked changes.', partialEmpty: 'No tracked changes were available in this incomplete view.', noDiff: 'A text diff is unavailable for this entry.', + noLines: 'No text lines in this diff.', truncated: 'The diff was truncated.', noBranches: 'No branches to show.', + cachedRemotes: 'Cached locally', noCommits: 'No commits to show.', older: 'Show more commits', historyLimit: 'More commits exist beyond the display limit.', + loading: 'Reading Git…', limited: 'Some Git information is outside this view’s scope.', + limitations: { + shallow: 'Shallow history ends at the local shallow boundary.', excluded_paths: 'Some paths were excluded from inspection.', + non_regular_entries: 'Some entries are not regular files.', git_limit: 'Part of the result exceeded an inspection limit.', + git_object_unavailable: 'Some Git objects are unavailable locally.', unsupported_git_layout: 'Some data uses an unsupported repository layout.', + excluded_refs: 'Some references were excluded from inspection.', unsafe_worktree: 'Some working tree entries were skipped.' + }, + issues: { + auth: 'Your owner session or request verification expired. Sign in again.', origin: 'Open the workbench at its configured address to view Git.', + csrf: 'Request verification failed. Reload the workbench before trying again.', not_granted: 'Git access is not granted for this workspace.', + workspace_unavailable: 'The selected workspace is unavailable or no longer authorized.', unsafe: 'This repository or entry is outside the safe read scope.', + stale: 'This Git view expired or changed. Refresh Git, then select the change again.', busy: 'Git inspection is busy. Try again manually.', + budget: 'Git inspection reached a resource limit; the requested result is incomplete.', unsupported_layout: 'This repository layout is outside the supported scope.', + incomplete: 'Git data is incomplete or unreadable. The requested result is unavailable.', unavailable: 'Git inspection is temporarily unavailable.', + failure: 'Git inspection failed. Try again manually.' + } satisfies Record +} +const zh: typeof en = { + inspect: 'Git 查看', readOnly: 'Git · 只读', unborn: '尚无初始提交', unknownBranch: '分支未知', worktree: '工作树', conflict: '冲突', + scope: '仅查看普通 SHA-1 仓库中已跟踪的更改。提交历史只沿首父遍历。远程分支来自本地缓存;上游、领先/落后和远端实时状态未知。', + not_repo: '所选工作区并非 Git 仓库。', unsupported_layout: '此仓库布局超出支持范围。', + partial: 'Git 信息不完整,仅展示已读取的结果。', unavailable: '此工作区的 Git 信息暂不可用。', + clean: '没有已跟踪的更改。', partialEmpty: '本次读取不完整,未获得已跟踪的更改。', noDiff: '此项没有可显示的文本差异。', + noLines: '此差异没有文本行。', truncated: '差异已截断。', noBranches: '没有可显示的分支。', + cachedRemotes: '本地缓存', noCommits: '没有可显示的提交。', older: '显示更多提交', historyLimit: '还有更多提交,已达到显示上限。', + loading: '正在读取 Git…', limited: '部分 Git 信息超出此视图的范围。', + limitations: { + shallow: '浅克隆历史止于本地浅克隆边界。', excluded_paths: '部分路径已排除。', non_regular_entries: '部分条目并非普通文件。', + git_limit: '部分结果超出读取上限。', git_object_unavailable: '本地缺少部分 Git 对象。', unsupported_git_layout: '部分数据使用超出支持范围的仓库布局。', + excluded_refs: '部分引用已排除。', unsafe_worktree: '已跳过部分工作树条目。' + }, + issues: { + auth: '所有者会话或请求验证已过期,请重新登录。', origin: '请从工作台的已配置地址打开 Git。', + csrf: '请求验证失败,请重新载入工作台后再试。', not_granted: '此工作区未获 Git 查看授权。', + workspace_unavailable: '所选工作区已失效或授权已撤销。', unsafe: '此仓库或条目超出安全读取范围。', + stale: 'Git 视图已过期或发生变化。请刷新 Git,再选择变更。', busy: 'Git 查看正忙,请手动重试。', + budget: 'Git 查看已达到资源上限,本次结果不完整。', unsupported_layout: '此仓库布局超出支持范围。', + incomplete: 'Git 数据不完整或读取失败,本次结果暂不可用。', unavailable: 'Git 查看暂不可用。', + failure: 'Git 读取失败,请手动重试。' + } +} +export type GitViewCopy = typeof en +export const gitViewCopy = (locale: string): GitViewCopy => locale === 'zh-CN' ? zh : en + +const describedInScope = new Set(['tracked_only', 'upstream_unknown', 'first_parent']) +const metadataOnly = new Set(['shallow', 'excluded_refs']) +const explainedByState = new Set(['not_repo', 'unsupported_layout', 'unavailable', 'binary_content', 'no_text_change']) +const budgetCodes = new Set(['status_entry_limit', 'worktree_file_limit', 'worktree_budget', 'branch_limit', + 'diff_byte_limit', 'diff_line_limit', 'diff_computation_limit', 'diff_output_limit']) + +/** Omissions of unknown effect must not be presented as a clean tracked view. */ +export function hasStatusOmissions(limitations: string[]): boolean { + return limitations.some((code) => !describedInScope.has(code) && !metadataOnly.has(code)) +} +export function gitLimitationLabels(c: GitViewCopy, limitations: string[]): string[] { + const labels = new Set() + for (const code of limitations) { + if (describedInScope.has(code) || explainedByState.has(code)) continue + const key = budgetCodes.has(code) ? 'git_limit' : code + labels.add(Object.prototype.hasOwnProperty.call(c.limitations, key) ? c.limitations[key as keyof typeof c.limitations] : c.limited) + } + return [...labels] +} diff --git a/apps/desktop/src/workbench/git-view-panel.tsx b/apps/desktop/src/workbench/git-view-panel.tsx new file mode 100644 index 00000000..eab93ac1 --- /dev/null +++ b/apps/desktop/src/workbench/git-view-panel.tsx @@ -0,0 +1,147 @@ +import { useId, useSyncExternalStore } from 'react' +import { Check, FileDiff, GitBranch, GitCommitHorizontal, RefreshCw } from 'lucide-react' +import { useI18n } from '../renderer/src/i18n/i18n' +import { GitBranchPill } from '../renderer/src/redesign/GitBranchPill' +import { gitLimitationLabels, gitViewCopy, hasStatusOmissions } from './git-view-copy' +import { hasGitData, type WorkspaceGitView } from './git-view-controller' +import { GIT_LOG_MAX, type GitBranches, type GitDiff, type GitEntry, type GitLog, type GitSide } from './git-view-transport' +import './git-view.css' + +export function WorkspaceGitPanel({ workspaceId, controller: api }: { workspaceId: string; controller: WorkspaceGitView }): React.JSX.Element | null { + const view = useSyncExternalStore(api.subscribe, api.snapshot, api.snapshot) + const { t, locale } = useI18n() + const c = gitViewCopy(locale) + const id = useId() + if (view.workspaceId !== workspaceId) return null + const status = view.status + const repo = hasGitData(status?.state) + const canInspect = repo && !view.stale + const blocked = view.issue === 'auth' || view.issue === 'origin' || view.issue === 'csrf' || view.issue === 'not_granted' || + view.issue === 'workspace_unavailable' || view.issue === 'unsafe' + const branch = repo && status ? status.detached ? t('cf.git.detached') : status.branch ?? c.unknownBranch : c.inspect + const changes = view.tab === 'changes' + const projection = changes ? status : view.tab === 'branches' ? view.branches : view.log + const state = changes && projection?.state === 'ready' && hasStatusOmissions(projection.limitations) ? 'partial' : projection?.state + const limitations = gitLimitationLabels(c, [...(projection?.limitations ?? []), ...(changes ? view.diff?.limitations ?? [] : [])]) + const message = view.issue ? c.issues[view.issue] : view.pending ? c.loading : state && state !== 'ready' ? c[state] : undefined + const sideLabel = (side: GitSide): string => side === 'staged' ? t('git.staged') : c.worktree + return <> + { + if (event.nativeEvent.isTrusted) void (view.open ? api.dismiss() : api.open()) + }} /> + {view.open &&
+
+

{c.readOnly}

+ +
+

{c.scope}

+ {repo && status?.unborn &&

{c.unborn}

} + {repo &&
+ + + +
} +
+ {message &&

{message}

} + {changes && repo && status?.entries.length === 0 &&

{state === 'ready' ? c.clean : c.partialEmpty}

} +
+ {limitations.map((text) =>

{text}

)} + {changes && repo && status && status.entries.length > 0 &&
    + {status.entries.map((entry) => void api.diff(entry.entryId, side)} />)} +
} + {view.branches && hasGitData(view.branches.state) && } + {view.log && hasGitData(view.log.state) && void api.history(true)} />} + {view.diff && } +
} + +} + +function GitChangeRow({ entry, available, selected, sideLabel, conflict, noDiff, onDiff }: { + entry: GitEntry; available: boolean; selected?: { entryId: string; side: GitSide }; sideLabel: (side: GitSide) => string + conflict: string; noDiff: string; onDiff: (side: GitSide) => void +}): React.JSX.Element { + const primary = entry.diffSides.includes('worktree') ? 'worktree' : entry.diffSides[0] + return
  • + + {entry.conflicted && {conflict}} + {(['staged', 'worktree'] as const).map((side) => { + const code = entry[side] + if (code === null && !entry.diffSides.includes(side)) return null + const label = `${sideLabel(side)}${code ? ` · ${code}` : ''}` + return entry.diffSides.includes(side) ? + : {label} + })} +
  • +} + +function Branches({ data }: { data: GitBranches }): React.JSX.Element { + const { t, locale } = useI18n() + const c = gitViewCopy(locale) + if (!data.branches.length) return

    {c.noBranches}

    + return
    + {([false, true] as const).map((remote) => { + const group = data.branches.filter((branch) => (branch.remote !== null) === remote) + return !!group.length &&
    +

    {remote ? `${t('cf.git.remoteBranches')} · ${c.cachedRemotes}` : t('cf.git.localBranches')}

    +
      {group.map((branch, index) =>
    • + {branch.current && {branch.name} +
    • )}
    +
    + })} +
    +} + +function History({ data, limit, loading, more }: { data: GitLog; limit: number; loading: boolean; more: () => void }): React.JSX.Element { + const { locale } = useI18n() + const c = gitViewCopy(locale) + const format = new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }) + return
    + {data.commits.length > 0 ?
      {data.commits.map((commit) => { + const date = new Date(commit.timestamp * 1000) + return
    1. +
    2. + })}
    :

    {c.noCommits}

    } + {data.more && (limit < GIT_LOG_MAX ? :

    {c.historyLimit}

    )} +
    +} + +function Diff({ data, sideLabel }: { data: GitDiff; sideLabel: string }): React.JSX.Element { + const { locale, t } = useI18n() + const c = gitViewCopy(locale) + const notice = data.state === 'binary' ? t('git.binary') : data.state === 'too_large' ? t('git.tooLarge') : + data.state === 'unavailable' ? c.noDiff : !data.truncated && data.lines.length === 0 ? c.noLines : undefined + return
    +

    {t('git.diff')} · {data.rel} · {sideLabel}

    + {notice &&

    {notice}

    } + {data.truncated &&

    {c.truncated}

    } + {data.state === 'ready' && data.lines.length > 0 &&
    + {data.lines.map((line, index) =>
    + {line.oldNo}{line.newNo} + {line.type === 'add' ? '+' : line.type === 'del' ? '−' : ' '} + {line.text} +
    )} +
    } +
    +} diff --git a/apps/desktop/src/workbench/git-view-transport.ts b/apps/desktop/src/workbench/git-view-transport.ts new file mode 100644 index 00000000..64eb6e36 --- /dev/null +++ b/apps/desktop/src/workbench/git-view-transport.ts @@ -0,0 +1,121 @@ +import type { Transport } from './transport' + +export type GitSide = 'staged' | 'worktree' +export type GitRepoState = 'ready' | 'partial' | 'unavailable' | 'not_repo' | 'unsupported_layout' +export type GitEntry = { + entryId: string; rel: string; staged: string | null; worktree: string | null; conflicted: boolean; diffSides: GitSide[] +} +type GitProjection = { state: GitRepoState; branch: string | null; limitations: string[] } +type GitHead = { detached: boolean; unborn: boolean } +export type GitStatus = GitProjection & GitHead & { + workspaceId: string; mergeInProgress: boolean; viewId: string | null; entries: GitEntry[] +} +export type GitBranch = { name: string; current: boolean; remote: string | null } +export type GitBranches = GitProjection & GitHead & { branches: GitBranch[] } +export type GitCommit = { oid: string; short: string; subject: string; author?: string; timestamp: number } +export type GitLog = GitProjection & { commits: GitCommit[]; traversal: 'first-parent'; more: boolean } +export type GitDiffLine = { type: 'ctx' | 'add' | 'del' | 'hunk'; oldNo?: number; newNo?: number; text: string } +export type GitDiff = { + state: 'ready' | 'binary' | 'too_large' | 'unavailable'; rel: string; side: GitSide; lines: GitDiffLine[]; truncated: boolean; limitations: string[] +} +export type GitDiffRequest = { viewId: string; entryId: string; side: GitSide } + +export const GIT_LOG_STEP = 20 +export const GIT_LOG_MAX = 100 + +function invalid(): never { throw new Error('Invalid Git inspection request or response') } +function object(value: unknown): Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record : invalid() +} +function str(value: unknown): string { return typeof value === 'string' ? value : invalid() } +function nullable(value: unknown): string | null { return value === null ? value : str(value) } +function bool(value: unknown): boolean { return typeof value === 'boolean' ? value : invalid() } +function array(value: unknown, parse: (item: unknown) => T): T[] { return Array.isArray(value) ? value.map(parse) : invalid() } +function token(value: unknown, pattern: RegExp): string { + return typeof value === 'string' && pattern.exec(value)?.[0] === value ? value : invalid() +} +function integer(value: unknown, min: number, max: number): number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= min && value <= max ? value : invalid() +} +function literal(value: unknown, values: readonly T[]): T { + return values.find((item) => item === value) ?? invalid() +} +const viewId = /^v_[0-9a-f]{32}$/u +const entryId = /^e_[0-9a-f]{32}$/u +const diffSide = (value: unknown): GitSide => literal(value, ['staged', 'worktree']) + +function projection(row: Record): GitProjection { + return { state: literal(row.state, ['ready', 'partial', 'unavailable', 'not_repo', 'unsupported_layout']), + branch: nullable(row.branch), limitations: array(row.limitations, str) } +} +function head(row: Record): GitHead { return { detached: bool(row.detached), unborn: bool(row.unborn) } } +function status(value: unknown, workspaceId: string): GitStatus { + const row = object(value) + if (row.workspaceId !== workspaceId) return invalid() + const seen = new Set() + const entries = array(row.entries, (item): GitEntry => { + const entry = object(item) + const id = token(entry.entryId, entryId) + const sides = array(entry.diffSides, diffSide) + if (seen.has(id) || new Set(sides).size !== sides.length) return invalid() + seen.add(id) + return { entryId: id, rel: str(entry.rel), staged: nullable(entry.staged), worktree: nullable(entry.worktree), + conflicted: bool(entry.conflicted), diffSides: sides } + }) + return { ...projection(row), ...head(row), workspaceId, mergeInProgress: bool(row.mergeInProgress), + viewId: row.viewId === null ? null : token(row.viewId, viewId), entries } +} +function branches(value: unknown): GitBranches { + const row = object(value) + return { ...projection(row), ...head(row), branches: array(row.branches, (item) => { + const branch = object(item) + return { name: str(branch.name), current: bool(branch.current), remote: nullable(branch.remote) } + }) } +} +function log(value: unknown, limit: number): GitLog { + const row = object(value) + const commits = array(row.commits, (item): GitCommit => { + const commit = object(item) + const oid = token(commit.oid, /^[0-9a-f]{40}$/u) + const short = token(commit.short, /^[0-9a-f]{4,40}$/u) + if (!oid.startsWith(short)) return invalid() + return { oid, short, subject: str(commit.subject), ...(commit.author === undefined ? {} : { author: str(commit.author) }), + timestamp: integer(commit.timestamp, -8_640_000_000_000, 8_640_000_000_000) } + }) + if (commits.length > limit) return invalid() + return { ...projection(row), more: bool(row.more), traversal: literal(row.traversal, ['first-parent']), commits } +} +function diff(value: unknown, side: GitSide): GitDiff { + const row = object(value) + if (row.side !== side) return invalid() + const lines = array(row.lines, (item): GitDiffLine => { + const line = object(item) + return { type: literal(line.type, ['ctx', 'add', 'del', 'hunk']), text: str(line.text), + ...(line.oldNo === undefined ? {} : { oldNo: integer(line.oldNo, 0, Number.MAX_SAFE_INTEGER) }), + ...(line.newNo === undefined ? {} : { newNo: integer(line.newNo, 0, Number.MAX_SAFE_INTEGER) }) } + }) + return { state: literal(row.state, ['ready', 'binary', 'too_large', 'unavailable']), rel: str(row.rel), side, lines, + truncated: bool(row.truncated), limitations: array(row.limitations, str) } +} + +/** Only the four owner projections; no route/body identifiers derived from Git text. */ +export function createGitViewTransport(transport: Pick, csrf: string) { + const request = (id: string, action: 'status' | 'branches' | 'log' | 'diff', body: object, signal: AbortSignal): Promise => + transport.gitRequest(`/workspaces/${token(id, /^w_[0-9a-f]{32}$/u)}/git/${action}`, body, csrf, signal) + return { + async status(id: string, signal: AbortSignal): Promise { + return status(await request(id, 'status', {}, signal), id) + }, + async branches(id: string, signal: AbortSignal): Promise { + return branches(await request(id, 'branches', {}, signal)) + }, + async log(id: string, limit: number, signal: AbortSignal): Promise { + return log(await request(id, 'log', { limit: integer(limit, 1, GIT_LOG_MAX) }, signal), limit) + }, + async diff(id: string, selection: GitDiffRequest, signal: AbortSignal): Promise { + const side = diffSide(selection.side) + return diff(await request(id, 'diff', { viewId: token(selection.viewId, viewId), entryId: token(selection.entryId, entryId), side }, signal), side) + } + } +} +export type GitViewTransport = ReturnType diff --git a/apps/desktop/src/workbench/git-view.css b/apps/desktop/src/workbench/git-view.css new file mode 100644 index 00000000..6b810be5 --- /dev/null +++ b/apps/desktop/src/workbench/git-view.css @@ -0,0 +1,62 @@ +.wb-workspace__project-picker { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: var(--space-2); + align-items: end; +} +.wb-workspace__project-picker > label { grid-column: 1 / -1; } +.wb-workspace__project-picker:has(> .wb-git__toggle) > label { grid-column: 1; } +.wb-git__toggle.cf-gitchip { + height: 34px; + border: 1px solid var(--border); + border-radius: var(--radius); +} +.wb-git__toggle[aria-expanded='true'] { background: var(--bg-active); color: var(--fg); } +.wb-git.cf-ctx { + grid-column: 1 / -1; + min-width: 0; + position: static; + max-height: min(50dvh, 440px); + padding: var(--space-2); + display: grid; + gap: var(--space-2); + overflow: auto; +} +.wb-git :is(p, h3, h4, ul, ol) { margin: 0; } +.wb-git :is(h3, .wb-git__diff h4) { font-size: 13px; } +.wb-git .cf-ctx__item { width: auto; } +.wb-git .cf-ctx__item[aria-pressed='true'], .wb-git .cf-ctx__item[aria-current='true'] { + background: var(--bg-active); + color: var(--accent); +} +.wb-git__bar, .wb-git__row, .wb-git__result { + display: flex; + align-items: center; + gap: var(--space-1); + flex-wrap: wrap; + min-width: 0; +} +.wb-git__bar h3 { flex: 1; } +.wb-git__tabs, .wb-git__diff { border-top: 1px solid var(--border); padding-top: var(--space-1); } +.wb-git__muted, .wb-git__alert, .wb-git__flag { font-size: 12px; } +.wb-git__muted { color: var(--fg-muted); } +.wb-git__alert { color: var(--warning); } +.wb-git__flag { + padding: 1px 6px; + border-radius: var(--radius-sm); + color: var(--warning); + background: color-mix(in srgb, var(--warning) 18%, transparent); +} +.wb-git__rows { list-style: none; padding: 0; } +.wb-git__row, .wb-git__result { padding: 3px 0; border-bottom: 1px solid var(--border); } +.wb-git__result { padding-inline: 9px; } +.wb-git__result bdi, .wb-git__diff h4 { overflow-wrap: anywhere; } +.wb-git .wb-git__path { flex: 1; min-width: min(200px, 100%); } +.wb-git .wb-git__path bdi { min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.wb-git .wb-git__side { font-size: 12px; } +.wb-git__branch-check { display: inline-flex; width: 14px; flex: none; color: var(--accent); } +.wb-git__commit code { color: var(--fg-muted); } +.wb-git__subject { flex: 1; min-width: min(150px, 100%); } +.wb-git .diffview { overflow: auto; max-height: 25dvh; } +.wb-git .diffview__line { min-width: max-content; } +.wb-git .diffview__no { width: 38px; } diff --git a/apps/desktop/src/workbench/text-workbench.tsx b/apps/desktop/src/workbench/text-workbench.tsx index cab0e9b0..7254e58a 100644 --- a/apps/desktop/src/workbench/text-workbench.tsx +++ b/apps/desktop/src/workbench/text-workbench.tsx @@ -20,6 +20,8 @@ import { createChatTransport, inputBytes, MAX_TEXT_INPUT, type ChatState } from import { eligibleDeliveryReplies } from './deliveries-controller' import { createDeliveriesTransport, type DeliveriesTransport, type DeliveryGroup, type DeliveryLocation } from './deliveries-transport' import { BrowserDeliveryCard, DeliveryFeedback, DeliveryHistory, ReplyDeliveryActions, useDeliveries } from './deliveries-ui' +import { createWorkspaceGitView } from './git-view-controller' +import { createGitViewTransport } from './git-view-transport' import { createLibrary, type Roster } from './library-transport' import { LibraryWorkspace, type LibraryPanel } from './library-workspace' import { createPreferenceTransport, matchesPreferences, projectSession } from './session-preferences' @@ -76,6 +78,9 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp const filesEnabled = bootstrap.capabilities?.workspaceFiles === true const files = useMemo(() => filesEnabled ? createWorkspaceFiles(createWorkspaceTransport(transport, bootstrap.csrf)) : undefined, [filesEnabled, transport, bootstrap.csrf]) + const gitEnabled = filesEnabled && bootstrap.capabilities?.gitInspect === true + const git = useMemo(() => gitEnabled ? createWorkspaceGitView(createGitViewTransport(transport, bootstrap.csrf), onExpired) : undefined, + [gitEnabled, transport, bootstrap.csrf, onExpired]) const [filesOpen, setFilesOpen] = useState(false) const workspaceLabel = locale === 'zh-CN' ? '工作区文件' : 'Workspace files' const openFiles = files ? () => { setFilesOpen(true); void files.loadProjects() } : undefined @@ -246,7 +251,7 @@ export default function TextWorkbench({ transport, bootstrap, beforeWrite, onExp {settingsOpen && renderSettings(() => setSettingsOpen(false))} {browserOpen && browserVisible && setBrowserOpen(undefined)} />} {files && { setFilesOpen(false); setLocatedFilesSid(undefined) }} controller={files} />} + close={() => { setFilesOpen(false); setLocatedFilesSid(undefined) }} controller={files} git={locked ? undefined : git} />} {renameSid && renameSid === sid && preferences && preferenceEntry && setRenameSid(undefined)} reload={reloadPreferences} />} diff --git a/apps/desktop/src/workbench/transport.ts b/apps/desktop/src/workbench/transport.ts index bc81af97..cb0fba17 100644 --- a/apps/desktop/src/workbench/transport.ts +++ b/apps/desktop/src/workbench/transport.ts @@ -14,7 +14,7 @@ export interface Bootstrap { config: RecordValue csrf: string expiresAt: number - capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true; deliveries?: true } + capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true; deliveries?: true; gitInspect?: true } } export type SessionScreen = { mode: 'authenticated'; bootstrap: Bootstrap } | { mode: 'claim' | 'login' } @@ -62,10 +62,10 @@ export function captureClaim(location: Pick { + async function fetchJson(path: string, init: RequestInit, referrerPolicy: ReferrerPolicy = 'no-referrer'): Promise { const response = await send(prefix + path, { ...init, credentials: 'same-origin', mode: 'same-origin', redirect: 'error', - cache: 'no-store', referrerPolicy: 'no-referrer' + cache: 'no-store', referrerPolicy }) if (!response.ok) { const failure: unknown = await response.json().catch(() => undefined) @@ -82,6 +82,16 @@ export function createTransport(send: Fetch = fetch) { return fetchJson(path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) }) } + function gitRequest(path: string, body: object, csrf: string, signal: AbortSignal): Promise { + if (!csrf || /^\/workspaces\/w_[a-f0-9]{32}\/git\/(status|branches|log|diff)$/u.exec(path)?.[0] !== path) + throw new Error('Invalid workspace Git request') + // The browser supplies Origin for same-origin POSTs. A no-referrer request can serialize + // Origin as null; use the same-origin policy already used by other owner-only panels. + return fetchJson(path, { method: 'POST', body: JSON.stringify(body), signal, + headers: { accept: 'application/json', 'content-type': 'application/json', [csrfHeader]: csrf } + }, 'same-origin') + } + async function uploadAttachment(sid: string, body: Blob, encodedName: string, mime: string, csrf: string): Promise { if (typeof sid !== 'string' || /^[A-Za-z0-9_-]{1,128}$/u.exec(sid)?.[0] !== sid || !(body instanceof Blob) || !csrf || /^[A-Za-z0-9_-]{1,340}$/u.exec(encodedName)?.[0] !== encodedName || /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/u.exec(mime)?.[0] !== mime) @@ -108,6 +118,7 @@ export function createTransport(send: Fetch = fetch) { if (result.capabilities.browserPanel === true) capabilities.browserPanel = true if (result.capabilities.sessionPreferences === true) capabilities.sessionPreferences = true if (result.capabilities.deliveries === true) capabilities.deliveries = true + if (result.capabilities.gitInspect === true) capabilities.gitInspect = true } return { protocol, version, platform, config, csrf, expiresAt, ...(Object.keys(capabilities).length ? { capabilities } : {}) } } @@ -156,7 +167,7 @@ export function createTransport(send: Fetch = fetch) { } return { - request, uploadAttachment, browserRequest, deliveryRequest, + request, uploadAttachment, browserRequest, deliveryRequest, gitRequest, async inspect(): Promise { try { return { mode: 'authenticated', bootstrap: await bootstrap() } diff --git a/apps/desktop/src/workbench/workspace-dialog.tsx b/apps/desktop/src/workbench/workspace-dialog.tsx index 675f972f..66ce7bbf 100644 --- a/apps/desktop/src/workbench/workspace-dialog.tsx +++ b/apps/desktop/src/workbench/workspace-dialog.tsx @@ -1,6 +1,8 @@ import { useEffect, useId, useLayoutEffect, useRef, useSyncExternalStore } from 'react' import { ChevronDown, ChevronRight, FileText, Folder, FolderOpen, X } from 'lucide-react' import { useI18n } from '../renderer/src/i18n/i18n' +import { authorizedWorkspaceId, bindWorkspaceGitView, type WorkspaceGitView } from './git-view-controller' +import { WorkspaceGitPanel } from './git-view-panel' import { type FileDraft, type WorkspaceFiles, type WorkspaceFilesView } from './workspace-files' import { workspaceEditorText } from './workspace-line-endings' import './workspace-dialog.css' @@ -37,21 +39,22 @@ const copy = { } type Copy = (typeof copy)['en'] -export function WorkspaceFilesPanel({ open, close, controller }: { - open: boolean; close: () => void; controller: WorkspaceFiles +export function WorkspaceFilesPanel({ open, close, controller, git }: { + open: boolean; close: () => void; controller: WorkspaceFiles; git?: WorkspaceGitView }): React.JSX.Element | null { const view = useSyncExternalStore(controller.subscribe, controller.snapshot) + useLayoutEffect(() => open && git ? bindWorkspaceGitView(git, controller) : undefined, [open, git, controller]) useEffect(() => { if (!view.anyDirty) return const warn = (event: BeforeUnloadEvent): void => { event.preventDefault(); event.returnValue = true } window.addEventListener('beforeunload', warn) return () => window.removeEventListener('beforeunload', warn) }, [view.anyDirty]) - return open ? : null + return open ? : null } -function WorkspaceFilesDialog({ view, api, close }: { - view: WorkspaceFilesView; api: WorkspaceFiles; close: () => void +function WorkspaceFilesDialog({ view, api, close, git }: { + view: WorkspaceFilesView; api: WorkspaceFiles; close: () => void; git?: WorkspaceGitView }): React.JSX.Element { const labels = copy[useI18n().locale === 'zh-CN' ? 'zh-CN' : 'en'] const title = useId() @@ -62,12 +65,13 @@ function WorkspaceFilesDialog({ view, api, close }: { return () => { if (element.open) element.close() } }, []) const projectList = view.projects.data ?? [] + const gitWorkspaceId = git ? authorizedWorkspaceId(view) : undefined return { event.preventDefault(); close() }} onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { event.preventDefault() event.stopPropagation() - void api.save() + if (!(event.target instanceof Element) || !event.target.closest('[data-workspace-git]')) void api.save() } }}>
    @@ -75,14 +79,17 @@ function WorkspaceFilesDialog({ view, api, close }: {

    {labels.manual}

    - +
    + + {git && gitWorkspaceId && } +
    {view.issue &&

    {labels[view.issue]}

    } {!view.issue && view.projects.pending &&

    {labels.loading}

    } {!view.issue && view.projects.issue &&

    {labels[view.projects.issue]}{' '} diff --git a/apps/headless/README.md b/apps/headless/README.md index e9881ee8..84167521 100644 --- a/apps/headless/README.md +++ b/apps/headless/README.md @@ -43,6 +43,22 @@ 保存使用服务器读回的版本。另一个标签页或宿主上的编辑改了文件,会收到冲突;网页保留草稿,显式重新读取后对照磁盘版本,再由用户决定是否保存。不会自动重放陈旧内容。此机制保证本服务处理的同版本竞争只会有一个成功;它不是针对其他未协作文件写入者的操作系统级写锁。此阶段的冲突预览也不等于 Agent 检查点/历史回退。 +## 手动查看项目的 Git 资料(只读) + +浏览文件与授权 Git 历史是两份不同的许可。先准备只读项目父目录,再用 `DEVA_GIT_PROJECTS` 指定允许查看 Git 的**直接子目录名**;项目中可能有历史版本的源代码,须按实际希望公开给当前所有者的范围选择。没有配置时,网页维持原工作区界面。 + +```sh +export DEVA_WORKSPACE_PARENT=/absolute/path/to/approved-projects +export DEVA_GIT_PROJECTS='["Documentation"]' +docker compose -f compose.yaml -f compose.workspaces.yaml -f compose.git-inspect.yaml up -d --build +``` + +打开工作区并选中该项目,然后点击 **Git 查看**。只读面板与桌面复用分支按钮;只有明确点击才读取状态、分支、历史或文件差异。存盘为普通 SHA‑1 loose objects 或常见 pack/idx v2 的仓库均可查看,无需在产品容器安装系统 Git。Git 元数据和 diff 不发给模型;没有后台 Git 轮询,不执行仓库配置、钩子或文本转换器。 + +- **变更**比较可见的已跟踪普通文件。暂存视图比较 HEAD 与索引,工作树视图比较索引与磁盘。文件被更改、视图过期或其他登录重用引用时,需要重新选择;切项目后不继续显示原项目的数据。 +- **历史**最多看 100 个首父提交;远程跟踪分支仅反映本地缓存。没有读取或连接远程,上游关系及领先/落后数量未知。未跟踪文件、重命名推断、`.gitattributes` 转换和子模块内部状态不在本视图内。 +- **范围**限制为普通仓库根下的真实 `.git` 目录,已登记项目被替换后需要重新检查部署授权。外置 gitdir、linked worktree、alternate 对象库、SHA‑256、部分或超限仓库会给出相应状态。每次读取受时间和字节上限约束;缺对象或预算耗尽不等于仓库干净。此面板不提供暂存、丢弃、提交、切分支、fetch/pull/push 或凭据设置。 + ## Docker Compose(linux/amd64) 在本分支的仓库根目录执行: diff --git a/apps/headless/src/business/handlers.mjs b/apps/headless/src/business/handlers.mjs index 6a5be22c..f9360121 100644 --- a/apps/headless/src/business/handlers.mjs +++ b/apps/headless/src/business/handlers.mjs @@ -7,6 +7,8 @@ import { createChatWebSocket } from '../events/websocket.mjs' import { createTextTurns } from '../chat/text-turns.mjs' import { chatRoutes } from '../chat/routes.mjs' import { browserRoutes } from '../browser/routes.mjs' +import { gitViewRoutes } from '../git/routes.mjs' +import { openGitService } from '../git/service.mjs' import { HttpError, json, readJson } from '../http/policy.mjs' import { openSettings } from './settings.mjs' import { allowedModelOrigins } from './provider-fetch.mjs' @@ -43,14 +45,15 @@ async function probe(settings, supplied, opts, signal) { return connection.listModels() } -export async function openBusiness({ dataDir, vault, auth, version, allowedOrigins = [], workspaceRoot, workspaceWritable = false, privateRoots, browserRunDir }) { +export async function openBusiness({ dataDir, vault, auth, version, allowedOrigins = [], workspaceRoot, workspaceWritable = false, privateRoots, browserRunDir, gitProjects }) { const opts = { version, allowedOrigins: [...allowedModelOrigins(allowedOrigins)] } const settings = await openSettings({ dataDir, vault }) const lifetime = new AbortController() const journal = createEventJournal() - let library, turns, uploads, browser, closingBrowser + let library, turns, uploads, browser, closingBrowser, git, closingGit try { - library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, privateRoots }) + library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, privateRoots, gitProjects }) + if (library.gitGrants.enabled) git = openGitService({ grants: library.gitGrants, auth }) uploads = await openUploadStore({ dataDir }) turns = createTextTurns({ dataDir, settings, journal, ...opts, resolveRole: library.resolveRole, uploads, deliveries: true }) // The Unix client is loaded only when the operator mounted a private worker socket. @@ -58,24 +61,27 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi const { createManualBrowser } = await import('../browser/manual-browser.mjs') browser = createManualBrowser({ runDir: browserRunDir, auth, sessionExists: turns.hasBrowserSession }) } - } catch (err) { journal.close(); await Promise.allSettled([turns?.close(), uploads?.close(), library?.close()]); throw err } + } catch (err) { journal.close(); await git?.close(); await Promise.allSettled([turns?.close(), uploads?.close(), library?.close()]); throw err } + const handleGit = gitViewRoutes(git) const handleBrowser = browserRoutes(browser) const chats = chatRoutes(turns, { withRoleForChat: library.withRoleForChat }) const attachments = attachmentRoutes({ uploads, turns }) const deliveries = deliveryRoutes({ turns, files: library.deliveryFiles }) function beginShutdown() { lifetime.abort(); attachments.close() + if (git && !closingGit) { closingGit = git.close(); void closingGit.catch(() => {}) } if (browser && !closingBrowser) { closingBrowser = Promise.resolve(browser.close()); void closingBrowser.catch(() => {}) } } return { beginShutdown, capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true, - browserPanel: !!browser, deliveries: typeof turns.deliverySnapshot === 'function', + browserPanel: !!browser, gitInspect: !!git, deliveries: typeof turns.deliverySnapshot === 'function', sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }), createRealtime: ({ auth, policy }) => createChatWebSocket({ turns, journal, auth, policy }), getConfig: () => settings.getPublicConfig(), async handle(req, res, { auth, policy }) { const path = (req.url ?? '').split('?', 1)[0] + if (path.startsWith('/api/v1/workspaces/') && path.includes('/git/') && await handleGit(req, res, { auth, policy })) return true if (path.includes('/browser') && await handleBrowser(req, res, { auth, policy })) return true if (path === '/api/v1/chats' || path.startsWith('/api/v1/chats/')) { if (path.includes('/deliveries') && await deliveries(req, res, { auth, policy })) return true @@ -126,7 +132,10 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi beginShutdown() try { await turns.close() } finally { journal.close() - try { await closingBrowser } finally { try { await uploads.close() } finally { await library.close() } } + try { + const results = await Promise.allSettled([closingBrowser, closingGit]) + if (results.some(row => row.status === 'rejected')) throw Error('Optional service shutdown unconfirmed') + } finally { try { await uploads.close() } finally { await library.close() } } } } } diff --git a/apps/headless/src/business/library-routes.mjs b/apps/headless/src/business/library-routes.mjs index 91c36c10..f305c43c 100644 --- a/apps/headless/src/business/library-routes.mjs +++ b/apps/headless/src/business/library-routes.mjs @@ -5,6 +5,7 @@ import { openProfile } from './profile.mjs' import { openPersonas } from './personas.mjs' import { checkRoleBindings } from './role-bindings.mjs' import { openWorkspaceCatalog } from './workspace-catalog.mjs' +import { gitGrants, gitProjectNames } from '../git/access.mjs' import { openWorkspaceFiles } from '../files/workspace-files.mjs' import { workspaceFileRoutes } from '../files/workspace-routes.mjs' import { openDeliveryFiles } from '../files/delivery-files.mjs' @@ -46,11 +47,14 @@ function snapshotOf(memory, scope) { return { snapshot, revision } } -export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable = false, privateRoots = [] }) { +export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable = false, privateRoots = [], gitProjects }) { if (typeof workspaceWritable !== 'boolean' || (workspaceWritable && !workspaceRoot)) throw new TypeError('Workspace writes require an explicit project root') + const gitNames = gitProjectNames(gitProjects) + if (gitNames.length && !workspaceRoot) throw new TypeError('Git inspection requires an explicit workspace root') const catalog = openWorkspaceCatalog({ root: workspaceRoot, privateRoots: [dataDir, ...privateRoots] }) - let profile, personas, memory, fileCommands + let profile, personas, memory, fileCommands, approvedGit try { + approvedGit = gitGrants(catalog, gitNames) if (workspaceRoot) fileCommands = workspaceFileRoutes(openWorkspaceFiles({ catalog, writable: workspaceWritable })) profile = await openProfile({ dataDir }) personas = await openPersonas({ dataDir, workspaceCatalog: catalog, checkReferences: checkRoleBindings(dataDir) }) @@ -95,6 +99,7 @@ export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable = } return { workspaceFilesEnabled: Boolean(fileCommands), + gitGrants: approvedGit, deliveryFiles: workspaceRoot ? openDeliveryFiles({ catalog }) : undefined, resolveRole: id => serial(() => enabledRole(id)), withRoleForChat: (id, action) => serial(async () => action(await enabledRole(id))), diff --git a/apps/headless/src/cli.mjs b/apps/headless/src/cli.mjs index 324f7238..d4aae538 100644 --- a/apps/headless/src/cli.mjs +++ b/apps/headless/src/cli.mjs @@ -31,6 +31,7 @@ Options override the environment: --workspace-root PATH DEVA_WORKSPACE_ROOT (optional mounted parent for registered projects; default none) --workspace-write DEVA_WORKSPACE_WRITE=1 (explicit permission to save an existing text file; default 0) --browser-control-dir PATH DEVA_BROWSER_CONTROL_DIR (optional private browser-worker socket mount) + --git-projects JSON DEVA_GIT_PROJECTS (optional array of project names approved for read-only Git history) --help Show this help. DEVA_PROVIDER_ORIGINS is an optional comma-separated list of exact private model origins for serve. @@ -42,7 +43,7 @@ const runtime = { 'run-dir': str } const origin = { host: str, port: str, 'public-url': str } const flags = Object.freeze({ 'init-key': { ...paths, ...key, 'if-missing': { type: 'boolean' } }, - serve: { ...paths, ...key, ...runtime, ...origin, 'web-dir': str, 'workspace-root': str, 'workspace-write': { type: 'boolean' }, 'browser-control-dir': str }, + serve: { ...paths, ...key, ...runtime, ...origin, 'web-dir': str, 'workspace-root': str, 'workspace-write': { type: 'boolean' }, 'browser-control-dir': str, 'git-projects': str }, claim: { ...paths, ...runtime, ...origin }, status: { ...paths, ...runtime } }) @@ -73,12 +74,14 @@ function configuration(command, values, env) { const origins = env.DEVA_PROVIDER_ORIGINS?.trim() const workspaceRoot = values['workspace-root'] ?? env.DEVA_WORKSPACE_ROOT const browserControl = values['browser-control-dir'] ?? env.DEVA_BROWSER_CONTROL_DIR + const gitProjects = values['git-projects'] ?? env.DEVA_GIT_PROJECTS const writeFlag = env.DEVA_WORKSPACE_WRITE ?? '0' if (!['0', '1'].includes(writeFlag)) throw Error('DEVA_WORKSPACE_WRITE must be 0 or 1') const workspaceWritable = values['workspace-write'] === true || writeFlag === '1' if (workspaceWritable && !workspaceRoot) throw Error('Workspace writes require an explicit workspace root') config.businessOptions = { workspaceWritable, + ...(gitProjects ? { gitProjects } : {}), ...(browserControl ? { browserRunDir: workbenchPath(browserControl, 'Browser control directory') } : {}), ...(origins ? { allowedOrigins: origins.split(',').map(origin => origin.trim()) } : {}), ...(workspaceRoot ? { workspaceRoot: workbenchPath(workspaceRoot, 'Workspace root') } : {}) diff --git a/apps/headless/src/git/access.mjs b/apps/headless/src/git/access.mjs new file mode 100644 index 00000000..f513d7a3 --- /dev/null +++ b/apps/headless/src/git/access.mjs @@ -0,0 +1,30 @@ +import { validWorkspaceName } from '../files/workspace-files-fd.mjs' +import { HttpError } from '../http/policy.mjs' + +/** Approving file browsing alone does not authorize viewing Git history. No glob or path syntax. */ +export function gitProjectNames(input) { + if (input === undefined || input === '') return [] + let names = input + if (typeof input === 'string') { + if (Buffer.byteLength(input) > 12 * 1024) throw Error('Invalid Git project allowlist') + try { names = JSON.parse(input) } catch { throw Error('Git project grants must be a JSON array of project names') } + } + if (!Array.isArray(names) || names.length > 32 || names.some(n => !validWorkspaceName(n) || n.trim() !== n || + /[?*:\[\]\p{Cf}\p{Zl}\p{Zp}]/u.test(n)) || new Set(names).size !== names.length) throw Error('Invalid Git project allowlist') + return Object.freeze([...names]) +} + +export function gitGrants(catalog, names) { + const chosen = new Set(gitProjectNames(names)) + // Pin *IDs* from the deployment's initial grant, not eternal authority over whatever may + // later replace a same-named directory. A newly created/replaced project needs a restart + // with an intentional operator grant. The bootstrap itself scans no Git metadata. + const ids = new Set(chosen.size ? catalog.list().filter(p => chosen.has(p.name)).map(p => p.id) : []) + return Object.freeze({ + enabled: chosen.size > 0, + pin(wid) { + if (!ids.has(wid)) throw new HttpError(403, 'git_not_granted') + return catalog.pinProject(wid) + } + }) +} diff --git a/apps/headless/src/git/git-errors.mjs b/apps/headless/src/git/git-errors.mjs new file mode 100644 index 00000000..0dea1545 --- /dev/null +++ b/apps/headless/src/git/git-errors.mjs @@ -0,0 +1,12 @@ +const messages = Object.freeze({ + git_stale: 'Git view changed; reload and try again', + git_limit: 'Git view exceeds its read limit', + git_corrupt: 'Git metadata or object is malformed', + git_object_unavailable: 'Git object is unavailable locally', + git_unsafe: 'Git view path is unsafe or inaccessible', + unsupported_git_layout: 'Git repository layout is unsupported', +}) + +export function gitError(code) { + return Object.assign(new Error(messages[code] ?? 'Git view failed'), { code }) +} diff --git a/apps/headless/src/git/inspect-diff.mjs b/apps/headless/src/git/inspect-diff.mjs new file mode 100644 index 00000000..dce746c7 --- /dev/null +++ b/apps/headless/src/git/inspect-diff.mjs @@ -0,0 +1,146 @@ +import { typedObject } from './inspect-history.mjs' +import { MAX_TEXT_BYTES, diffText, limitationFor } from './inspect-policy.mjs' + +const MAX_LINES = 4000 +const MAX_OUTPUT_LINES = 1000 +const MAX_COMPARISONS = 1_000_000 +const CONTEXT = 3 +const EMPTY = Buffer.alloc(0) + +export function emptyDiff(rel, side, state, limitation) { + return { state, rel, side, lines: [], truncated: false, limitations: [limitation] } +} + +function toLines(text) { + const lines = [] + for (let at = 0; at < text.length;) { + if (lines.length === MAX_LINES) return null + const next = text.indexOf('\n', at) + if (next < 0) { + lines.push({ text: text.slice(at), lf: false }) + break + } + lines.push({ text: text.slice(at, next), lf: true }) + at = next + 1 + } + return lines +} + +function sameLine(a, b) { return a.id === b.id } + +function internLines(oldLines, newLines) { + // Intern once so the LCS cap bounds comparisons even with long shared string prefixes. + const ids = [new Map(), new Map()] + let next = 0 + for (const lines of [oldLines, newLines]) { + for (const line of lines) { + const group = ids[Number(line.lf)] + if (!group.has(line.text)) group.set(line.text, ++next) + line.id = group.get(line.text) + } + } +} + +function editRows(oldLines, newLines) { + internLines(oldLines, newLines) + let prefix = 0, oldEnd = oldLines.length, newEnd = newLines.length + while (prefix < oldEnd && prefix < newEnd && sameLine(oldLines[prefix], newLines[prefix])) prefix++ + while (oldEnd > prefix && newEnd > prefix && sameLine(oldLines[oldEnd - 1], newLines[newEnd - 1])) { + oldEnd-- + newEnd-- + } + const a = oldEnd - prefix, b = newEnd - prefix, width = b + 1 + if (a * b > MAX_COMPARISONS) return null + const lcs = new Uint16Array((a + 1) * width) + for (let i = a - 1; i >= 0; i--) { + for (let j = b - 1; j >= 0; j--) { + const cell = i * width + j + lcs[cell] = sameLine(oldLines[prefix + i], newLines[prefix + j]) + ? lcs[cell + width + 1] + 1 : Math.max(lcs[cell + width], lcs[cell + 1]) + } + } + const rows = [] + let oldAt = 0, newAt = 0 + const append = type => { + const oldNo = type !== 'add' ? ++oldAt : undefined + const newNo = type !== 'del' ? ++newAt : undefined + const source = oldNo === undefined ? newLines[newNo - 1] : oldLines[oldNo - 1] + rows.push({ row: { type, ...(oldNo === undefined ? {} : { oldNo }), ...(newNo === undefined ? {} : { newNo }), + text: source.text }, lf: source.lf, oldAt, newAt }) + } + while (oldAt < prefix) append('ctx') + while (oldAt < oldEnd || newAt < newEnd) { + if (oldAt < oldEnd && newAt < newEnd && sameLine(oldLines[oldAt], newLines[newAt])) append('ctx') + else { + const cell = (oldAt - prefix) * width + newAt - prefix + if (oldAt < oldEnd && (newAt === newEnd || lcs[cell + width] >= lcs[cell + 1])) append('del') + else append('add') + } + } + while (oldAt < oldLines.length) append('ctx') + return rows +} + +function renderRows(rows, before, after) { + const lines = [], hunks = [] + let total = 0, truncated = false + const add = row => { + const cost = Buffer.byteLength(row.text) + if (lines.length >= MAX_OUTPUT_LINES || total + cost > MAX_TEXT_BYTES) { + truncated = true + return false + } + total += cost + lines.push(row) + return true + } + if (before && after && before.mode !== after.mode) { + add({ type: 'hunk', text: `mode ${before.mode.toString(8)} → ${after.mode.toString(8)}` }) + } + for (let i = 0; i < rows.length; i++) { + if (rows[i].row.type === 'ctx') continue + const start = Math.max(0, i - CONTEXT), end = Math.min(rows.length, i + CONTEXT + 1) + const previous = hunks.at(-1) + if (previous && previous.end >= start) previous.end = end + else hunks.push({ start, end }) + } + if (hunks.length === 0 && Boolean(before) !== Boolean(after)) { + add({ type: 'hunk', text: before ? 'Empty file deleted' : 'Empty file added' }) + } + for (const { start, end } of hunks) { + const oldBefore = rows[start - 1]?.oldAt ?? 0, newBefore = rows[start - 1]?.newAt ?? 0 + const oldSize = rows[end - 1].oldAt - oldBefore, newSize = rows[end - 1].newAt - newBefore + if (!add({ type: 'hunk', text: `@@ -${oldBefore + Number(oldSize > 0)},${oldSize} +${newBefore + Number(newSize > 0)},${newSize} @@` })) break + for (let i = start; i < end; i++) { + if (!add(rows[i].row) || (!rows[i].lf && !add({ type: 'hunk', text: '\\ No newline at end of file' }))) break + } + if (truncated) break + } + return { lines, truncated } +} + +export function buildDiff(reader, rel, side, before, after) { + let oldBytes, newBytes + try { + oldBytes = before ? typedObject(reader, before.oid, 'blob') : EMPTY + newBytes = after ? (after.bytes ?? (after.oid === before?.oid ? oldBytes : typedObject(reader, after.oid, 'blob'))) : EMPTY + } catch (error) { + if (error?.code === 'git_stale') throw error + return emptyDiff(rel, side, error?.code === 'git_limit' ? 'too_large' : 'unavailable', limitationFor(error, 'diff_object')) + } + if (oldBytes.length + newBytes.length > MAX_TEXT_BYTES) return emptyDiff(rel, side, 'too_large', 'diff_byte_limit') + const oldText = diffText(oldBytes), newText = diffText(newBytes) + const blocked = [oldText, newText].find(value => value.state === 'unavailable') ?? + [oldText, newText].find(value => value.state !== 'ready') + if (blocked) return emptyDiff(rel, side, blocked.state, blocked.limitation) + const oldLines = toLines(oldText.text), newLines = toLines(newText.text) + if (!oldLines || !newLines) return emptyDiff(rel, side, 'too_large', 'diff_line_limit') + const rows = editRows(oldLines, newLines) + if (!rows) return emptyDiff(rel, side, 'too_large', 'diff_computation_limit') + const { lines, truncated } = renderRows(rows, before, after) + if (truncated && !lines.some(line => line.type === 'add' || line.type === 'del')) { + return emptyDiff(rel, side, 'too_large', 'diff_output_limit') + } + if (!lines.length) return emptyDiff(rel, side, 'unavailable', 'no_text_change') + return { state: 'ready', rel, side, lines, truncated, limitations: truncated ? ['diff_output_limit'] : [] } +} diff --git a/apps/headless/src/git/inspect-history.mjs b/apps/headless/src/git/inspect-history.mjs new file mode 100644 index 00000000..60fe7b7b --- /dev/null +++ b/apps/headless/src/git/inspect-history.mjs @@ -0,0 +1,103 @@ +import { + MAX_ENTRIES, MAX_TREE_BYTES, MAX_TREE_DEPTH, MODE_DIR, MODE_EXEC, MODE_FILE, MODE_GITLINK, MODE_LINK, + SHA1, displayText, fail, safePath, +} from './inspect-policy.mjs' + +const MAX_COMMIT_BYTES = 256 * 1024 +const MAX_PARENTS = 128 +const HASH_BYTES = 20 +const ZERO_OID = '0'.repeat(40) +const BLANK_LINE = Buffer.from('\n\n') +const TREE_MODES = new Map([ + ['40000', MODE_DIR], ['100644', MODE_FILE], ['100755', MODE_EXEC], ['120000', MODE_LINK], ['160000', MODE_GITLINK], +]) + +export function typedObject(reader, oid, type) { + if (typeof oid !== 'string' || !SHA1.test(oid)) fail('git_corrupt') + const object = reader.get(oid) + if (object == null) fail('git_object_unavailable') + if (object.type !== type || !Buffer.isBuffer(object.bytes)) fail('git_corrupt') + return object.bytes +} + +function readAuthor(bytes) { + if (bytes.length > 4096) fail('git_limit') + const match = /^(.*) <[^<>]*> (-?\d{1,12}) [+-]\d{4}$/.exec(bytes.toString('latin1')) + if (!match) fail('git_corrupt') + const timestamp = Number(match[2]) + if (timestamp > 253402300799 || timestamp < -62135596800) fail('git_corrupt') + return { author: displayText(bytes.subarray(0, match[1].length), 96), timestamp } +} + +export function readCommit(reader, oid, includeMetadata = false) { + const bytes = typedObject(reader, oid, 'commit') + if (bytes.length > MAX_COMMIT_BYTES) fail('git_limit') + const body = bytes.indexOf(BLANK_LINE) + if (body < 0 || bytes[4] !== 0x20 || bytes.toString('latin1', 0, 4) !== 'tree') fail('git_corrupt') + const tree = bytes.toString('latin1', 5, 45) + if (!SHA1.test(tree) || tree === ZERO_OID || bytes[45] !== 0x0a) fail('git_corrupt') + let firstParent = null, parents = 0, offset = 46, authorBytes, hasCommitter = false + while (offset < body) { + const lineEnd = bytes.indexOf(0x0a, offset) + if (lineEnd < 0 || lineEnd > body) fail('git_corrupt') + if (bytes.subarray(offset, offset + 7).toString('latin1') === 'parent ') { + const parent = bytes.toString('latin1', offset + 7, lineEnd) + if (!SHA1.test(parent) || parent === ZERO_OID || authorBytes !== undefined) fail('git_corrupt') + if (++parents > MAX_PARENTS) fail('git_limit') + firstParent ??= parent + } else if (bytes.subarray(offset, offset + 7).toString('latin1') === 'author ') { + if (authorBytes !== undefined) fail('git_corrupt') + authorBytes = bytes.subarray(offset + 7, lineEnd) + } else if (bytes.subarray(offset, offset + 10).toString('latin1') === 'committer ') { + if (authorBytes === undefined || hasCommitter) fail('git_corrupt') + hasCommitter = true + } + offset = lineEnd + 1 + } + if (authorBytes === undefined || !hasCommitter) fail('git_corrupt') + if (!includeMetadata) return { tree } + const nextLine = bytes.indexOf(0x0a, body + 2) + const subject = displayText(bytes.subarray(body + 2, nextLine < 0 ? bytes.length : nextLine), 160) + return { firstParent, cost: bytes.length, row: { oid, short: oid.slice(0, 7), subject, ...readAuthor(authorBytes) } } +} + +export function readHeadTree(reader, head) { + const entries = new Map() + let excluded = false, count = 0, total = 0 + if (head === null) return { entries, excluded } + const { tree } = readCommit(reader, head) + function walk(oid, prefix, depth) { + if (depth > MAX_TREE_DEPTH) fail('git_limit') + const bytes = typedObject(reader, oid, 'tree') + total += bytes.length + if (total > MAX_TREE_BYTES) fail('git_limit') + const siblings = new Set() + for (let at = 0; at < bytes.length;) { + if (++count > MAX_ENTRIES) fail('git_limit') + const space = bytes.indexOf(0x20, at) + if (space < 0 || space - at > 6) fail('git_corrupt') + const mode = TREE_MODES.get(bytes.toString('latin1', at, space)) + const nul = bytes.indexOf(0, space + 1) + if (!mode || nul <= space + 1 || bytes.length - nul <= HASH_BYTES) fail('git_corrupt') + const name = bytes.subarray(space + 1, nul) + if (name.includes(0x2f)) fail('git_corrupt') + const key = name.toString('hex') + if (siblings.has(key)) fail('git_corrupt') + siblings.add(key) + const entryOid = bytes.toString('hex', nul + 1, nul + 1 + HASH_BYTES) + if (entryOid === ZERO_OID) fail('git_corrupt') + at = nul + 1 + HASH_BYTES + // A visible parent was already decoded; join through bytes so each raw leaf is validated. + const rel = safePath(prefix ? Buffer.concat([Buffer.from(`${prefix}/`), name]) : name) + if (rel === null) { + excluded = true + } else if (mode === MODE_DIR) { + walk(entryOid, rel, depth + 1) + } else { + entries.set(rel, { mode, oid: entryOid }) + } + } + } + walk(tree, '', 1) + return { entries, excluded } +} diff --git a/apps/headless/src/git/inspect-index.mjs b/apps/headless/src/git/inspect-index.mjs new file mode 100644 index 00000000..8022b07a --- /dev/null +++ b/apps/headless/src/git/inspect-index.mjs @@ -0,0 +1,86 @@ +import { MAX_ENTRIES, MAX_INDEX_BYTES, MODE_DIR, fail, leafMode, safePath, sha1, sha256 } from './inspect-policy.mjs' + +const ENTRY_BYTES = 62 +const HASH_BYTES = 20 +const LENGTH_MASK = 0x0fff +const EXTENDED = 0x4000 +const SKIP_WORKTREE = 0x4000 +const INTENT_TO_ADD = 0x2000 +const ZERO_OID = '0'.repeat(40) +const EMPTY_BLOB_OID = 'e69de29bb2d1d6434b8b29ae775ad8c2e48c5391' + +function indexExtensions(bytes, offset, end) { + while (offset < end) { + if (end - offset < 8) fail('git_corrupt') + const signature = bytes[offset] + const length = bytes.readUInt32BE(offset + 4) + if (length > end - offset - 8) fail('git_corrupt') + // Git's index format reserves an uppercase first signature byte for optional extensions. + // In particular, split index (link) and sparse index (sdir) are required, not hints. + if (signature < 0x41 || signature > 0x5a) fail('git_index_unsupported') + offset += 8 + length + } +} + +export function parseIndex(bytes) { + const entries = new Map() + if (bytes === null) return { entries, excluded: false } + if (!Buffer.isBuffer(bytes) || bytes.length < 12 + HASH_BYTES || bytes.toString('latin1', 0, 4) !== 'DIRC') fail('git_corrupt') + if (bytes.length > MAX_INDEX_BYTES) fail('git_limit') + const end = bytes.length - HASH_BYTES + const version = bytes.readUInt32BE(4) + if (version !== 2 && version !== 3) fail('git_index_unsupported') + if (sha1(bytes.subarray(0, end)) !== bytes.toString('hex', end)) { + // Detect a valid SHA-256 trailer without consulting repository configuration. + if (bytes.length >= 44 && sha256(bytes.subarray(0, -32)) === bytes.toString('hex', bytes.length - 32)) { + fail('git_index_unsupported') + } + fail('git_corrupt') + } + const count = bytes.readUInt32BE(8) + if (count > MAX_ENTRIES) fail('git_limit') + let offset = 12 + let previous, previousStage, excluded = false + for (let entry = 0; entry < count; entry++) { + const start = offset + if (end - offset <= ENTRY_BYTES) fail('git_corrupt') + const mode = bytes.readUInt32BE(offset + 24) + if (mode === MODE_DIR) fail('git_index_unsupported') + if (!leafMode(mode)) fail('git_corrupt') + const oid = bytes.toString('hex', offset + 40, offset + 60) + const flags = bytes.readUInt16BE(offset + 60) + const stage = (flags >> 12) & 3 + let intent = false + offset += ENTRY_BYTES + if (flags & EXTENDED) { + if (version < 3 || end - offset < 3) fail('git_corrupt') + const extended = bytes.readUInt16BE(offset) + if ((extended & SKIP_WORKTREE) || (extended & ~(SKIP_WORKTREE | INTENT_TO_ADD))) fail('git_index_unsupported') + intent = Boolean(extended & INTENT_TO_ADD) + if (intent && (stage !== 0 || oid !== EMPTY_BLOB_OID)) fail('git_corrupt') + offset += 2 + } + const nul = bytes.indexOf(0, offset) + if (nul < 0 || nul >= end || nul === offset || oid === ZERO_OID) fail('git_corrupt') + const name = bytes.subarray(offset, nul) + if (Math.min(name.length, LENGTH_MASK) !== (flags & LENGTH_MASK)) fail('git_corrupt') + if (previous) { + const order = Buffer.compare(previous, name) + if (order > 0 || (order === 0 && (previousStage === 0 || previousStage >= stage))) fail('git_corrupt') + } + previous = name + previousStage = stage + offset = start + Math.ceil((nul + 1 - start) / 8) * 8 + if (offset > end || bytes.subarray(nul, offset).some(byte => byte !== 0)) fail('git_corrupt') + const rel = safePath(name) + if (rel === null) { + excluded = true + } else { + const stages = entries.get(rel) ?? [] + stages[stage] = { mode, oid, intent } + entries.set(rel, stages) + } + } + indexExtensions(bytes, offset, end) + return { entries, excluded } +} diff --git a/apps/headless/src/git/inspect-policy.mjs b/apps/headless/src/git/inspect-policy.mjs new file mode 100644 index 00000000..d4d46f06 --- /dev/null +++ b/apps/headless/src/git/inspect-policy.mjs @@ -0,0 +1,86 @@ +import { createHash } from 'node:crypto' +import { decodeUtf8 } from '../files/workspace-files-fd.mjs' +import { sensitiveBytes, workPath } from './repository-paths.mjs' + +export const SHA1 = /^[0-9a-f]{40}$/ +export const MODE_FILE = 0o100644 +export const MODE_EXEC = 0o100755 +export const MODE_LINK = 0o120000 +export const MODE_GITLINK = 0o160000 +export const MODE_DIR = 0o040000 +export const MAX_ENTRIES = 2000 +export const MAX_TREE_DEPTH = 16 +export const MAX_INDEX_BYTES = 4 * 1024 * 1024 +export const MAX_TREE_BYTES = 4 * 1024 * 1024 +export const MAX_WORK_FILE_BYTES = 2 * 1024 * 1024 +export const MAX_WORK_BYTES = 32 * 1024 * 1024 +export const MAX_TEXT_BYTES = 256 * 1024 +export const MAX_RESULT_ROWS_BYTES = 1536 * 1024 + +const PRIVATE_NAME = /^(?:env(?:[._-].*)?|(?:.*[._-])?(?:credentials?|secrets?|passwords?|tokens?|private[-_ ]?keys?|keystores?|keyrings?)(?:[._-].*)?|id_(?:rsa|dsa|ecdsa|ed25519)(?:[._-].*)?|authorized_keys|known_hosts|passwd|shadow|netrc|npmrc|pypirc|git-credentials)$/i +const PRIVATE_SUFFIX = /\.(?:pem|key|p12|pfx|pkcs12|jks|keystore|kdbx|ovpn|ppk)$/i +const PRIVATE_TEXT = /-----BEGIN [A-Z0-9 -]{0,48}(?:PRIVATE KEY(?: BLOCK)?|PKCS12)-----|PuTTY-User-Key-File-[0-9]{1,2}:/i +const BINARY_CONTROL = /[\u0000-\u0008\u000e-\u001f\u007f-\u0084\u0086-\u009f]/u +const UNSAFE_DISPLAY = /[\u0000-\u001f\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]|[^\s<>()]@[^\s<>()]|:\/\/|\b(?:file|ssh|git|ftp|https?|mailto|data):\S|(?:^|[^\p{L}\p{N}_.\-/])(?:\/(?=\S)|[a-z]:[\\/]|\\\\|~\/)/iu +const UNSAFE_REF = /[\p{Cf}\p{Zl}\p{Zp}]|@[a-z0-9][a-z0-9.-]{0,99}\.[a-z][a-z0-9]{1,10}(?:\/|$)|[\\:]|^\/|\/\//iu + +export function gitInspectError(code) { + return Object.assign(new Error(code), { code }) +} + +export function fail(code) { throw gitInspectError(code) } +export function regularMode(mode) { return mode === MODE_FILE || mode === MODE_EXEC } +export function leafMode(mode) { return regularMode(mode) || mode === MODE_LINK || mode === MODE_GITLINK } +export function sha1(bytes) { return createHash('sha1').update(bytes).digest('hex') } +export function blobOid(bytes) { + return createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex') +} +export function sha256(bytes) { return createHash('sha256').update(bytes).digest('hex') } + +export function safePath(bytes) { + try { + const rel = decodeUtf8(bytes) + const parts = workPath(rel) + if (!parts || parts.some(part => PRIVATE_NAME.test(part) || PRIVATE_SUFFIX.test(part) || + /[\u202a-\u202e\u2066-\u2069\ufeff]/u.test(part))) return null + return rel + } catch { return null } +} + +export function diffText(bytes) { + if (sensitiveBytes(bytes)) return { state: 'unavailable', limitation: 'sensitive_content' } + try { + const text = decodeUtf8(bytes) + if (PRIVATE_TEXT.test(text)) return { state: 'unavailable', limitation: 'sensitive_content' } + if (BINARY_CONTROL.test(text)) return { state: 'binary', limitation: 'binary_content' } + return { state: 'ready', text } + } catch { return { state: 'binary', limitation: 'binary_content' } } +} + +export function displayRef(value) { + if (typeof value !== 'string' || value.length === 0 || value.length > 512 || UNSAFE_REF.test(value) || + /[\u0000-\u001f\u007f-\u009f]/u.test(value) || !value.isWellFormed()) return null + return value +} + +export function displayText(bytes, limit) { + // Validate all of the bounded first line before truncating; never show part of a redacted value. + if (bytes.length > 4096) return '' + try { + const value = decodeUtf8(bytes).trim() + if (UNSAFE_DISPLAY.test(value) || PRIVATE_TEXT.test(value)) return '' + const chars = Array.from(value) + return chars.length > limit ? chars.slice(0, limit - 1).join('') + '…' : value + } catch { return '' } +} + +export function limitationFor(error, fallback) { + switch (error?.code) { + case 'git_limit': return `${fallback}_limit` + case 'git_object_unavailable': return 'missing_object' + case 'git_corrupt': return `${fallback}_invalid` + case 'unsupported_git_layout': return 'unsupported_layout' + case 'git_index_unsupported': return 'index_unsupported' + default: return `${fallback}_unavailable` + } +} diff --git a/apps/headless/src/git/inspect-status.mjs b/apps/headless/src/git/inspect-status.mjs new file mode 100644 index 00000000..079b5722 --- /dev/null +++ b/apps/headless/src/git/inspect-status.mjs @@ -0,0 +1,141 @@ +import { createHash } from 'node:crypto' +import { parseIndex } from './inspect-index.mjs' +import { readHeadTree } from './inspect-history.mjs' +import { + MAX_ENTRIES, MAX_INDEX_BYTES, MAX_RESULT_ROWS_BYTES, MAX_WORK_BYTES, MAX_WORK_FILE_BYTES, MODE_EXEC, MODE_FILE, + blobOid, limitationFor, regularMode, sha256, +} from './inspect-policy.mjs' + +function change(before, after) { + if (!before) return after ? 'A' : null + if (!after) return 'D' + if ((before.mode & 0o170000) !== (after.mode & 0o170000)) return 'T' + return before.oid !== after.oid || before.mode !== after.mode ? 'M' : null +} + +function mayDiff(letter, before, after) { + return Boolean(letter && (!before || regularMode(before.mode)) && (!after || regularMode(after.mode))) +} + +export function statusSnapshot(state, fields, limitations, hash, entries = []) { + return { state, ...fields, limitations: [...limitations], fingerprint: hash.digest('hex'), entries } +} + +export function emptyStatus(state, fields, limitations) { + return statusSnapshot(state, fields, limitations, + createHash('sha256').update(JSON.stringify(['git-view-v1', state, fields, [...limitations]]))) +} + +function workReader(io, hash, limitations, markPartial) { + let remaining = MAX_WORK_BYTES, exhausted = false + return function readWork(rel, keepBytes) { + let work + const limit = Math.min(remaining, MAX_WORK_FILE_BYTES) + if (!limit || exhausted) work = { state: 'budget' } + else { + try { work = io.workFile(rel, limit) } + catch (error) { + if (error?.code === 'git_stale') throw error + if (error?.code === 'git_limit') { + exhausted = true + work = { state: 'budget' } + } else work = { state: 'unsafe' } + } + } + if (work?.state === 'regular' && Buffer.isBuffer(work.bytes) && typeof work.executable === 'boolean' && work.bytes.length <= limit) { + const { bytes } = work + remaining -= bytes.length + const mode = work.executable ? MODE_EXEC : MODE_FILE + const oid = blobOid(bytes) + hash.update(JSON.stringify([rel, 'regular', mode, bytes.length, sha256(bytes)])) + return { state: 'regular', entry: { mode, oid, ...(keepBytes ? { bytes } : {}) } } + } + if (work?.state === 'missing') { + hash.update(JSON.stringify([rel, 'missing'])) + return { state: 'missing', entry: null } + } + const state = work?.state === 'too_large' && limit === MAX_WORK_FILE_BYTES ? 'too_large' : + work?.state === 'too_large' || work?.state === 'budget' ? 'budget' : 'unsafe' + markPartial() + limitations.add(({ too_large: 'worktree_file_limit', budget: 'worktree_budget', unsafe: 'unsafe_worktree' })[state]) + hash.update(JSON.stringify([rel, state])) + return { state, entry: null } + } +} + +export function collectStatus(io, reader, refs, fields, limitations, selectedRel) { + const hash = createHash('sha256').update(JSON.stringify(['git-view-v1', refs.head, refs.branch, fields])) + let index, head, target, state = 'ready' + try { + const indexBytes = io.readMeta('index', MAX_INDEX_BYTES) + index = parseIndex(indexBytes) + hash.update(JSON.stringify(['index', indexBytes === null ? null : sha256(indexBytes)])) + } catch (error) { + if (error?.code === 'git_stale') throw error + const reason = limitationFor(error, 'index') + limitations.add(reason) + hash.update(JSON.stringify(reason)) + const unavailable = error?.code === 'git_index_unsupported' || error?.code === 'unsupported_git_layout' ? 'unsupported_layout' : 'unavailable' + return { status: statusSnapshot(unavailable, fields, limitations, hash) } + } + try { head = readHeadTree(reader, refs.head) } + catch (error) { + if (error?.code === 'git_stale') throw error + const reason = limitationFor(error, 'head_tree') + limitations.add(reason) + hash.update(JSON.stringify(reason)) + return { status: statusSnapshot(error?.code === 'unsupported_git_layout' ? 'unsupported_layout' : 'unavailable', fields, limitations, hash) } + } + if (index.excluded || head.excluded) limitations.add('excluded_paths') + const entries = [] + let outputBytes = 0, outputFull = false + const paths = [...new Set([...index.entries.keys(), ...head.entries.keys()])].sort() + if (paths.length > MAX_ENTRIES) { + state = 'partial' + limitations.add('status_entry_limit') + hash.update(JSON.stringify(['status_entry_limit', paths.length])) + paths.length = MAX_ENTRIES + } + const readWork = workReader(io, hash, limitations, () => { state = 'partial' }) + for (const rel of paths) { + const headEntry = head.entries.get(rel) ?? null + const stages = index.entries.get(rel) + const indexEntry = stages?.[0] ?? null + const conflicted = stages !== undefined && indexEntry === null + const conflictHasNonRegular = conflicted && stages.some(entry => !regularMode(entry.mode)) + const hasRegularStage = stages?.some(entry => regularMode(entry.mode)) + if (conflictHasNonRegular || (headEntry && !regularMode(headEntry.mode)) || (indexEntry && !regularMode(indexEntry.mode))) { + limitations.add('non_regular_entries') + if (conflictHasNonRegular || (!hasRegularStage && !regularMode(headEntry?.mode))) continue + } + // A pathname removed from the index is no longer tracked in the worktree, even if an + // untracked replacement currently exists at the same name. Never open it for comparison. + const work = hasRegularStage ? readWork(rel, rel === selectedRel) : { state: 'not_tracked', entry: null } + if (work.state === 'unsafe' || work.state === 'budget') continue + const intent = indexEntry?.intent === true + const staged = conflicted ? 'U' : intent ? null : change(headEntry, indexEntry) + const workBase = intent ? null : indexEntry + const workAvailable = work.state === 'regular' || work.state === 'missing' + const worktree = conflicted ? 'U' : workAvailable ? change(workBase, work.entry) : null + const diffSides = [] + if (!conflicted) { + if (mayDiff(staged, headEntry, indexEntry)) diffSides.push('staged') + if (mayDiff(worktree, workBase, work.entry)) diffSides.push('worktree') + } + if (staged || worktree) { + const row = { rel, staged, worktree, conflicted, diffSides } + if (!outputFull) outputBytes += 1 + Buffer.byteLength(JSON.stringify(row)) + if (outputBytes > MAX_RESULT_ROWS_BYTES) { + outputFull = true + state = 'partial' + limitations.add('status_output_limit') + // Still fingerprint approved worktree slots; omit this and following rows from the view. + continue + } + entries.push(row) + } + if (rel === selectedRel) target = { headEntry, indexEntry, workBase, work, conflicted, diffSides } + } + hash.update(JSON.stringify([state, [...limitations]])) + return { status: statusSnapshot(state, fields, limitations, hash, entries), target } +} diff --git a/apps/headless/src/git/inspect-worker.mjs b/apps/headless/src/git/inspect-worker.mjs new file mode 100644 index 00000000..7b0438f4 --- /dev/null +++ b/apps/headless/src/git/inspect-worker.mjs @@ -0,0 +1,22 @@ +import { isMainThread, parentPort, workerData } from 'node:worker_threads' +import { openGitIo } from './repository.mjs' +import { inspectGit } from './inspect.mjs' + +const known = new Set(['git_unsafe', 'git_stale', 'git_corrupt', 'git_object_unavailable', 'git_limit', 'unsupported_git_layout']) + +// This thread only separates bounded SHA/pack/diff computation from the owner HTTP loop. It +// is not a general code sandbox, accepts no script or shell command, and has no model RPC. +if (!isMainThread && parentPort) { + let io, reply + try { + io = openGitIo({ fd: workerData.fd, mount: workerData.mount }) + const result = inspectGit(io, workerData.job) + if (result instanceof Promise || !result || typeof result !== 'object') throw Error('invalid result') + io.verify() + if (Buffer.byteLength(JSON.stringify(result)) > 2 * 1024 * 1024) throw Object.assign(Error(), {code:'git_limit'}) + reply = { ok: true, result } + } catch (error) { reply = { ok: false, error: known.has(error?.code) ? error.code : 'git_unavailable' } } + finally { try { io?.close() } catch { reply = {ok:false,error:'git_unavailable'} } } + parentPort.postMessage(reply) + parentPort.close() +} diff --git a/apps/headless/src/git/inspect.mjs b/apps/headless/src/git/inspect.mjs new file mode 100644 index 00000000..a1c964cb --- /dev/null +++ b/apps/headless/src/git/inspect.mjs @@ -0,0 +1,127 @@ +import { buildDiff, emptyDiff } from './inspect-diff.mjs' +import { readCommit } from './inspect-history.mjs' +import { MAX_RESULT_ROWS_BYTES, displayRef, fail, limitationFor, safePath } from './inspect-policy.mjs' +import { collectStatus, emptyStatus } from './inspect-status.mjs' +import { createGitObjectReader } from './objects.mjs' +import { readGitRefs } from './refs.mjs' + +const MAX_BRANCHES = 2000 +const MAX_LOG_COUNT = 100 +const MAX_LOG_BYTES = 8 * 1024 * 1024 +const OPS = new Set(['branches', 'log', 'status', 'diff']) +const DIFFERENT_SIDES = new Set(['staged', 'worktree']) +const NO_HEAD = { branch: null, detached: false, unborn: false, mergeInProgress: false } + +function ioFailure(state) { + if (state === undefined || state === 'ready') return null + return state === 'not_repo' || state === 'unsupported_layout' ? state : 'unavailable' +} + +function readRefs(io) { + const ioState = ioFailure(io.state) + if (ioState) return { refs: null, state: ioState, limitations: new Set([ioState]) } + try { + const refs = readGitRefs(io) + const limitations = new Set(refs.limitations) + const branch = displayRef(refs.branch) + if (refs.branch !== null && branch === null) limitations.add('excluded_refs') + const fields = { branch, detached: refs.detached, unborn: refs.unborn, mergeInProgress: refs.mergeInProgress } + return { state: 'ready', refs, fields, limitations } + } catch (error) { + if (error?.code === 'git_stale') throw error + const state = error?.code === 'unsupported_git_layout' ? 'unsupported_layout' : 'unavailable' + return { refs: null, state, limitations: new Set([limitationFor(error, 'refs')]) } + } +} + +function branches({ refs, state, fields = NO_HEAD, limitations }) { + const rows = [] + let outputBytes = 0 + if (refs) { + limitations.add('upstream_unknown') + for (const ref of refs.branches) { + const name = displayRef(ref.name), remote = ref.remote === null ? null : displayRef(ref.remote) + if (name === null || (ref.remote !== null && remote === null)) { + limitations.add('excluded_refs') + continue + } + if (rows.length === MAX_BRANCHES) { + state = 'partial' + limitations.add('branch_limit') + break + } + const row = { name, current: ref.current, remote } + outputBytes += 1 + Buffer.byteLength(JSON.stringify(row)) + if (outputBytes > MAX_RESULT_ROWS_BYTES) { + state = 'partial' + limitations.add('branch_output_limit') + break + } + rows.push(row) + } + } + return { state, branch: fields.branch, detached: fields.detached, unborn: fields.unborn, branches: rows, limitations: [...limitations] } +} + +function log(reader, { refs, state, fields = NO_HEAD, limitations }, requestedLimit) { + const limit = Number.isInteger(requestedLimit) ? Math.min(MAX_LOG_COUNT, Math.max(1, requestedLimit)) : 50 + const commits = [], seen = new Set() + let oid = refs?.head ?? null, bytes = 0, more = false + while (oid !== null) { + if (commits.length === limit) { more = true; break } + try { + if (seen.has(oid)) fail('git_corrupt') + seen.add(oid) + const commit = readCommit(reader, oid, true) + bytes += commit.cost + if (bytes > MAX_LOG_BYTES) fail('git_limit') + commits.push(commit.row) + oid = refs.shallow.has(oid) ? null : commit.firstParent + } catch (error) { + if (error?.code === 'git_stale') throw error + limitations.add(limitationFor(error, 'history')) + state = commits.length ? 'partial' : error?.code === 'unsupported_git_layout' ? 'unsupported_layout' : 'unavailable' + break + } + } + return { state, branch: fields.branch, commits, traversal: 'first-parent', more, limitations: [...limitations] } +} + +function status(io, reader, { refs, state, fields = NO_HEAD, limitations }, rel) { + limitations.add('tracked_only') + if (!refs) return { status: emptyStatus(state, fields, limitations) } + return collectStatus(io, reader, refs, fields, limitations, rel) +} + +function validateDiff({ rel, side, expectedFingerprint }) { + if (typeof expectedFingerprint !== 'string' || expectedFingerprint.length !== 64 || !/^[a-f0-9]{64}$/.test(expectedFingerprint)) fail('git_stale') + if (typeof rel !== 'string' || rel.length > 4095 || !rel.isWellFormed() || safePath(Buffer.from(rel)) !== rel || + !DIFFERENT_SIDES.has(side)) fail('git_invalid_job') +} + +function diff(io, reader, refState, { rel, side, expectedFingerprint }) { + const snapshot = status(io, reader, refState, rel) + if (snapshot.status.fingerprint !== expectedFingerprint) fail('git_stale') + const { target } = snapshot + if (!target) return emptyDiff(rel, side, 'unavailable', 'entry_unavailable') + if (target.conflicted) return emptyDiff(rel, side, 'unavailable', 'conflicted_entry') + if (!target.diffSides.includes(side)) { + if (side === 'worktree' && target.work.state === 'too_large') return emptyDiff(rel, side, 'too_large', 'worktree_file_limit') + return emptyDiff(rel, side, 'unavailable', 'side_unavailable') + } + return side === 'staged' + ? buildDiff(reader, rel, side, target.headEntry, target.indexEntry) + : buildDiff(reader, rel, side, target.workBase, target.work.entry) +} + +/** Synchronous inspection; job.rel/job.side are service-resolved view data, never browser input. */ +export function inspectGit(io, job) { + if (!job || !OPS.has(job.op)) fail('git_invalid_job') + if (job.op === 'diff') validateDiff(job) + const refState = readRefs(io) + if (job.op === 'branches') return branches(refState) + const reader = createGitObjectReader(io) + if (job.op === 'log') return log(reader, refState, job.limit) + if (job.op === 'status') return status(io, reader, refState).status + return diff(io, reader, refState, job) +} diff --git a/apps/headless/src/git/objects-format.mjs b/apps/headless/src/git/objects-format.mjs new file mode 100644 index 00000000..85c024b2 --- /dev/null +++ b/apps/headless/src/git/objects-format.mjs @@ -0,0 +1,63 @@ +import { createHash } from 'node:crypto' +import { inflateSync } from 'node:zlib' + +const MiB = 1024 * 1024 +export const limits = Object.freeze({ + pack: 24 * MiB, + packTotal: 48 * MiB, // Sum of the pack and idx file lengths. + packs: 16, + directoryEntries: 128, + packObjects: 8192, + gets: 8192, + object: 2 * MiB, + tree: 4 * MiB, + loose: 4 * MiB + 64 * 1024, + delta: 8 * MiB, // Instructions can be larger than the reconstructed object. + deltaDepth: 32, + work: 64 * MiB, + activeMs: 1000 +}) + +const publicCodes = new Set([ + 'git_limit', 'git_corrupt', 'git_object_unavailable', 'unsupported_git_layout', + // Preserve safe codes from the pinned metadata boundary, without its messages. + 'git_stale', 'git_unsafe' +]) +export const gitError = code => Object.assign(new Error(code), { code }) +export function meta(callback) { + try { return callback() } + catch (error) { + throw gitError(publicCodes.has(error?.code) ? error.code : 'git_object_unavailable') + } +} + +export const oidPattern = /^[0-9a-f]{40}$/ +export const rawSha1 = bytes => createHash('sha1').update(bytes).digest() +export const objectLimit = type => type === 'tree' ? limits.tree : limits.object + +export function verifyObject(oid, object) { + const { type, bytes } = object + const hash = createHash('sha1').update(`${type} ${bytes.length}\0`).update(bytes).digest('hex') + if (hash !== oid) throw gitError('git_corrupt') + return object +} + +// Node's info.engine.bytesWritten reports the input consumed, not output size. +// Git entries have one complete zlib stream, without padding or a second stream. +export function inflateObject(input, maximum, excessCode, work) { + work.consume(input.length) + const cap = Math.min(maximum, work.remaining) + let result + try { + result = inflateSync(input, { maxOutputLength: Math.max(1, cap), info: true }) + } catch (error) { + // Failed inflation does not expose the bytes emitted before the failure. + work.consume(cap) + if (error?.code === 'ERR_BUFFER_TOO_LARGE') throw gitError(cap < maximum ? 'git_limit' : excessCode) + throw gitError('git_corrupt') + } + work.consume(result.buffer.length) + if (result.buffer.length > maximum) throw gitError(excessCode) + if (result.engine.bytesWritten !== input.length) throw gitError('git_corrupt') + return result.buffer +} diff --git a/apps/headless/src/git/objects.mjs b/apps/headless/src/git/objects.mjs new file mode 100644 index 00000000..7bdd5e37 --- /dev/null +++ b/apps/headless/src/git/objects.mjs @@ -0,0 +1,109 @@ +import { performance } from 'node:perf_hooks' +import { gitError, inflateObject, limits, meta, objectLimit, oidPattern, verifyObject } from './objects-format.mjs' +import { applyDelta, inflatePackEntry, readPacks } from './pack.mjs' + +const LOOSE_HEADER_MAX = 32 + +function readLoose(io, oid, work) { + const cap = Math.min(limits.loose, work.remaining) + if (!cap) throw gitError('git_limit') + const encoded = meta(() => io.readMeta(`objects/${oid.slice(0, 2)}/${oid.slice(2)}`, cap)) + work.check() + if (encoded === null) return null + if (!Buffer.isBuffer(encoded)) throw gitError('git_corrupt') + if (encoded.length > cap) throw gitError('git_limit') + const raw = inflateObject(encoded, limits.tree + LOOSE_HEADER_MAX, 'git_limit', work) + const headerEnd = raw.subarray(0, LOOSE_HEADER_MAX).indexOf(0) + if (headerEnd < 0) throw gitError('git_corrupt') + const header = /^(commit|tree|blob|tag) (0|[1-9][0-9]*)$/.exec(raw.toString('latin1', 0, headerEnd)) + if (!header) throw gitError('git_corrupt') + const [, type, size] = header + const declared = Number(size) + if (declared > objectLimit(type)) throw gitError('git_limit') + const bytes = raw.subarray(headerEnd + 1) + if (bytes.length > objectLimit(type)) throw gitError('git_limit') + if (bytes.length !== declared) throw gitError('git_corrupt') + return verifyObject(oid, { type, bytes }) +} + +/** + * Read SHA-1 objects named by trusted internal refs/index/tree traversal. + * io is already scoped to the approved project's pinned Git metadata directory; + * reads return fresh buffers (or null for missing files) and an absent pack + * directory lists as []. Use one reader per operation with synchronous traversal. + * Disk and zlib calls are synchronous; the active-time deadline is cooperative. + */ +export function createGitObjectReader(io) { + let packs, packError + let calls = 0, elapsed = 0, remaining = limits.work + + function unpackedPacks(work) { + if (packError) throw gitError(packError) + if (!packs) { + try { packs = readPacks(io, work) } + catch (error) { + packError = error.code + throw error + } + } + return packs + } + + function locate(oid, work, samePack) { + const preferred = samePack?.byOid.get(oid) + if (preferred) return { pack: samePack, entry: preferred } + const loose = readLoose(io, oid, work) + if (loose) return { loose } + for (const pack of unpackedPacks(work)) { + const entry = pack.byOid.get(oid) + if (entry) return { pack, entry } + } + throw gitError('git_object_unavailable') + } + + function resolve(pack, entry, depth, active, work) { + work.check() + if (depth > limits.deltaDepth) throw gitError('git_limit') + const { oid, type, offsetBase, refBase } = entry + if (active.has(oid)) throw gitError('git_corrupt') + if (type) return verifyObject(oid, { type, bytes: inflatePackEntry(pack, entry, work) }) + if (entry.size > limits.delta || depth === limits.deltaDepth) throw gitError('git_limit') + active.add(oid) + try { + let base + if (offsetBase) base = resolve(pack, offsetBase, depth + 1, active, work) + else { + if (active.has(refBase)) throw gitError('git_corrupt') + const target = locate(refBase, work, pack) + base = target.loose ?? resolve(target.pack, target.entry, depth + 1, active, work) + } + return verifyObject(oid, applyDelta(inflatePackEntry(pack, entry, work), base, work)) + } finally { active.delete(oid) } + } + + function get(oid) { + if (++calls > limits.gets) throw gitError('git_limit') + const started = performance.now() + const work = { + get remaining() { return remaining }, + check() { + if (elapsed + (performance.now() - started) >= limits.activeMs) throw gitError('git_limit') + }, + consume(bytes) { + if (bytes > remaining) throw gitError('git_limit') + remaining -= bytes + this.check() + } + } + try { + work.check() + if (typeof oid !== 'string' || oid.length !== 40 || !oidPattern.test(oid)) throw gitError('git_corrupt') + const target = locate(oid, work) + const object = target.loose ?? resolve(target.pack, target.entry, 0, new Set(), work) + work.check() + return object + } finally { elapsed += performance.now() - started } + } + + return { get } +} diff --git a/apps/headless/src/git/pack-index.mjs b/apps/headless/src/git/pack-index.mjs new file mode 100644 index 00000000..88741fe5 --- /dev/null +++ b/apps/headless/src/git/pack-index.mjs @@ -0,0 +1,56 @@ +import { gitError, limits, rawSha1 } from './objects-format.mjs' + +const MAGIC = 0xff744f63 +const FANOUT_END = 8 + 256 * 4 +const TRAILER = 40 +export const maxIndexBytes = FANOUT_END + 36 * limits.packObjects + TRAILER + +export function parsePackIndex(bytes, objectsRemaining, work) { + const length = bytes.length + if (length < FANOUT_END - 8 + TRAILER) throw gitError('git_corrupt') + if (!rawSha1(bytes.subarray(0, -20)).equals(bytes.subarray(-20))) throw gitError('git_corrupt') + if (bytes.readUInt32BE(0) !== MAGIC || bytes.readUInt32BE(4) !== 2) throw gitError('unsupported_git_layout') + if (length < FANOUT_END + TRAILER) throw gitError('git_corrupt') + + const count = bytes.readUInt32BE(FANOUT_END - 4) + if (count > objectsRemaining) throw gitError('git_limit') + const crcStart = FANOUT_END + count * 20 + const offsetStart = crcStart + count * 4 + const largeStart = offsetStart + count * 4 + const largeBytes = length - TRAILER - largeStart + if (largeBytes < 0 || largeBytes % 8 || largeBytes > count * 8) throw gitError('git_corrupt') + const usedLarge = new Uint8Array(largeBytes / 8) + + const byOid = new Map() + const byOffset = new Map() + let previousOid + let i = 0 + for (let bucket = 0; bucket < 256; bucket++) { + work.check() + const stop = bytes.readUInt32BE(8 + bucket * 4) + if (stop < i || stop > count) throw gitError('git_corrupt') + for (; i < stop; i++) { + const start = FANOUT_END + i * 20 + const id = bytes.subarray(start, start + 20) + if (id[0] !== bucket || (previousOid && Buffer.compare(previousOid, id) >= 0)) throw gitError('git_corrupt') + previousOid = id + + let offset = bytes.readUInt32BE(offsetStart + i * 4) + if (offset >= 0x80000000) { + const index = offset - 0x80000000 + if (index >= usedLarge.length || usedLarge[index]) throw gitError('git_corrupt') + usedLarge[index] = 1 + const wideOffset = bytes.readBigUInt64BE(largeStart + index * 8) + if (wideOffset >= BigInt(limits.pack)) throw gitError('git_corrupt') + offset = Number(wideOffset) + } + if (offset < 12 || offset >= limits.pack || byOffset.has(offset)) throw gitError('git_corrupt') + const oid = id.toString('hex') + const entry = { oid, offset, crc: bytes.readUInt32BE(crcStart + i * 4) } + byOid.set(oid, entry) + byOffset.set(offset, entry) + } + } + if (usedLarge.includes(0)) throw gitError('git_corrupt') + return { byOid, byOffset, checksum: Buffer.from(bytes.subarray(-40, -20)) } +} diff --git a/apps/headless/src/git/pack.mjs b/apps/headless/src/git/pack.mjs new file mode 100644 index 00000000..b1552513 --- /dev/null +++ b/apps/headless/src/git/pack.mjs @@ -0,0 +1,186 @@ +import { gitError, inflateObject, limits, meta, objectLimit, rawSha1 } from './objects-format.mjs' +import { maxIndexBytes, parsePackIndex } from './pack-index.mjs' + +const PACK_MAGIC = 0x5041434b +const HEADER = 12 +const TRAILER = 20 +const OFS_DELTA = 6 +const REF_DELTA = 7 +const types = [undefined, 'commit', 'tree', 'blob', 'tag'] + +// Git's idx v2 CRC32 uses the IEEE polynomial. Keep this compatible with Node +// 22.0 as well as Node releases with node:zlib.crc32. +const crcTable = Uint32Array.from({ length: 256 }, (_, i) => { + for (let j = 0; j < 8; j++) i = (i >>> 1) ^ (i & 1 ? 0xedb88320 : 0) + return i +}) +function crc32(bytes, start, end) { + let crc = 0xffffffff + for (let i = start; i < end; i++) crc = (crc >>> 8) ^ crcTable[(crc ^ bytes[i]) & 0xff] + return (crc ^ 0xffffffff) >>> 0 +} + +function parseEntryHeader(bytes, entry, end, byOffset) { + let cursor = entry.offset + const next = () => { + if (cursor >= end) throw gitError('git_corrupt') + return bytes[cursor++] + } + let octet = next() + const kind = (octet >>> 4) & 7 + const type = types[kind] + if (!type && kind !== OFS_DELTA && kind !== REF_DELTA) throw gitError('git_corrupt') + + let size = octet & 15 + let place = 16 + while (octet & 0x80) { + if (!Number.isSafeInteger(place)) throw gitError('git_corrupt') + octet = next() + size += (octet & 0x7f) * place + if (!Number.isSafeInteger(size)) throw gitError('git_corrupt') + place *= 128 + } + + let offsetBase, refBase + if (kind === OFS_DELTA) { + octet = next() + let distance = octet & 0x7f + const maxDistance = entry.offset - HEADER + while (octet & 0x80) { + octet = next() + distance = (distance + 1) * 128 + (octet & 0x7f) + if (distance > maxDistance) throw gitError('git_corrupt') + } + if (!distance || distance > maxDistance) throw gitError('git_corrupt') + offsetBase = byOffset.get(entry.offset - distance) + if (!offsetBase) throw gitError('git_corrupt') + } else if (kind === REF_DELTA) { + if (cursor + 20 > end) throw gitError('git_corrupt') + refBase = bytes.toString('hex', cursor, cursor + 20) + cursor += 20 + } + if (end - cursor < 8) throw gitError('git_corrupt') // Minimum zlib stream size. + Object.assign(entry, { start: cursor, end, type, size, offsetBase, refBase }) +} + +function validatePack(bytes, index, work) { + if (bytes.length < HEADER + TRAILER || bytes.readUInt32BE(0) !== PACK_MAGIC) throw gitError('git_corrupt') + const version = bytes.readUInt32BE(4) + if (version !== 2 && version !== 3) throw gitError('unsupported_git_layout') + if (bytes.readUInt32BE(8) !== index.byOid.size) throw gitError('git_corrupt') + const end = bytes.length - TRAILER + if (!bytes.subarray(end).equals(index.checksum) || !rawSha1(bytes.subarray(0, end)).equals(index.checksum)) { + throw gitError('git_corrupt') + } + const entries = [...index.byOffset.values()].sort((a, b) => a.offset - b.offset) + if ((entries[0]?.offset ?? end) !== HEADER) throw gitError('git_corrupt') + for (let i = 0; i < entries.length; i++) { + work.check() + const entry = entries[i] + const nextOffset = entries[i + 1]?.offset ?? end + if (entry.offset >= nextOffset || nextOffset > end) throw gitError('git_corrupt') + if (crc32(bytes, entry.offset, nextOffset) !== entry.crc) throw gitError('git_corrupt') + parseEntryHeader(bytes, entry, nextOffset, index.byOffset) + } + return { bytes, byOid: index.byOid } +} + +function packNames(io, work) { + const listed = meta(() => io.listMeta('objects/pack', limits.directoryEntries)) + work.check() + if (!Array.isArray(listed)) throw gitError('git_corrupt') + if (listed.length > limits.directoryEntries) throw gitError('git_limit') + const pairs = new Map() + for (const item of listed) { + const name = item?.name + if (typeof name !== 'string' || !name.startsWith('pack-') || !(name.endsWith('.pack') || name.endsWith('.idx'))) continue + const match = /^(pack-[0-9a-f]{40})\.(pack|idx)$/.exec(name) + if (!match || item.type !== 'file') throw gitError('unsupported_git_layout') + const [, prefix, suffix] = match + const files = pairs.get(prefix) ?? new Set() + if (files.has(suffix)) throw gitError('git_corrupt') + files.add(suffix) + pairs.set(prefix, files) + if (pairs.size > limits.packs) throw gitError('git_limit') + } + for (const files of pairs.values()) if (files.size !== 2) throw gitError('git_corrupt') + return [...pairs.keys()].sort() +} + +export function readPacks(io, work) { + let remaining = limits.packTotal + let objectsRemaining = limits.packObjects + const read = (prefix, suffix, maximum) => { + const cap = Math.min(maximum, remaining) + if (!cap) throw gitError('git_limit') + const bytes = meta(() => io.readMeta(`objects/pack/${prefix}.${suffix}`, cap)) + work.check() + if (bytes === null) throw gitError('git_object_unavailable') + if (!Buffer.isBuffer(bytes)) throw gitError('git_corrupt') + if (bytes.length > cap) throw gitError('git_limit') + remaining -= bytes.length + return bytes + } + const packs = [] + for (const name of packNames(io, work)) { + const index = parsePackIndex(read(name, 'idx', maxIndexBytes), objectsRemaining, work) + objectsRemaining -= index.byOid.size + packs.push(validatePack(read(name, 'pack', limits.pack), index, work)) + } + return packs +} + +export function inflatePackEntry(pack, entry, work) { + const maximum = entry.type ? objectLimit(entry.type) : limits.delta + if (entry.size > maximum) throw gitError('git_limit') + const result = inflateObject(pack.bytes.subarray(entry.start, entry.end), entry.size, 'git_corrupt', work) + if (result.length !== entry.size) throw gitError('git_corrupt') + return result +} + +export function applyDelta(delta, base, work) { + let cursor = 0 + const next = () => { + if (cursor >= delta.length) throw gitError('git_corrupt') + return delta[cursor++] + } + const size = () => { + let value = 0, place = 1, octet + do { + if (!Number.isSafeInteger(place)) throw gitError('git_corrupt') + octet = next() + value += (octet & 0x7f) * place + if (!Number.isSafeInteger(value)) throw gitError('git_corrupt') + place *= 128 + } while (octet & 0x80) + return value + } + if (size() !== base.bytes.length) throw gitError('git_corrupt') + const resultSize = size() + if (resultSize > objectLimit(base.type)) throw gitError('git_limit') + work.consume(resultSize) + const bytes = Buffer.alloc(resultSize) + let written = 0 + let instructions = 0 + while (cursor < delta.length) { + if ((instructions++ & 0xfff) === 0) work.check() + const instruction = next() + if (instruction & 0x80) { + let offset = 0, length = 0 + for (let i = 0; i < 4; i++) if (instruction & (1 << i)) offset += next() * 256 ** i + for (let i = 0; i < 3; i++) if (instruction & (0x10 << i)) length += next() * 256 ** i + length ||= 0x10000 + if (offset + length > base.bytes.length || written + length > resultSize) throw gitError('git_corrupt') + base.bytes.copy(bytes, written, offset, offset + length) + written += length + } else { + const length = instruction + if (!length || cursor + length > delta.length || written + length > resultSize) throw gitError('git_corrupt') + delta.copy(bytes, written, cursor, cursor + length) + cursor += length + written += length + } + } + if (written !== resultSize) throw gitError('git_corrupt') + return { type: base.type, bytes } +} diff --git a/apps/headless/src/git/refs.mjs b/apps/headless/src/git/refs.mjs new file mode 100644 index 00000000..be912305 --- /dev/null +++ b/apps/headless/src/git/refs.mjs @@ -0,0 +1,120 @@ +import { decodeUtf8 } from '../files/workspace-files-fd.mjs' +import { gitError } from './git-errors.mjs' +import { MAX_GIT_DEPTH, validRefName } from './repository-paths.mjs' + +const HEADS = 'refs/heads/' +const REMOTES = 'refs/remotes/' +const REPLACE = 'refs/replace/' +const MAX_REF_BYTES = 4096 +const MAX_PACKED_BYTES = 4 * 1024 * 1024 +const MAX_SHALLOW_BYTES = 2 * 1024 * 1024 +const MAX_REFS = 10_000 +const corrupt = () => { throw gitError('git_corrupt') } +const unsupported = () => { throw gitError('unsupported_git_layout') } + +function text(bytes) { + try { return decodeUtf8(bytes) } catch { corrupt() } +} +function stripFinalEol(s) { + return s.endsWith('\r\n') ? s.slice(0, -2) : s.endsWith('\n') ? s.slice(0, -1) : s +} +function oid(value) { + if (/^[0-9a-f]{64}$/iu.test(value)) unsupported() + if (!/^[0-9a-f]{40}$/iu.test(value) || /^0{40}$/u.test(value)) corrupt() + return value.toLowerCase() +} +function refValue(bytes) { + const value = stripFinalEol(text(bytes)) + if (!value.startsWith('ref: ')) return { oid: oid(value) } + const target = value.slice(5) + if (!target.startsWith('refs/') || !validRefName(target)) corrupt() + return { target } +} +function trackingRef(ref) { + return ref.startsWith(HEADS) || (ref.startsWith(REMOTES) && ref.slice(REMOTES.length).includes('/')) +} +function remoteAlias(ref) { + return ref.startsWith(REMOTES) && ref.endsWith('/HEAD') +} +function packedRefs(io) { + const bytes = io.readMeta('packed-refs', MAX_PACKED_BYTES) + const refs = new Map() + if (bytes === null || bytes.length === 0) return refs + let peelAllowed = false + const seen = new Set() + for (const line of stripFinalEol(text(bytes)).split(/\r?\n/u)) { + if (line.startsWith('#')) { peelAllowed = false; continue } + if (line.startsWith('^')) { + if (!peelAllowed) corrupt() + oid(line.slice(1)) + peelAllowed = false + continue + } + const gap = line.indexOf(' ') + if (gap < 0) corrupt() + const id = oid(line.slice(0, gap)) + const name = line.slice(gap + 1) + if (!name.startsWith('refs/') || !validRefName(name) || seen.has(name)) corrupt() + if (name.startsWith(REPLACE)) unsupported() + seen.add(name) + if (seen.size > MAX_REFS) throw gitError('git_limit') + if (trackingRef(name)) refs.set(name, id) + peelAllowed = true + } + return refs +} +function looseRefs(io, refs) { + let entriesVisited = 0 + function walk(dir, depth) { + const entries = io.listMeta(dir, MAX_REFS - entriesVisited) + entriesVisited += entries.length + for (const { name, type } of entries) { + const ref = `${dir}/${name}` + if (depth >= MAX_GIT_DEPTH) throw gitError('git_limit') + if (type === 'dir') { walk(ref, depth + 1); continue } + if (!validRefName(ref)) corrupt() + if (!trackingRef(ref)) unsupported() + const bytes = io.readMeta(ref, MAX_REF_BYTES) + if (bytes === null) throw gitError('git_stale') + const value = refValue(bytes) + if (value.target !== undefined) { + if (!remoteAlias(ref)) unsupported() + // A remote HEAD is an alias, not a tracking branch. Its loose value also + // shadows a stale packed record at the same ref name. + refs.delete(ref) + } else refs.set(ref, value.oid) + if (refs.size > MAX_REFS) throw gitError('git_limit') + } + } + walk(HEADS.slice(0, -1), 2) + walk(REMOTES.slice(0, -1), 2) +} +function shallowRefs(io) { + const bytes = io.readMeta('shallow', MAX_SHALLOW_BYTES) + if (bytes === null || bytes.length === 0) return new Set() + const lines = stripFinalEol(text(bytes)).split(/\r?\n/u) + if (lines.length > MAX_REFS) throw gitError('git_limit') + return new Set(lines.map(oid)) +} + +export function readGitRefs(io) { + if (io.state !== undefined && io.state !== 'ready') unsupported() + const headBytes = io.readMeta('HEAD', MAX_REF_BYTES) + if (headBytes === null) corrupt() + const value = refValue(headBytes) + if (value.target !== undefined && !value.target.startsWith(HEADS)) unsupported() + if (value.target?.split('/').length > MAX_GIT_DEPTH) throw gitError('git_limit') + const refs = packedRefs(io) + looseRefs(io, refs) + const detached = value.target === undefined + const branch = detached ? null : value.target.slice(HEADS.length) + const head = (detached ? value.oid : refs.get(value.target)) ?? null + const shallow = shallowRefs(io) + const branches = [...refs.keys()].sort().map(ref => { + const local = ref.startsWith(HEADS) + const name = ref.slice((local ? HEADS : REMOTES).length) + return { name, current: value.target === ref, remote: local ? null : name.slice(0, name.indexOf('/')) } + }) + return { branch, head, detached, unborn: !detached && head === null, mergeInProgress: io.marker('MERGE_HEAD'), branches, shallow, + limitations: shallow.size ? ['shallow'] : [] } +} diff --git a/apps/headless/src/git/repository-fd.mjs b/apps/headless/src/git/repository-fd.mjs new file mode 100644 index 00000000..17e717f4 --- /dev/null +++ b/apps/headless/src/git/repository-fd.mjs @@ -0,0 +1,193 @@ +import { constants as C, openSync, opendirSync, readSync } from 'node:fs' +import { DIRECTORY, PATH, close, decodeUtf8, fdPath, mountId, sameInode, stat } from '../files/workspace-files-fd.mjs' +import { access, regular } from '../files/workspace-files-pin.mjs' +import { gitError } from './git-errors.mjs' + +const MAX_BYTES = 64 * 1024 * 1024 +const MAX_NODES = 30_000 +const fail = code => { throw gitError(code) } + +// Do not include atime (these reads can update it) or birthtime (old Linux can +// synthesize it from ctime). Inodes identify mounts/entries; the rest fences revisions. +function sameVersion(a, b) { + return sameInode(a, b) && a.size === b.size && a.ctimeNs === b.ctimeNs && a.mtimeNs === b.mtimeNs && + a.mode === b.mode && a.nlink === b.nlink && a.uid === b.uid && a.gid === b.gid +} +function fdVersion(fd) { + const info = stat(fd) + const mount = mountId(fd) + if (!sameVersion(info, stat(fd))) fail('git_stale') + return { info, mount } +} +function current(expected, actual) { + if (expected === undefined || actual === undefined) return expected === actual + return expected.mount === actual.mount && sameVersion(expected.info, actual.info) +} +function assertCurrent(expected, actual) { + if (!current(expected, actual)) fail('git_stale') +} +function nativeFailure(error) { + if (typeof error?.code === 'string' && (error.code.startsWith('git_') || error.code === 'unsupported_git_layout')) throw error + if (['EBADF', 'ENOENT', 'ESTALE'].includes(error?.code)) fail('git_stale') + if (['EMFILE', 'ENFILE', 'ENOMEM'].includes(error?.code)) fail('git_limit') + fail('git_unsafe') +} + +function peek(parent, name) { + let fd + try { + try { fd = openSync(fdPath(parent, name), PATH) } catch (error) { + if (error?.code === 'ENOENT') return { fd: undefined, version: undefined } + nativeFailure(error) + } + return { fd, version: fdVersion(fd) } + } catch (error) { + close(fd) + nativeFailure(error) + } +} +function search(fd, version, expectedMount) { + if (version.mount !== expectedMount || !version.info.isDirectory() || !access(fd, version.info, C.X_OK)) fail('git_unsafe') +} +export function boundedInteger(value) { + if (!Number.isSafeInteger(value) || value < 0) fail('git_limit') + return value +} + +export function pinGitRoot(source, expectedMount) { + if (process.platform !== 'linux') fail('unsupported_git_layout') + if (!Number.isSafeInteger(source) || source < 0 || !['string', 'number'].includes(typeof expectedMount) || + !/^\d+$/u.test(String(expectedMount))) fail('git_stale') + expectedMount = String(expectedMount) + let root, baseline + try { + baseline = fdVersion(source) + if (baseline.mount !== expectedMount) fail('git_stale') + search(source, baseline, expectedMount) + // Each worker owns this descriptor only. The service keeps `source` pinned. + root = openSync(fdPath(source, '.'), DIRECTORY) + assertCurrent(baseline, fdVersion(root)) + assertCurrent(baseline, fdVersion(source)) + } catch (error) { + close(root) + nativeFailure(error) + } + + let nodes = 0 + let bytes = 0 + const observed = { version: baseline, children: new Map() } + function chargeNode() { + if (++nodes > MAX_NODES) fail('git_limit') + } + function checkRoot() { + if (root === undefined) fail('git_stale') + try { + assertCurrent(baseline, fdVersion(source)) + assertCurrent(baseline, fdVersion(root)) + } catch { fail('git_stale') } + } + function namedVersion(parent, name, expected) { + try { + const { fd, version } = peek(parent, name) + try { assertCurrent(expected, version) } finally { close(fd) } + } catch { fail('git_stale') } + } + function descend(parent, record, parts, index, fn) { + if (index === parts.length) return fn(parent, record.version) + search(parent, record.version, expectedMount) + const name = parts[index] + chargeNode() + const previous = record.children.get(name) + let inspect + try { inspect = peek(parent, name) } catch (error) { + if (previous !== undefined && error.code !== 'git_limit') fail('git_stale') + throw error + } + const { fd, version } = inspect + try { + if (previous !== undefined) assertCurrent(previous.version, version) + const child = previous ?? { version, children: new Map() } + if (previous === undefined) record.children.set(name, child) + const answer = fd === undefined ? fn(undefined, undefined) : descend(fd, child, parts, index + 1, fn) + // Check both the descriptor and the named slot (a bind mount can change the latter + // without touching parent-directory timestamps). + if (fd !== undefined) assertCurrent(version, fdVersion(fd)) + namedVersion(parent, name, version) + assertCurrent(record.version, fdVersion(parent)) + return answer + } finally { close(fd) } + } + function path(parts, fn) { + checkRoot() + let result + try { result = descend(root, observed, parts, 0, fn) } catch (error) { nativeFailure(error) } + checkRoot() + return result + } + function verifyChildren(fd, record) { + if (record.children.size) search(fd, record.version, expectedMount) + for (const [name, child] of record.children) { + const next = peek(fd, name) + try { + assertCurrent(child.version, next.version) + if (next.fd !== undefined) verifyChildren(next.fd, child) + } finally { close(next.fd) } + } + assertCurrent(record.version, fdVersion(fd)) + } + return { + path, + read(pin, version, limit) { + const { info } = version + if (version.mount !== expectedMount || !regular(info) || !access(pin, info, C.R_OK)) fail('git_unsafe') + if (info.size > BigInt(limit)) return undefined + const size = Number(info.size) + if (size > MAX_BYTES - bytes) fail('git_limit') + bytes += size + let reader + try { + // The only followed link is the kernel's procfd link for the inspected ordinary inode. + reader = openSync(fdPath(pin), C.O_RDONLY | C.O_NONBLOCK) + assertCurrent(version, fdVersion(reader)) + const result = Buffer.allocUnsafe(size) + for (let pos = 0; pos < size;) { + const count = readSync(reader, result, pos, size - pos, pos) + if (count === 0) fail('git_stale') + pos += count + } + assertCurrent(version, fdVersion(reader)) + return result + } finally { close(reader) } + }, + list(dir, version, visit) { + search(dir, version, expectedMount) + if (!access(dir, version.info, C.R_OK | C.X_OK)) fail('git_unsafe') + const scan = opendirSync(fdPath(dir, '.'), { encoding: 'buffer' }) + try { + for (let entry; (entry = scan.readSync()) !== null;) { + chargeNode() + let name + try { name = decodeUtf8(entry.name) } catch { continue } + if (visit(name) === false) break + } + } finally { scan.closeSync() } + }, + entryType(version) { + if (version.mount !== expectedMount) fail('git_unsafe') + if (version.info.isDirectory()) return 'dir' + if (regular(version.info)) return 'file' + fail('git_unsafe') + }, + verify() { + checkRoot() + try { verifyChildren(root, observed) } catch { fail('git_stale') } + checkRoot() + }, + close() { + if (root === undefined) return + const fd = root + root = undefined + close(fd) + }, + } +} diff --git a/apps/headless/src/git/repository-paths.mjs b/apps/headless/src/git/repository-paths.mjs new file mode 100644 index 00000000..0eaa3263 --- /dev/null +++ b/apps/headless/src/git/repository-paths.mjs @@ -0,0 +1,62 @@ +import { validWorkspaceName, workspacePathParts } from '../files/workspace-files-fd.mjs' + +export const MAX_GIT_DEPTH = 16 +const META = new Set(['HEAD', 'packed-refs', 'index', 'shallow', 'MERGE_HEAD']) +export const layoutMarkers = [ + 'commondir', 'gitdir', 'reftable', 'objects/info/alternates', 'objects/info/http-alternates', + 'info/grafts', 'refs/replace', +] +const markerPaths = new Set([...META, ...layoutMarkers]) +const hex2 = /^[0-9a-f]{2}$/u +const hex38 = /^[0-9a-f]{38}$/u +const packSHA1 = /^pack-[0-9a-f]{40}\.(?:pack|idx)$/u +export const unsupportedPack = /^pack-(?:[0-9a-f]{40}\.promisor|[0-9a-f]{64}\.(?:pack|idx|promisor))$/u + +export function validRefComponent(name) { + return validWorkspaceName(name) && !name.endsWith('.lock') && !name.includes('..') && !name.includes('@{') && + !/[ ~^:?*\[\p{Cf}\p{Zl}\p{Zp}]/u.test(name) +} +export function validRefName(ref) { + if (typeof ref !== 'string' || ref.length > 4095 || Buffer.byteLength(ref) > 4095 || ref.endsWith('.')) return false + const parts = ref.split('/') + return parts.length > 1 && parts.every(validRefComponent) +} + +function refTree(parts) { + return parts[0] === 'refs' && (parts[1] === 'heads' || parts[1] === 'remotes') && + parts.slice(2).every(validRefComponent) +} + +export function metadataPath(rel, mode) { + if (typeof rel !== 'string' || rel.length > 4095 || Buffer.byteLength(rel) > 4095) return null + const parts = rel.split('/') + if (mode === 'marker') { + return markerPaths.has(rel) || (parts.length === 3 && parts[0] === 'objects' && parts[1] === 'pack' && unsupportedPack.test(parts[2])) ? parts : null + } + if (parts.length > MAX_GIT_DEPTH) return null + if (mode === 'read') { + if (META.has(rel) || (parts.length >= 3 && refTree(parts) && validRefName(rel))) return parts + if (parts.length === 3 && parts[0] === 'objects' && + ((hex2.test(parts[1]) && hex38.test(parts[2])) || (parts[1] === 'pack' && packSHA1.test(parts[2])))) return parts + } else if (refTree(parts) || (parts[0] === 'objects' && + (parts.length === 1 || (parts.length === 2 && (parts[1] === 'pack' || hex2.test(parts[1])))))) return parts + return null +} + +export function listMetaType(parts, name) { + if (parts[0] === 'refs') return validRefComponent(name) ? 'either' : undefined + if (parts.length === 1) return hex2.test(name) || name === 'pack' ? 'dir' : undefined + return (parts[1] === 'pack' ? packSHA1.test(name) : hex38.test(name)) ? 'file' : undefined +} + +const sensitiveName = /(?:^|[._ -])(?:env|credentials?|secrets?|passwords?|private[-_ ]?keys?|api[-_ ]?keys?|(?:access[-_ ]?|refresh[-_ ]?)?tokens?|id[-_](?:rsa|dsa|ecdsa|ed25519)|known_hosts|authorized_keys|passwd|shadow|htpasswd|kubeconfig|keyrings?|keystores?|netrc|npmrc|pypirc|auth\.json)(?:[._ -]|$)|\.(?:pem|key|p12|pfx|pkcs12|kdbx|jks|keystore|ovpn|ppk)(?:\.|$)/iu +export function workPath(rel) { + const parts = workspacePathParts(rel) + if (!parts || parts.some(name => sensitiveName.test(name) || /[\p{Cf}\p{Zl}\p{Zp}]/u.test(name))) return null + return parts +} + +export function sensitiveBytes(bytes) { + // Check the bounded payload, including keys embedded below a comment or JSON prefix. + return /(? version) + if (!git) return 'not_repo' + if (!git.info.isDirectory()) return 'unsupported_layout' + if (git.mount !== String(mount)) throw gitError('git_unsafe') + for (const rel of layoutMarkers) { + if (scope.path(['.git', ...rel.split('/')], fd => fd !== undefined)) return 'unsupported_layout' + } + // Promisor and SHA-256 pack sidecars/names are classified by existence only. + // No pointer file, sidecar or repository configuration is ever opened for data. + const unsupported = scope.path(['.git', 'objects', 'pack'], (fd, version) => { + if (fd === undefined) return false + let found = false + scope.list(fd, version, name => { + if (unsupportedPack.test(name)) { found = true; return false } + }) + return found + }) + return unsupported ? 'unsupported_layout' : 'ready' +} + +/** Open a synchronous, request-scoped view of an operator-approved Linux directory FD. */ +export function openGitIo({ fd, mount } = {}) { + const scope = pinGitRoot(fd, mount) + let state + try { state = detectLayout(scope, mount) } catch (error) { scope.close(); throw error } + + function meta(rel, mode) { + if (typeof rel === 'string' && rel.length <= 4095 && rel.split('/', MAX_GIT_DEPTH + 1).length > MAX_GIT_DEPTH) { + throw gitError('git_limit') + } + const parts = metadataPath(rel, mode) + if (!parts) throw gitError('git_unsafe') + return ['.git', ...parts] + } + function requireReady() { + if (state !== 'ready') throw gitError('unsupported_git_layout') + } + return Object.freeze({ + state, + readMeta(rel, maxBytes) { + const parts = meta(rel, 'read') + const limit = boundedInteger(maxBytes) + requireReady() + return scope.path(parts, (pin, version) => { + if (pin === undefined) return null + const bytes = scope.read(pin, version, limit) + if (bytes === undefined) throw gitError('git_limit') + return bytes + }) + }, + listMeta(rel, maxEntries) { + const parts = meta(rel, 'list') + const limit = boundedInteger(maxEntries) + requireReady() + const relParts = parts.slice(1) + const names = scope.path(parts, (dir, version) => { + if (dir === undefined) return [] + const matched = [] + scope.list(dir, version, name => { + const expected = listMetaType(relParts, name) + if (expected === undefined) return + if (relParts.length === MAX_GIT_DEPTH || matched.length >= limit) throw gitError('git_limit') + matched.push({ name, expected }) + }) + return matched + }) + return names.map(({ name, expected }) => scope.path([...parts, name], (pin, version) => { + if (pin === undefined) throw gitError('git_stale') + const type = scope.entryType(version) + if (expected !== 'either' && type !== expected) throw gitError('git_unsafe') + return { name, type } + })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) + }, + marker(rel) { + const parts = meta(rel, 'marker') + return scope.path(parts, pin => pin !== undefined) + }, + workFile(rel, maxBytes) { + const parts = workPath(rel) + if (!parts) return UNSAFE + const limit = boundedInteger(maxBytes) + try { + return scope.path(parts, (pin, version) => { + if (pin === undefined) return ABSENT + const bytes = scope.read(pin, version, limit) + if (bytes === undefined) return TOO_LARGE + if (sensitiveBytes(bytes)) return UNSAFE + return { state: 'regular', bytes, executable: Boolean(version.info.mode & 0o100n) } + }) + } catch (error) { + if (error?.code === 'git_unsafe') return UNSAFE + throw error + } + }, + verify: scope.verify, + close: scope.close, + }) +} diff --git a/apps/headless/src/git/routes.mjs b/apps/headless/src/git/routes.mjs new file mode 100644 index 00000000..6e8f73ce --- /dev/null +++ b/apps/headless/src/git/routes.mjs @@ -0,0 +1,37 @@ +import { HttpError, json, readJson } from '../http/policy.mjs' + +const pathPattern = /^\/api\/v1\/workspaces\/(w_[0-9a-f]{32})\/git\/(available|status|branches|log|diff)$/u + +/** The HTTP surface is five fixed manual reads. The server, not the browser or a model, + * binds a selected workspace and maps a short-lived entry ID to a diff comparison. */ +export function gitViewRoutes(service) { + let reading = 0 + return async function handle(req, res, {auth, policy}) { + const raw = req.url ?? '', path = raw.split('?',1)[0], match = pathPattern.exec(path) + if (!match || match[0] !== path) return false + let reserved = false + const abort = new AbortController() + const disconnect = () => { if (!res.writableEnded) abort.abort() } + try { + policy.check(req, true) + if (path !== raw) throw new HttpError(400, 'unexpected_query') + if (req.method !== 'POST') { json(res,405,{error:'method'},{allow:'POST',connection:'close'}); return true } + const cookie = policy.cookie(req), identify = () => auth.identify(cookie, req.headers['x-deva-csrf']) + const actor = identify() + if (!service) throw new HttpError(403, 'git_not_granted') + if (reading >= 8) throw new HttpError(409, 'git_busy') + reading++; reserved=true; res.once('close', disconnect) + const body = await readJson(req, 1024) + identify() + if (res.destroyed) return true + const result = await service.inspect(actor,match[1],match[2],body,abort.signal) + identify() + if (!res.destroyed) json(res,200,result) + } catch (error) { + const [status,code] = error instanceof HttpError ? [error.status,error.code] : error?.code === 'AUTH_FAILED' ? [401,'auth'] : + error?.code === 'ERR_WORKSPACE_UNAVAILABLE' ? [404,'workspace_unavailable'] : [503,'git_unavailable'] + if (!res.headersSent && !res.destroyed) json(res,status,{error:code},{connection:'close'}) + } finally { if (reserved) reading--; res.off('close', disconnect) } + return true + } +} diff --git a/apps/headless/src/git/runner.mjs b/apps/headless/src/git/runner.mjs new file mode 100644 index 00000000..6101e63b --- /dev/null +++ b/apps/headless/src/git/runner.mjs @@ -0,0 +1,45 @@ +import { Worker } from 'node:worker_threads' +import { HttpError } from '../http/policy.mjs' + +const file = new URL('./inspect-worker.mjs', import.meta.url) +const codes = new Map([ + ['git_stale',409], ['git_limit',413], ['git_unsafe',403], ['git_corrupt',422], + ['git_object_unavailable',422], ['unsupported_git_layout',422], ['git_timeout',503], ['git_unavailable',503] +]) +export function gitFault(code) { return new HttpError(codes.get(code) ?? 503, codes.has(code) ? code : 'git_unavailable') } + +/** The directory lease remains held by the caller until the Worker has actually exited. + * No caller-provided code/filename/argv/env/URL is passed to a worker. */ +export function inspectInWorker(pin, job, signal) { + if (signal.aborted) return Promise.reject(gitFault('git_unavailable')) + return new Promise((resolve, reject) => { + let worker + try { + worker = new Worker(file, { workerData: { fd: pin.fd, mount: String(pin.mount), job }, + execArgv: [], env: {}, trackUnmanagedFds: true, stdout: true, stderr: true, + resourceLimits: { maxOldGenerationSizeMb: 96, maxYoungGenerationSizeMb: 16, stackSizeMb: 4 } }) + } catch { reject(gitFault('git_unavailable')); return } + worker.stdout.resume(); worker.stderr.resume() + let outcome, failure, terminating = false + function terminate(code) { + failure ??= code + if (!terminating) { terminating = true; void worker.terminate().catch(() => {}) } + } + const abort = () => terminate('git_unavailable') + const timer = setTimeout(() => terminate('git_timeout'), 6000); timer.unref() + signal.addEventListener('abort', abort, { once: true }) + worker.on('message', result => { + if (outcome || !result || typeof result.ok !== 'boolean') { terminate('git_unavailable'); return } + outcome = result + }) + worker.once('messageerror', () => terminate('git_unavailable')) + worker.once('error', () => terminate('git_unavailable')) + worker.once('exit', code => { + clearTimeout(timer); signal.removeEventListener('abort', abort) + if (signal.aborted || failure || code !== 0 || !outcome) { reject(gitFault(failure ?? 'git_unavailable')); return } + if (!outcome.ok) reject(gitFault(outcome.error)) + else resolve(outcome.result) + }) + if (signal.aborted) abort() + }) +} diff --git a/apps/headless/src/git/service.mjs b/apps/headless/src/git/service.mjs new file mode 100644 index 00000000..8489d715 --- /dev/null +++ b/apps/headless/src/git/service.mjs @@ -0,0 +1,168 @@ +import { randomBytes } from 'node:crypto' +import { performance } from 'node:perf_hooks' +import { HttpError } from '../http/policy.mjs' +import { inspectInWorker, gitFault } from './runner.mjs' + +const opaque = prefix => prefix + randomBytes(16).toString('hex') +const viewTag = /^v_[a-f0-9]{32}$/u, entryTag = /^e_[a-f0-9]{32}$/u +const states = new Set(['ready','partial','unavailable','not_repo','unsupported_layout']) +const diffStates = new Set(['ready','binary','too_large','unavailable']) +const sides = new Set(['staged','worktree']), letters = new Set([null,'A','D','M','T','U']) +const typ = new Set(['ctx','add','del','hunk']) +const exact = (s, re) => typeof s === 'string' && re.exec(s)?.[0] === s +const bad = () => { throw new HttpError(400, 'invalid_git_request') } +const unavailable = () => { throw gitFault('git_unavailable') } +const stale = () => { throw gitFault('git_stale') } +function fields(value, keys) { + if (!value || typeof value !== 'object' || Array.isArray(value) || keys.length !== Object.keys(value).length || !keys.every(k => Object.hasOwn(value,k))) bad() +} +function parseJob(op, body) { + if (['status','branches','available'].includes(op)) { fields(body, []); return { op } } + if (op === 'log') { + fields(body, ['limit']) + if (!Number.isInteger(body.limit) || body.limit < 1 || body.limit > 100) bad() + return { op, limit: body.limit } + } + if (op !== 'diff') bad() + fields(body, ['viewId','entryId','side']) + if (!exact(body.viewId, viewTag) || !exact(body.entryId, entryTag) || !sides.has(body.side)) bad() + return { op, viewId: body.viewId, entryId: body.entryId, side: body.side } +} +function limits(value) { + if (!Array.isArray(value) || value.length > 32 || !value.every(s => exact(s, /^[a-z0-9_]{1,64}$/u))) unavailable() + return value +} +function plainRel(rel) { + return typeof rel === 'string' && rel.length > 0 && Buffer.byteLength(rel) <= 4095 && + !/[\\\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(rel) && rel.split('/').every(p => p && !p.startsWith('.') && !/^[a-z]:/i.test(p)) +} +function common(value) { + if (!value || !states.has(value.state) || (value.branch !== null && typeof value.branch !== 'string')) unavailable() + return { state: value.state, branch: value.branch, limitations: limits(value.limitations) } +} +function head(value) { + if (typeof value.detached !== 'boolean' || typeof value.unborn !== 'boolean') unavailable() + return { detached: value.detached, unborn: value.unborn } +} +function branches(value) { + const base = common(value) + if (!Array.isArray(value.branches) || value.branches.length > 2000) unavailable() + return { ...base, ...head(value), branches: value.branches.map(({name,current,remote}) => { + if (typeof name !== 'string' || typeof current !== 'boolean' || (remote !== null && typeof remote !== 'string')) unavailable() + return {name,current,remote} + }) } +} +function history(value, cap) { + const base = common(value) + if (value.traversal !== 'first-parent' || typeof value.more !== 'boolean' || !Array.isArray(value.commits) || value.commits.length > cap) unavailable() + return { ...base, traversal: 'first-parent', more: value.more, commits: value.commits.map(({oid,short,author,subject,timestamp}) => { + if (!exact(oid,/^[a-f0-9]{40}$/u) || !exact(short,/^[a-f0-9]{4,40}$/u) || !oid.startsWith(short) || + typeof author !== 'string' || typeof subject !== 'string' || !Number.isSafeInteger(timestamp)) unavailable() + return {oid,short,author,subject,timestamp} + }) } +} +function difference(value, rel, side) { + if (value.rel !== rel || value.side !== side || !diffStates.has(value.state) || !Array.isArray(value.lines) || + value.lines.length > 1000 || typeof value.truncated !== 'boolean') unavailable() + return { state: value.state, rel, side, limitations: limits(value.limitations), truncated: value.truncated, + lines: value.lines.map(({type,oldNo,newNo,text}) => { + if (!typ.has(type) || typeof text !== 'string' || [oldNo,newNo].some(n => n !== undefined && (!Number.isSafeInteger(n) || n < 0))) unavailable() + return { type, ...(oldNo === undefined ? {} : {oldNo}), ...(newNo === undefined ? {} : {newNo}), text } + }) } +} + +/** Read-only explicit operator grants. Status snapshots retain only relative entry names and + * comparison sides (not diff contents). The unguessable IDs are not credentials. */ +export function openGitService({ grants, auth, now = () => performance.now(), run = inspectInWorker }) { + const views = new Map(), active = new Map(), tasks = new Set() + const maxViews = 24, ttl = 60_000 + let closing = false, closeJob + function clearLogin(id) { + for (const [key, view] of views) if (view.login === id) views.delete(key) + for (const context of active.values()) if (context.login === id) context.abort.abort() + } + const unsubscribe = auth.onSessionRevoked(clearLogin) + function checkActor(actor) { + if (closing) unavailable() + if (!auth.isLoginActive(actor)) throw new HttpError(401, 'auth') + } + function trim() { + const time = now() + for (const [key, view] of views) if (view.until <= time) views.delete(key) + } + function recall(actor, workspace, request) { + trim() + const view = views.get(request.viewId), row = view?.rows.get(request.entryId) + if (!view || view.workspace !== workspace || view.login !== actor.loginSessionId || view.owner !== actor.ownerId || + !row?.diffSides.includes(request.side)) stale() + return { view, row } + } + function status(value, actor, workspace) { + const base = { ...common(value), ...head(value) } + if (typeof value.mergeInProgress !== 'boolean' || !Array.isArray(value.entries) || value.entries.length > 2000 || + !exact(value.fingerprint, /^[a-f0-9]{64}$/u)) unavailable() + const rows = new Map(), paths = new Set() + const entries = value.entries.map(({rel,staged,worktree,conflicted,diffSides}) => { + if (!plainRel(rel) || paths.has(rel) || !letters.has(staged) || !letters.has(worktree) || typeof conflicted !== 'boolean' || + !Array.isArray(diffSides) || diffSides.length > 2 || !diffSides.every(s => sides.has(s)) || new Set(diffSides).size !== diffSides.length) unavailable() + paths.add(rel) + const entryId = opaque('e_') + rows.set(entryId, {rel,diffSides}) + return {entryId,rel,staged,worktree,conflicted,diffSides} + }) + let viewId = null + if (['ready','partial'].includes(base.state) && entries.some(row => row.diffSides.length)) { + trim() + // Each new explicit status supersedes this login's earlier view of the same workspace. + for (const [key, v] of views) if (v.login === actor.loginSessionId && v.workspace === workspace) views.delete(key) + if (views.size >= maxViews) views.delete(views.keys().next().value) + viewId = opaque('v_') + views.set(viewId,{login:actor.loginSessionId,owner:actor.ownerId,workspace,rows,expected:value.fingerprint,until:now()+ttl}) + } else { + for (const [key, v] of views) if (v.login === actor.loginSessionId && v.workspace === workspace) views.delete(key) + } + return { ...base, workspaceId: workspace, viewId, entries, mergeInProgress: value.mergeInProgress } + } + async function execute(actor, wid, op, body, signal) { + const request = parseJob(op, body) + checkActor(actor); trim() + if (!grants.enabled) throw new HttpError(403, 'git_not_granted') + const before = op === 'diff' ? recall(actor, wid, request) : null + if (active.size >= 2 || active.has(wid)) throw new HttpError(409, 'git_busy') + const pin = grants.pin(wid), abort = new AbortController() + const cancel = () => abort.abort() + active.set(wid, {login:actor.loginSessionId,abort}); signal?.addEventListener('abort',cancel,{once:true}) + try { + if (signal?.aborted) cancel() + if (abort.signal.aborted) unavailable() + pin.assertCurrent() + if (op === 'available') return {available:true,mode:'read-only',workspaceId:wid} + const job = before ? { op:'diff', rel:before.row.rel, side:request.side, expectedFingerprint:before.view.expected } : request + const result = await run(pin, job, abort.signal) + checkActor(actor) + if (abort.signal.aborted) unavailable() + pin.assertCurrent() + if (op === 'status') return status(result, actor, wid) + if (op === 'branches') return branches(result) + if (op === 'log') return history(result, request.limit) + const { view, row } = recall(actor, wid, request) + if (view !== before.view || row !== before.row) stale() + return difference(result,row.rel,request.side) + } finally { signal?.removeEventListener('abort',cancel); active.delete(wid); pin.close() } + } + return Object.freeze({ + inspect(actor, wid, op, body, signal) { + const task = execute(actor,wid,op,body,signal) + tasks.add(task); const done = () => tasks.delete(task); void task.then(done,done) + return task + }, + close() { + if (!closeJob) { + closing=true; unsubscribe(); views.clear() + for (const context of active.values()) context.abort.abort() + closeJob=Promise.allSettled([...tasks]).then(()=>{}) + } + return closeJob + } + }) +} diff --git a/apps/headless/src/http/session-routes.mjs b/apps/headless/src/http/session-routes.mjs index b4d2a655..121438d3 100644 --- a/apps/headless/src/http/session-routes.mjs +++ b/apps/headless/src/http/session-routes.mjs @@ -50,7 +50,7 @@ export function sessionRoutes({ auth, policy, version, getConfig, capabilities } capabilities: { textChat: capabilities?.textChat === true, library: capabilities?.library === true, workspaceFiles: capabilities?.workspaceFiles === true, attachments: capabilities?.attachments === true, browserPanel: capabilities?.browserPanel === true, sessionPreferences: capabilities?.sessionPreferences === true, - deliveries: capabilities?.deliveries === true } }) + deliveries: capabilities?.deliveries === true, gitInspect: capabilities?.gitInspect === true } }) return true } if (path === '/api/v1/auth/logout') { diff --git a/apps/headless/test/git-inspect.test.mjs b/apps/headless/test/git-inspect.test.mjs new file mode 100644 index 00000000..8299d7dc --- /dev/null +++ b/apps/headless/test/git-inspect.test.mjs @@ -0,0 +1,428 @@ +import assert from 'node:assert/strict' +import { createHash } from 'node:crypto' +import test from 'node:test' +import { crc32, deflateSync } from 'node:zlib' +import { inspectGit } from '../src/git/inspect.mjs' + +const REG = 0o100644, EXEC = 0o100755, LINK = 0o120000, SUBMODULE = 0o160000 +const SHA = value => createHash('sha1').update(value).digest() +const objectPath = oid => `objects/${oid.slice(0, 2)}/${oid.slice(2)}` +const when = 1712345678 + +function realIndex(items, { version = 2, extensions = [] } = {}) { + const sorted = [...items].sort((a, b) => Buffer.compare(Buffer.from(a.path), Buffer.from(b.path)) || (a.stage ?? 0) - (b.stage ?? 0)) + const header = Buffer.alloc(12) + header.write('DIRC') + header.writeUInt32BE(version, 4) + header.writeUInt32BE(items.length, 8) + const entries = sorted.map(({ path, oid, mode = REG, stage = 0, extended }) => { + const raw = Buffer.from(path), prefix = extended === undefined ? 62 : 64 + const bytes = Buffer.alloc(Math.ceil((prefix + raw.length + 1) / 8) * 8) + bytes.writeUInt32BE(mode, 24) + Buffer.from(oid, 'hex').copy(bytes, 40) + bytes.writeUInt16BE(Math.min(raw.length, 0xfff) | (stage << 12) | (extended === undefined ? 0 : 0x4000), 60) + if (extended !== undefined) bytes.writeUInt16BE(extended, 62) + raw.copy(bytes, prefix) + return bytes + }) + const extra = extensions.map(([signature, body]) => { + const header = Buffer.alloc(8) + header.write(signature) + header.writeUInt32BE(body.length, 4) + return Buffer.concat([header, body]) + }) + const bytes = Buffer.concat([header, ...entries, ...extra]) + return Buffer.concat([bytes, SHA(bytes)]) +} + +function realPack(objects) { + const header = Buffer.alloc(12) + header.write('PACK') + header.writeUInt32BE(2, 4) + header.writeUInt32BE(objects.size, 8) + let offset = header.length + const values = { commit: 1, tree: 2, blob: 3 } + const indexRows = [] + const entries = [] + for (const [oid, { type, bytes }] of objects) { + let remaining = bytes.length >>> 4 + const descriptor = [(values[type] << 4) | (bytes.length & 15) | (remaining ? 128 : 0)] + while (remaining) { + const part = remaining & 127 + remaining >>>= 7 + descriptor.push(part | (remaining ? 128 : 0)) + } + const packed = Buffer.concat([Buffer.from(descriptor), deflateSync(bytes)]) + entries.push(packed) + indexRows.push({ oid: Buffer.from(oid, 'hex'), offset, crc: crc32(packed) }) + offset += packed.length + } + const packData = Buffer.concat([header, ...entries]) + const key = SHA(packData) + const idx = Buffer.alloc(1032 + 28 * indexRows.length) + idx.writeUInt32BE(0xff744f63) + idx.writeUInt32BE(2, 4) + indexRows.sort((a, b) => Buffer.compare(a.oid, b.oid)) + let found = 0 + for (let byte = 0; byte < 256; byte++) { + while (found < indexRows.length && indexRows[found].oid[0] <= byte) found++ + idx.writeUInt32BE(found, 8 + byte * 4) + } + for (const [at, { oid, crc, offset }] of indexRows.entries()) { + oid.copy(idx, 1032 + at * 20) + idx.writeUInt32BE(crc, 1032 + indexRows.length * 20 + 4 * at) + idx.writeUInt32BE(offset, 1032 + indexRows.length * 24 + 4 * at) + } + const idxData = Buffer.concat([idx, key]) + return { + filename: `objects/pack/pack-${key.toString('hex')}`, + pack: Buffer.concat([packData, key]), + idx: Buffer.concat([idxData, SHA(idxData)]), + } +} + +function repo() { + const meta = new Map([['HEAD', Buffer.from('ref: refs/heads/main\n')]]) + const work = new Map(), workReads = [], metaReads = [], objects = new Map() + const io = { + state: 'ready', + readMeta(path, limit) { + metaReads.push(path) + if (path === 'config' || path === 'config.worktree' || path.includes('hooks/')) assert.fail(`unexpected read: ${path}`) + const bytes = meta.get(path) ?? null + if (bytes && bytes.length > limit) throw Object.assign(Error('git_limit'), { code: 'git_limit' }) + return bytes + }, + listMeta(path, max) { + const entries = new Map() + for (const key of meta.keys()) { + if (!key.startsWith(`${path}/`)) continue + const [name, ...rest] = key.slice(path.length + 1).split('/') + entries.set(name, { name, type: rest.length ? 'dir' : 'file' }) + } + if (entries.size > max) throw Object.assign(Error('git_limit'), { code: 'git_limit' }) + return [...entries.values()] + }, + marker(path) { return meta.has(path) }, + workFile(path, max) { + workReads.push(path) + const value = work.get(path) ?? { state: 'missing' } + if (value.state === 'regular' && value.bytes.length > max) return { state: 'too_large' } + return value + }, + } + function object(type, data) { + const bytes = Buffer.from(data) + const raw = Buffer.concat([Buffer.from(`${type} ${bytes.length}\0`), bytes]) + const oid = SHA(raw).toString('hex') + objects.set(oid, { type, bytes }) + meta.set(objectPath(oid), deflateSync(raw)) + return oid + } + return { + io, meta, work, workReads, metaReads, + blob: value => object('blob', value), + tree(entries) { + const rows = [...entries].sort((a, b) => Buffer.compare(Buffer.from(a.path), Buffer.from(b.path))) + return object('tree', Buffer.concat(rows.flatMap(({ path, oid, mode = REG }) => [ + Buffer.from(`${mode.toString(8)} `), Buffer.from(path), Buffer.from([0]), Buffer.from(oid, 'hex'), + ]))) + }, + commit(tree, { parents = [], message = 'Subject\n\nUnreviewed body', author = 'Ada Test', timestamp = when } = {}) { + return object('commit', `tree ${tree}\n${parents.map(oid => `parent ${oid}\n`).join('')}author ${author} ${timestamp} +0530\ncommitter Hidden Person ${timestamp + 1} +0000\n\n${message}\n`) + }, + index(items, options) { meta.set('index', realIndex(items, options)) }, + setWork(path, bytes, executable = false) { work.set(path, { state: 'regular', bytes: Buffer.from(bytes), executable }) }, + head(oid) { meta.set('refs/heads/main', Buffer.from(`${oid}\n`)) }, + remove(oid) { meta.delete(objectPath(oid)) }, + pack() { + const { filename, pack, idx } = realPack(objects) + for (const oid of objects.keys()) meta.delete(objectPath(oid)) + meta.set(`${filename}.idx`, idx) + meta.set(`${filename}.pack`, pack) + }, + } +} + +function status(repo) { return inspectGit(repo.io, { op: 'status' }) } +function diff(repo, view, rel, side) { + return inspectGit(repo.io, { op: 'diff', expectedFingerprint: view.fingerprint, rel, side }) +} +function changedText(result) { + return result.lines.filter(row => row.type === 'del' || row.type === 'add').map(row => [row.type, row.text]) +} + +function basic(old, staged = old, working = staged) { + const fixture = repo() + const base = fixture.blob(old), next = fixture.blob(staged) + const tree = fixture.tree([{ path: 'readme.txt', oid: base }]) + const head = fixture.commit(tree) + fixture.head(head) + fixture.index([{ path: 'readme.txt', oid: next }]) + fixture.setWork('readme.txt', working) + return { fixture, head, tree, base, next } +} + +test('real SHA-1 status distinguishes staged and raw worktree changes, mode, add and deletes', () => { + const r = repo() + const prior = r.blob('lead\nold\nend\n'), next = r.blob('lead\nstaged\nend\n'), other = r.blob('same\n') + const empty = r.blob(''), sym = r.blob('/private-target'), newer = r.blob('regular\n') + const path = (path, oid, mode) => ({ path, oid, mode }) + const head = r.commit(r.tree([path('readme.txt', prior), path('staged-deleted.txt', other), path('removed.txt', other), + path('mode.sh', other), path('type-change', sym, LINK), path('hidden-link', sym, LINK), path('hidden-submodule', prior, SUBMODULE), + path('.gitignore', other), path('config', r.tree([path('apiKeys.json', other)]), 0o040000), + path(Buffer.from([0x80, 0xff]), other)])) + r.head(head) + r.index([path('readme.txt', next), path('removed.txt', other), path('mode.sh', other), path('type-change', newer), + path('hidden-link', sym, LINK), path('hidden-submodule', prior, SUBMODULE), path('.gitignore', other), + path('config/apiKeys.json', other), path(Buffer.from([0x80, 0xff]), other), path('added.txt', empty)]) + r.setWork('readme.txt', 'lead\nworking\nend\n') + r.setWork('mode.sh', 'same\n', true) + r.setWork('type-change', 'regular\n') + r.setWork('staged-deleted.txt', 'untracked different replacement') + r.setWork('untracked-now.txt', 'never read') + r.setWork('added.txt', '') + const view = status(r) + assert.equal(view.state, 'ready') + assert.match(view.fingerprint, /^[0-9a-f]{64}$/) + assert.equal(view.branch, 'main') + assert.deepEqual(view.entries, [ + { rel: 'added.txt', staged: 'A', worktree: null, conflicted: false, diffSides: ['staged'] }, + { rel: 'mode.sh', staged: null, worktree: 'M', conflicted: false, diffSides: ['worktree'] }, + { rel: 'readme.txt', staged: 'M', worktree: 'M', conflicted: false, diffSides: ['staged', 'worktree'] }, + { rel: 'removed.txt', staged: null, worktree: 'D', conflicted: false, diffSides: ['worktree'] }, + { rel: 'staged-deleted.txt', staged: 'D', worktree: null, conflicted: false, diffSides: ['staged'] }, + { rel: 'type-change', staged: 'T', worktree: null, conflicted: false, diffSides: [] }, + ]) + assert.deepEqual(r.workReads, ['added.txt', 'mode.sh', 'readme.txt', 'removed.txt', 'type-change']) + assert.ok(view.limitations.includes('tracked_only')) + assert.ok(view.limitations.includes('excluded_paths')) + assert.ok(view.limitations.includes('non_regular_entries')) + assert.deepEqual(changedText(diff(r, view, 'readme.txt', 'staged')), [['del', 'old'], ['add', 'staged']]) + assert.deepEqual(changedText(diff(r, view, 'readme.txt', 'worktree')), [['del', 'staged'], ['add', 'working']]) + assert.deepEqual(diff(r, view, 'mode.sh', 'worktree').lines, [{ type: 'hunk', text: 'mode 100644 → 100755' }]) + assert.deepEqual(diff(r, view, 'added.txt', 'staged').lines, [{ type: 'hunk', text: 'Empty file added' }]) + assert.deepEqual(changedText(diff(r, view, 'removed.txt', 'worktree')), [['del', 'same']]) + const numbered = diff(r, view, 'readme.txt', 'staged').lines + assert.deepEqual(numbered[0], { type: 'hunk', text: '@@ -1,3 +1,3 @@' }) + assert.deepEqual(numbered[2], { type: 'del', oldNo: 2, text: 'old' }) + assert.deepEqual(numbered[3], { type: 'add', newNo: 2, text: 'staged' }) +}) + +test('real local and remote tracking refs, detached and unborn HEAD, and first-parent audit rows', () => { + const r = repo() + const unborn = status(r) + assert.equal(unborn.state, 'ready') + assert.equal(unborn.branch, 'main') + assert.equal(unborn.unborn, true) + assert.deepEqual(inspectGit(r.io, { op: 'log' }).commits, []) + const tree = r.tree([]) + const root = r.commit(tree, { message: 'Public root' }) + const side = r.commit(tree, { message: 'Unvisited side', parents: [root] }) + const main = r.commit(tree, { message: 'Email someone@example.test with https://remote/pass /private/path', parents: [root] }) + const head = r.commit(tree, { message: 'Public merge\n\n/hidden/host/path', parents: [main, side] }) + r.head(head) + r.meta.set('packed-refs', Buffer.from(`# pack-refs with: peeled sorted\n${side} refs/heads/side\n${root} refs/remotes/origin/main\n`)) + r.meta.set('refs/remotes/origin/HEAD', Buffer.from('ref: refs/remotes/origin/main\n')) + assert.deepEqual(inspectGit(r.io, { op: 'branches' }), { + state: 'ready', branch: 'main', detached: false, unborn: false, limitations: ['upstream_unknown'], + branches: [ + { name: 'main', current: true, remote: null }, { name: 'side', current: false, remote: null }, + { name: 'origin/main', current: false, remote: 'origin' }, + ], + }) + const log = inspectGit(r.io, { op: 'log', limit: 1000, oid: side }) + assert.equal(log.traversal, 'first-parent') + assert.equal(log.more, false) + assert.deepEqual(log.commits, [ + { oid: head, short: head.slice(0, 7), subject: 'Public merge', author: 'Ada Test', timestamp: when }, + { oid: main, short: main.slice(0, 7), subject: '', author: 'Ada Test', timestamp: when }, + { oid: root, short: root.slice(0, 7), subject: 'Public root', author: 'Ada Test', timestamp: when }, + ]) + assert.equal(inspectGit(r.io, { op: 'log', limit: 1 }).more, true) + assert.equal(r.metaReads.includes(objectPath(side)), false) + r.meta.set('HEAD', Buffer.from(`${head}\n`)) + assert.equal(status(r).detached, true) + assert.equal(inspectGit(r.io, { op: 'log' }).branch, null) + assert.equal(inspectGit(r.io, { op: 'branches' }).branches.some(row => row.current), false) + r.meta.set('shallow', Buffer.from(`${head}\n`)) + const shallow = inspectGit(r.io, { op: 'log' }) + assert.deepEqual(shallow.commits.map(row => row.oid), [head]) + assert.equal(shallow.more, false) + assert.ok(shallow.limitations.includes('shallow')) +}) + +test('v3 conflict, merge marker and intent-to-add; required extensions and checksum are rejected', () => { + const r = repo() + const a = r.blob('old\n'), b = r.blob('other\n'), empty = r.blob('') + const head = r.commit(r.tree([{ path: 'merge.txt', oid: a }])) + r.head(head) + r.meta.set('MERGE_HEAD', Buffer.from(`${head}\n`)) + const items = [ + { path: 'merge.txt', oid: a, stage: 1 }, { path: 'merge.txt', oid: a, stage: 2 }, { path: 'merge.txt', oid: b, stage: 3 }, + { path: 'new.txt', oid: empty, extended: 0x2000 }, + ] + r.index(items, { version: 3, extensions: [['FSMN', Buffer.from('ignored metadata')], ['TREE', Buffer.from('cache')]] }) + r.setWork('merge.txt', 'conflict body\n') + r.setWork('new.txt', 'pending\n') + const view = status(r) + assert.equal(view.mergeInProgress, true) + assert.deepEqual(view.entries, [ + { rel: 'merge.txt', staged: 'U', worktree: 'U', conflicted: true, diffSides: [] }, + { rel: 'new.txt', staged: null, worktree: 'A', conflicted: false, diffSides: ['worktree'] }, + ]) + assert.deepEqual(diff(r, view, 'merge.txt', 'staged').limitations, ['conflicted_entry']) + assert.deepEqual(changedText(diff(r, view, 'new.txt', 'worktree')), [['add', 'pending']]) + for (const ext of ['link', 'sdir', 'abcd']) { + r.index(items, { version: 3, extensions: [[ext, Buffer.alloc(0)]] }) + const unsupported = status(r) + assert.equal(unsupported.state, 'unsupported_layout') + assert.deepEqual(unsupported.entries, []) + } + r.index([{ path: 'sparse/', oid: a, mode: 0o040000 }]) + assert.equal(status(r).state, 'unsupported_layout') + r.index([{ path: 'new.txt', oid: empty, extended: 0x4000 }], { version: 3 }) + assert.equal(status(r).state, 'unsupported_layout') + r.index([], { version: 4 }) + assert.equal(status(r).state, 'unsupported_layout') + const sha256Header = realIndex([]).subarray(0, 12) + r.meta.set('index', Buffer.concat([sha256Header, createHash('sha256').update(sha256Header).digest()])) + assert.equal(status(r).state, 'unsupported_layout') + r.index([], { version: 3 }) + r.meta.get('index')[13] ^= 1 + assert.equal(status(r).state, 'unavailable') + assert.ok(status(r).limitations.includes('index_invalid')) +}) + +test('pack-only repository after GC and explicit missing-object outcomes', () => { + const { fixture: r } = basic('pre-GC\n', 'post-GC\n', 'post-GC\n') + r.pack() + const view = status(r) + assert.equal(view.state, 'ready') + assert.deepEqual(changedText(diff(r, view, 'readme.txt', 'staged')), [['del', 'pre-GC'], ['add', 'post-GC']]) + assert.equal(inspectGit(r.io, { op: 'log' }).commits.length, 1) + + const { fixture: missing, next, tree } = basic('base\n', 'changed\n') + missing.remove(next) + const missingBlob = diff(missing, status(missing), 'readme.txt', 'staged') + assert.equal(missingBlob.state, 'unavailable') + assert.deepEqual(missingBlob.limitations, ['missing_object']) + missing.remove(tree) + const missingTree = status(missing) + assert.equal(missingTree.state, 'unavailable') + assert.ok(missingTree.limitations.includes('missing_object')) + const partial = repo() + const emptyTree = partial.tree([]) + const parent = partial.commit(emptyTree) + const child = partial.commit(emptyTree, { parents: [parent] }) + partial.head(child) + partial.remove(parent) + const log = inspectGit(partial.io, { op: 'log' }) + assert.equal(log.state, 'partial') + assert.deepEqual(log.commits.map(commit => commit.oid), [child]) + assert.ok(log.limitations.includes('missing_object')) +}) + +test('diff preserves raw CRLF, leading BOM and final newline; blocks binary and obvious private keys', () => { + const { fixture: raw } = basic('line\r\nend\n', '\uFEFFline\nend') + const result = diff(raw, status(raw), 'readme.txt', 'staged') + assert.deepEqual(changedText(result), [['del', 'line\r'], ['del', 'end'], ['add', '\uFEFFline'], ['add', 'end']]) + assert.ok(result.lines.some(row => row.text === '\\ No newline at end of file')) + const { fixture: binary } = basic('old\n', Buffer.from([0x00, 0x01, 0xff])) + const hiddenBinary = diff(binary, status(binary), 'readme.txt', 'staged') + assert.equal(hiddenBinary.state, 'binary') + assert.deepEqual(hiddenBinary.lines, []) + const { fixture: key } = basic('# Example\n-----BEGIN OPENSSH PRIVATE KEY-----\nprivate\n', 'replacement\n') + const secret = diff(key, status(key), 'readme.txt', 'staged') + assert.equal(secret.state, 'unavailable') + assert.deepEqual(secret.limitations, ['sensitive_content']) + assert.deepEqual(secret.lines, []) + const { fixture: repeated } = basic('---\n', '-'.repeat(200 * 1024)) + assert.equal(diff(repeated, status(repeated), 'readme.txt', 'staged').state, 'ready') +}) + +test('diff and worktree budgets are explicit; status never turns unread or untrusted files into clean rows', () => { + const { fixture: big } = basic('old\n', 'x'.repeat(256 * 1024)) + assert.equal(diff(big, status(big), 'readme.txt', 'staged').state, 'too_large') + const { fixture: many } = basic('old\n', 'new\n'.repeat(4001)) + assert.deepEqual(diff(many, status(many), 'readme.txt', 'staged').limitations, ['diff_line_limit']) + const { fixture: costly } = basic('old\n'.repeat(1100), 'new\n'.repeat(1100)) + assert.deepEqual(diff(costly, status(costly), 'readme.txt', 'staged').limitations, ['diff_computation_limit']) + const { fixture: output } = basic('old\n', 'new\n'.repeat(1200)) + const cut = diff(output, status(output), 'readme.txt', 'staged') + assert.equal(cut.state, 'ready') + assert.equal(cut.truncated, true) + assert.equal(cut.lines.length, 1000) + const { fixture: unread } = basic('old\n', 'next\n') + unread.work.set('readme.txt', { state: 'unsafe' }) + const partial = status(unread) + assert.equal(partial.state, 'partial') + assert.deepEqual(partial.entries, []) + assert.ok(partial.limitations.includes('unsafe_worktree')) + unread.work.set('readme.txt', { state: 'too_large' }) + const stagedOnly = status(unread) + assert.equal(stagedOnly.state, 'partial') + assert.deepEqual(stagedOnly.entries[0].diffSides, ['staged']) + assert.equal(diff(unread, stagedOnly, 'readme.txt', 'worktree').state, 'too_large') +}) + +test('fresh content is bound to expected status fingerprint, across path content, mode, index and HEAD', () => { + const { fixture: r, next, tree } = basic('before\n', 'stage!\n', 'first!\n') + const view = status(r) + assert.equal(status(r).fingerprint, view.fingerprint) + r.setWork('readme.txt', 'late!!\n') + assert.throws(() => diff(r, view, 'readme.txt', 'worktree'), { code: 'git_stale' }) + const moved = status(r) + r.setWork('readme.txt', 'late!!\n', true) + assert.throws(() => diff(r, moved, 'readme.txt', 'staged'), { code: 'git_stale' }) + const mode = status(r) + r.index([{ path: 'readme.txt', oid: next, mode: EXEC }]) + assert.throws(() => diff(r, mode, 'readme.txt', 'staged'), { code: 'git_stale' }) + const index = status(r) + r.head(r.commit(tree, { message: 'Different HEAD, same tree' })) + assert.throws(() => diff(r, index, 'readme.txt', 'staged'), { code: 'git_stale' }) + assert.throws(() => inspectGit(r.io, { op: 'diff', rel: 'readme.txt', side: 'staged' }), { code: 'git_stale' }) +}) + +test('tree depth, index entries, serialized result size and history traversal are bounded', () => { + const r = repo() + const blob = r.blob('tracked\n') + let tree = r.tree([{ path: 'readme.txt', oid: blob }]) + for (let i = 0; i < 16; i++) tree = r.tree([{ path: 'subdir', oid: tree, mode: 0o040000 }]) + r.head(r.commit(tree)) + const deep = status(r) + assert.equal(deep.state, 'unavailable') + assert.ok(deep.limitations.includes('head_tree_limit')) + + const many = repo() + const leaf = many.blob('entry\n') + many.index(Array.from({ length: 2001 }, (_, i) => ({ path: `file-${i}`, oid: leaf }))) + const tooMany = status(many) + assert.equal(tooMany.state, 'unavailable') + assert.ok(tooMany.limitations.includes('index_limit')) + const long = Array.from({ length: 1000 }, (_, i) => ({ path: `${String(i).padStart(4, '0')}/${'a'.repeat(240)}/`.repeat(7) + 'file', oid: leaf })) + many.index(long) + const output = status(many) + assert.equal(output.state, 'partial') + assert.ok(output.entries.length < long.length) + assert.ok(output.limitations.includes('status_output_limit')) + + const history = repo(), empty = history.tree([]) + let parent = history.commit(empty) + for (let i = 0; i < 104; i++) parent = history.commit(empty, { parents: [parent], message: 'x'.repeat(200), author: 'a'.repeat(100) }) + history.head(parent) + const log = inspectGit(history.io, { op: 'log', limit: 1000 }) + assert.equal(log.commits.length, 100) + assert.equal(log.more, true) + assert.equal(log.commits[0].author, 'a'.repeat(95) + '…') + assert.equal(log.commits[0].subject, 'x'.repeat(159) + '…') +}) + +test('not-repo and unsupported layouts are distinct and perform zero reads', () => { + for (const state of ['not_repo', 'unsupported_layout']) { + const io = { state, readMeta() { assert.fail('unexpected metadata read') } } + for (const op of ['branches', 'log', 'status']) assert.equal(inspectGit(io, { op }).state, state) + const snapshot = inspectGit(io, { op: 'status' }) + assert.equal(inspectGit(io, { op: 'diff', rel: 'readme.txt', side: 'staged', expectedFingerprint: snapshot.fingerprint }).state, 'unavailable') + } +}) diff --git a/apps/headless/test/git-objects.test.mjs b/apps/headless/test/git-objects.test.mjs new file mode 100644 index 00000000..c2f890a2 --- /dev/null +++ b/apps/headless/test/git-objects.test.mjs @@ -0,0 +1,297 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { basename, dirname, join, resolve } from 'node:path' +import { performance } from 'node:perf_hooks' +import test from 'node:test' +import { deflateSync } from 'node:zlib' +import { createGitObjectReader } from '../src/git/objects.mjs' + +const MiB = 1024 * 1024 +const sha1 = bytes => createHash('sha1').update(bytes).digest() +const oidForBlob = bytes => createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex') +const loosePath = oid => `objects/${oid.slice(0, 2)}/${oid.slice(2)}` +const errorCode = code => error => error.code === code && error.message === code + +function repo(t) { + const tmp = resolve(tmpdir()) + const root = mkdtempSync(join(tmp, 'deva-git-objects-')) + t.after(() => { + assert.equal(dirname(root), tmp) + assert.match(basename(root), /^deva-git-objects-/) + rmSync(root, { recursive: true, force: true }) + }) + const metadata = join(root, '.git') + const env = { + PATH: '/usr/bin:/bin', HOME: root, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', + GIT_AUTHOR_NAME: 'Local QA', GIT_AUTHOR_EMAIL: 'qa@example.test', + GIT_COMMITTER_NAME: 'Local QA', GIT_COMMITTER_EMAIL: 'qa@example.test', + GIT_AUTHOR_DATE: '2025-01-01T00:00:00Z', GIT_COMMITTER_DATE: '2025-01-01T00:00:00Z', LC_ALL: 'C' + } + const git = (args, input) => execFileSync('/usr/bin/git', ['-c', 'gc.auto=0', ...args], { + cwd: root, env, input, maxBuffer: 8 * MiB, stdio: ['pipe', 'pipe', 'pipe'] + }) + git(['init', '--quiet', '--template=', '--object-format=sha1', '-b', 'main']) + const text = (...args) => git(args).toString('utf8').trim() + const readMeta = (rel, maxBytes) => { + assert.match(rel, /^objects\/(?:[0-9a-f]{2}\/[0-9a-f]{38}|pack\/pack-[0-9a-f]{40}\.(?:idx|pack))$/) + const path = join(metadata, rel) + try { + if (statSync(path).size > maxBytes) throw Object.assign(Error(path), { code: 'git_limit' }) + return readFileSync(path) + } catch (error) { + if (error.code === 'ENOENT') return null + throw error + } + } + const listMeta = (rel, maxEntries) => { + assert.equal(rel, 'objects/pack') + const path = join(metadata, rel) + try { + const entries = readdirSync(path, { withFileTypes: true }) + if (entries.length > maxEntries) throw Object.assign(Error(path), { code: 'git_limit' }) + return entries.map(e => ({ name: e.name, type: e.isFile() ? 'file' : 'other' })) + } catch (error) { + if (error.code === 'ENOENT') return [] + throw error + } + } + return { root, metadata, git, text, io: { readMeta, listMeta } } +} + +function relatedObjects(repository) { + const { root, text } = repository + const lines = Array.from({ length: 900 }, (_, i) => `Topic ${i}: ${sha1(Buffer.from(`ordinary record ${i}`)).toString('hex')}`) + const records = [] + writeFileSync(join(root, 'empty.txt'), '') + for (let i = 0; i < 10; i++) { + lines[i * 73] = `Amended record ${i}: an ordinary local edit.` + writeFileSync(join(root, 'notes.txt'), `${lines.join('\n')}\n`) + text('add', '--', 'notes.txt', 'empty.txt') + text('commit', '--quiet', '-m', `Revise notes ${i}`) + records.push({ oid: text('rev-parse', 'HEAD'), type: 'commit' }) + records.push({ oid: text('rev-parse', 'HEAD^{tree}'), type: 'tree' }) + records.push({ oid: text('rev-parse', 'HEAD:notes.txt'), type: 'blob' }) + } + text('tag', '-a', 'revision', '-m', 'Annotated local release') + records.push({ oid: text('rev-parse', 'refs/tags/revision'), type: 'tag' }) + records.push({ oid: text('rev-parse', 'HEAD:empty.txt'), type: 'blob' }) + return records +} + +function compareObjects(repository, records, reader) { + for (const { oid, type } of records) { + assert.equal(repository.text('cat-file', '-t', oid), type) + assert.deepEqual(reader.get(oid), { type, bytes: repository.git(['cat-file', type, oid]) }) + } +} + +function packEntries(repository, records, useOffsetDeltas) { + repository.text('-c', `repack.useDeltaBaseOffset=${useOffsetDeltas}`, 'repack', '-adf', '--depth=50', '--window=20') + const list = repository.io.listMeta('objects/pack', 128) + const idx = list.find(({ name }) => name.endsWith('.idx')).name + const packName = idx.replace(/\.idx$/, '.pack') + const packBytes = repository.io.readMeta(`objects/pack/${packName}`, 24 * MiB) + const report = repository.text('verify-pack', '-v', join(repository.metadata, 'objects', 'pack', idx)) + const deltas = report.split('\n').map(line => line.trim().split(/\s+/)).filter(parts => parts.length === 7 && parts[1] === 'blob') + assert.ok(deltas.length >= 5, 'the fixture must contain real blob deltas') + for (const [oid, , , , offset] of deltas) { + assert.ok(records.some(record => record.oid === oid)) + assert.equal((packBytes[Number(offset)] >>> 4) & 7, useOffsetDeltas ? 6 : 7) + } + for (const { oid } of records) assert.equal(repository.io.readMeta(loosePath(oid), 4 * MiB), null) + return { idx: `objects/pack/${idx}`, pack: `objects/pack/${packName}` } +} + +test('loose SHA‑1 commits, trees, blobs and tags agree byte for byte with cat-file', t => { + const repository = repo(t) + const records = relatedObjects(repository) + const reader = createGitObjectReader({ ...repository.io, listMeta() { throw Error('unexpected pack lookup') } }) + compareObjects(repository, records, reader) + const [record] = records + reader.get(record.oid).bytes.fill(0) + compareObjects(repository, [record], reader) +}) + +for (const useOffsetDeltas of [true, false]) { + test(`Git repack ${useOffsetDeltas ? 'OFS_DELTA' : 'REF_DELTA'} objects agree byte for byte with cat-file`, t => { + const repository = repo(t) + const records = relatedObjects(repository) + packEntries(repository, records, useOffsetDeltas) + let listed = 0 + const io = { ...repository.io, listMeta(...args) { listed++; return repository.io.listMeta(...args) } } + const reader = createGitObjectReader(io) + compareObjects(repository, records, reader) + const [record] = records + reader.get(record.oid).bytes.fill(0) + compareObjects(repository, [record], reader) + assert.throws(() => reader.get('0'.repeat(40)), errorCode('git_object_unavailable')) + assert.equal(listed, 1) + }) +} + +test('over-limit and malformed loose streams fail closed through the bounded IO interface', t => { + const repository = repo(t) + const oversized = repository.git(['hash-object', '-w', '--stdin'], Buffer.alloc(2 * MiB + 1, 0x78)).toString().trim() + assert.throws(() => createGitObjectReader(repository.io).get(oversized), errorCode('git_limit')) + + const body = Buffer.from('ordinary') + const oid = oidForBlob(body) + const valid = deflateSync(Buffer.concat([Buffer.from('blob 8\0'), body])) + for (const encoded of [ + valid.subarray(0, -2), Buffer.concat([valid, Buffer.from('trailing')]), Buffer.concat([valid, valid]), + deflateSync(Buffer.from('blob 7\0ordinary')), deflateSync(Buffer.from('blob 08\0ordinary')), + deflateSync(Buffer.from('blob 8\0Ordinary')), deflateSync(Buffer.from('item 8\0ordinary')) + ]) { + const io = { readMeta(rel) { assert.equal(rel, loosePath(oid)); return encoded }, listMeta() { return [] } } + assert.throws(() => createGitObjectReader(io).get(oid), errorCode('git_corrupt')) + } + const lookup = createGitObjectReader({ readMeta() { throw Error('/workspace/private/path') }, listMeta() { return [] } }) + assert.throws(() => lookup.get(oid), errorCode('git_object_unavailable')) + for (const code of ['git_stale', 'git_unsafe']) { + const io = { readMeta() { throw Object.assign(Error('/workspace/private/path'), { code }) } } + assert.throws(() => createGitObjectReader(io).get(oid), errorCode(code)) + } + assert.throws(() => lookup.get(`${oid}\n`), errorCode('git_corrupt')) + assert.throws(() => lookup.get('../objects/pack'), errorCode('git_corrupt')) + assert.throws(() => lookup.get(oid.toUpperCase()), errorCode('git_corrupt')) +}) + +test('repeated reads charge one reader-wide byte budget', t => { + t.mock.method(performance, 'now', () => 0) + const body = Buffer.alloc(2 * MiB, 0x78) + const oid = oidForBlob(body) + const data = deflateSync(Buffer.concat([Buffer.from(`blob ${body.length}\0`), body])) + const reader = createGitObjectReader({ readMeta: () => data, listMeta: () => [] }) + for (let i = 0; i < 31; i++) assert.equal(reader.get(oid).bytes.length, body.length) + assert.throws(() => reader.get(oid), errorCode('git_limit')) +}) + +test('the cooperative deadline accumulates active time and excludes idle time', t => { + let clock = 0, reads = 0 + t.mock.method(performance, 'now', () => clock) + const body = Buffer.from('ordinary') + const oid = oidForBlob(body) + const data = deflateSync(Buffer.concat([Buffer.from('blob 8\0'), body])) + const reader = createGitObjectReader({ readMeta() { reads++; clock += 450; return data } }) + assert.deepEqual(reader.get(oid).bytes, body) + clock += 5000 + assert.deepEqual(reader.get(oid).bytes, body) + assert.throws(() => reader.get(oid), errorCode('git_limit')) + assert.throws(() => reader.get(oid), errorCode('git_limit')) + assert.equal(reads, 3) +}) + +test('packed file checksums, count, fanout, offsets and paired files are enforced', t => { + const repository = repo(t) + const records = relatedObjects(repository) + const filenames = packEntries(repository, records, true) + const [{ oid }] = records + const mutate = (which, change, code = 'git_corrupt') => { + const io = { ...repository.io, readMeta(rel, cap) { + const bytes = repository.io.readMeta(rel, cap) + if (rel === filenames[which]) change(bytes) + return bytes + } } + assert.throws(() => createGitObjectReader(io).get(oid), errorCode(code)) + } + const patchIdx = change => mutate('idx', bytes => { + change(bytes) + sha1(bytes.subarray(0, -20)).copy(bytes, bytes.length - 20) + }) + mutate('idx', bytes => { bytes[bytes.length - 1] ^= 1 }) + mutate('pack', bytes => { bytes[bytes.length - 1] ^= 1 }) + mutate('pack', bytes => bytes.writeUInt32BE(bytes.readUInt32BE(8) + 1, 8)) + patchIdx(bytes => bytes.writeUInt32BE(bytes.readUInt32BE(8 + 255 * 4) + 1, 8)) + patchIdx(bytes => { + const n = bytes.readUInt32BE(8 + 255 * 4) + bytes.writeUInt32BE(9, 8 + 256 * 4 + 24 * n) + }) + patchIdx(bytes => { + const n = bytes.readUInt32BE(8 + 255 * 4) + const offsetTable = 8 + 256 * 4 + 24 * n + bytes.writeUInt32BE(bytes.readUInt32BE(offsetTable + 4), offsetTable) + }) + patchIdx(bytes => { bytes[8 + 256 * 4 + 20 * bytes.readUInt32BE(8 + 255 * 4)] ^= 1 }) + const io = { ...repository.io, listMeta(...args) { return repository.io.listMeta(...args).filter(e => e.name.endsWith('.idx')) } } + assert.throws(() => createGitObjectReader(io).get(oid), errorCode('git_corrupt')) +}) + +test('ordinary Git packed blobs at and beyond the object limit', t => { + const repository = repo(t) + writeFileSync(join(repository.root, 'at-limit.txt'), Buffer.alloc(2 * MiB, 0x61)) + writeFileSync(join(repository.root, 'over-limit.txt'), Buffer.alloc(2 * MiB + 1, 0x62)) + repository.text('add', '--', 'at-limit.txt', 'over-limit.txt') + repository.text('commit', '--quiet', '-m', 'Large ordinary text') + const atLimit = repository.text('rev-parse', 'HEAD:at-limit.txt') + const overLimit = repository.text('rev-parse', 'HEAD:over-limit.txt') + const head = repository.text('rev-parse', 'HEAD') + repository.text('repack', '-adf', '--window=0') + for (const oid of [head, atLimit, overLimit]) assert.equal(repository.io.readMeta(loosePath(oid), 4 * MiB), null) + const reader = createGitObjectReader(repository.io) + compareObjects(repository, [{ oid: head, type: 'commit' }, { oid: atLimit, type: 'blob' }], reader) + assert.throws(() => reader.get(overLimit), errorCode('git_limit')) +}) + +function crc32(bytes) { + let crc = 0xffffffff + for (const byte of bytes) { + crc ^= byte + for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0) + } + return (crc ^ 0xffffffff) >>> 0 +} + +test('PACK v3 uses normal entry framing; generic padding after a zlib stream is corrupt', t => { + const repository = repo(t) + const records = relatedObjects(repository) + const paths = packEntries(repository, records, false) + const v2 = repository.io.readMeta(paths.pack, 24 * MiB) + const index = repository.io.readMeta(paths.idx, MiB) + const count = index.readUInt32BE(8 + 255 * 4) + const crcStart = 8 + 256 * 4 + count * 20 + const offsetStart = crcStart + count * 4 + let lastIndex = 0, lastOffset = 0 + for (let i = 0; i < count; i++) { + const offset = index.readUInt32BE(offsetStart + i * 4) + if (offset > lastOffset) { lastOffset = offset; lastIndex = i } + } + const idStart = 8 + 256 * 4 + lastIndex * 20 + const lastOid = index.toString('hex', idStart, idStart + 20) + const last = records.find(({ oid }) => oid === lastOid) + assert.ok(last) + const fixture = (version, trailingBytes = Buffer.alloc(0)) => { + const raw = Buffer.concat([v2.subarray(0, -20), trailingBytes]) + raw.writeUInt32BE(version, 4) + const packHash = sha1(raw) + const idx = Buffer.from(index) + idx.writeUInt32BE(crc32(raw.subarray(lastOffset)), crcStart + lastIndex * 4) + packHash.copy(idx, idx.length - 40) + sha1(idx.subarray(0, -20)).copy(idx, idx.length - 20) + return { + listMeta: repository.io.listMeta, + readMeta(path, cap) { + if (path === paths.pack) return Buffer.concat([raw, packHash]) + if (path === paths.idx) return idx + return repository.io.readMeta(path, cap) + } + } + } + compareObjects(repository, [last], createGitObjectReader(fixture(3))) + assert.throws(() => createGitObjectReader(fixture(4)).get(lastOid), errorCode('unsupported_git_layout')) + assert.throws(() => createGitObjectReader(fixture(3, Buffer.from('padding'))).get(lastOid), errorCode('git_corrupt')) +}) + +test('pack listing limits apply before metadata files are read', () => { + const oid = '0'.repeat(40) + const entries = Array.from({ length: 17 }, (_, i) => { + const prefix = `pack-${i.toString(16).padStart(40, '0')}` + return [{ name: `${prefix}.idx`, type: 'file' }, { name: `${prefix}.pack`, type: 'file' }] + }).flat() + const io = { readMeta(rel) { assert.equal(rel, loosePath(oid)); return null }, listMeta() { return entries } } + assert.throws(() => createGitObjectReader(io).get(oid), errorCode('git_limit')) + entries[0].type = 'symlink' + assert.throws(() => createGitObjectReader(io).get(oid), errorCode('unsupported_git_layout')) +}) diff --git a/apps/headless/test/git-repository.test.mjs b/apps/headless/test/git-repository.test.mjs new file mode 100644 index 00000000..79f02b83 --- /dev/null +++ b/apps/headless/test/git-repository.test.mjs @@ -0,0 +1,301 @@ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { + chmodSync, fstatSync, linkSync, mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, truncateSync, writeFileSync, +} from 'node:fs' +import { createServer } from 'node:net' +import { tmpdir } from 'node:os' +import { dirname, join, resolve, sep } from 'node:path' +import { test } from 'node:test' +import { Worker } from 'node:worker_threads' +import { openWorkspaceCatalog } from '../src/business/workspace-catalog.mjs' +import { openGitIo } from '../src/git/repository.mjs' +import { readGitRefs } from '../src/git/refs.mjs' + +const GIT = '/usr/bin/git' +const a = 'a'.repeat(40) +const b = 'b'.repeat(40) +const linux = { skip: process.platform !== 'linux' } + +function fixture(t, init = true) { + const base = mkdtempSync(join(tmpdir(), 'dsh-git-repository-')) + const root = join(base, 'project') + mkdirSync(root) + const catalog = openWorkspaceCatalog({ root: base }) + const project = catalog.pinProject(catalog.list()[0].id) + const views = [] + t.after(() => { + for (const io of views) io.close() + project.close() + catalog.close() + const path = resolve(base) + assert.ok(path.startsWith(resolve(tmpdir()) + sep + 'dsh-git-repository-')) + rmSync(path, { recursive: true, force: true }) + }) + const git = (...args) => execFileSync(GIT, ['-c', 'core.hooksPath=/dev/null', '-c', 'commit.gpgsign=false', ...args], { + cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], + env: { HOME: base, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', LANG: 'C.UTF-8' }, + }).trim() + const meta = rel => join(root, '.git', rel) + const work = rel => join(root, rel) + const open = () => { + project.assertCurrent() + const io = openGitIo(project) + views.push(io) + return io + } + if (init) git('init', '--quiet', '--initial-branch=main', '--object-format=sha1', '--template=') + return { base, root, project, meta, work, open, git } +} + +function commit(f, content) { + writeFileSync(f.work('hello.txt'), content) + f.git('add', '--', 'hello.txt') + f.git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '--quiet', '-m', content) + return f.git('rev-parse', 'HEAD') +} + +test('uses a real granted root; missing files and empty unborn HEAD remain distinct', linux, t => { + const f = fixture(t, false) + const nonRepo = f.open() + assert.equal(nonRepo.state, 'not_repo') + assert.equal(nonRepo.marker('MERGE_HEAD'), false) + assert.equal(nonRepo.workFile('absent.txt', 3).state, 'missing') + nonRepo.verify() + nonRepo.close() + + f.git('init', '--quiet', '--initial-branch=main', '--object-format=sha1', '--template=') + const io = f.open() + assert.equal(io.state, 'ready') + assert.equal(io.readMeta('index', 4), null) + assert.equal(io.readMeta('refs/heads/nested/missing', 4), null) + assert.deepEqual(io.listMeta('refs/remotes', 5), []) + assert.throws(() => io.readMeta('HEAD', 1), { code: 'git_limit' }) + assert.deepEqual(readGitRefs(io), { + branch: 'main', head: null, detached: false, unborn: true, mergeInProgress: false, + branches: [], shallow: new Set(), limitations: [], + }) + io.verify() + io.close() + rmSync(f.meta('HEAD')) + assert.throws(() => readGitRefs(f.open()), { code: 'git_corrupt' }) +}) + +test('merges real loose and packed SHA-1 refs with Unicode, remote aliases and detached HEAD', linux, t => { + const f = fixture(t) + const first = commit(f, 'initial') + f.git('branch', '主题/équipe') + f.git('update-ref', 'refs/remotes/origin/topic/deep', first) + f.git('symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/topic/deep') + f.git('tag', 'unlisted') + f.git('pack-refs', '--all') + const second = commit(f, 'second') + assert.notEqual(first, second) + writeFileSync(f.meta('shallow'), `${first}\n`) + writeFileSync(f.meta('MERGE_HEAD'), `${first}\n`) + const io = f.open() + assert.deepEqual(io.listMeta('refs/heads', 8), [{ name: 'main', type: 'file' }]) + assert.throws(() => io.listMeta('refs/heads', 0), { code: 'git_limit' }) + assert.ok(io.readMeta(`objects/${second.slice(0, 2)}/${second.slice(2)}`, 4096).length > 0) + assert.match(io.readMeta('packed-refs', 4096).toString('utf8'), /refs\/heads\/主题\/équipe/u) + assert.deepEqual(readGitRefs(io), { + branch: 'main', head: second, detached: false, unborn: false, mergeInProgress: true, + branches: [ + { name: 'main', current: true, remote: null }, + { name: '主题/équipe', current: false, remote: null }, + { name: 'origin/topic/deep', current: false, remote: 'origin' }, + ], + shallow: new Set([first]), limitations: ['shallow'], + }) + io.verify() + writeFileSync(f.meta('HEAD'), `${first}\n`) + assert.throws(() => io.verify(), { code: 'git_stale' }) + const detached = readGitRefs(f.open()) + assert.deepEqual([detached.branch, detached.head, detached.detached, detached.unborn], [null, first, true, false]) + assert.ok(detached.branches.every(ref => ref.current === false)) +}) + +test('excludes nonallowlisted metadata and reads pack names only in the fixed namespace', linux, t => { + const f = fixture(t) + const oid = commit(f, 'packed') + f.git('repack', '-adq') + const packed = f.open() + const entries = packed.listMeta('objects/pack', 5) + assert.equal(entries.length, 2) + for (const { name, type } of entries) { + assert.match(name, /^pack-[a-f0-9]{40}\.(?:idx|pack)$/u) + assert.equal(type, 'file') + assert.ok(packed.readMeta(`objects/pack/${name}`, 65536).length > 0) + } + packed.verify() + packed.close() + + // These paths are rejected before any traversal or data open, even when they exist. + for (const path of ['config', 'hooks', 'logs/HEAD', 'info/attributes', 'refs/tags/unlisted', + '.gitmodules', 'objects/info/alternates', '../hello.txt', '/etc/passwd', 'refs/heads/a\\b', + `objects/${oid.slice(0, 2)}/${oid.slice(2)}.bad`, `objects/pack/${entries[0].name}/extra`]) { + assert.throws(() => packed.readMeta(path, 1024), { code: 'git_unsafe' }) + assert.throws(() => packed.listMeta(path, 10), { code: 'git_unsafe' }) + } + assert.throws(() => packed.marker('config'), { code: 'git_unsafe' }) + assert.throws(() => packed.readMeta(`refs/heads/${Array(16).fill('nested').join('/')}`, 1024), { code: 'git_limit' }) + writeFileSync(f.meta('config'), 'not a parseable Git config\n') + const io = f.open() + assert.equal(readGitRefs(io).head, oid) + io.verify() +}) + +test('unsupported layouts use type or existence and never follow links or pointer files', linux, t => { + const f = fixture(t, false) + const outside = join(f.base, 'outside') + mkdirSync(outside) + writeFileSync(join(outside, 'HEAD'), `${a}\n`) + for (const kind of ['gitfile', 'symlink', 'commondir', 'gitdir', 'reftable', 'objects/info/alternates', + 'objects/info/http-alternates', 'info/grafts', 'refs/replace', `objects/pack/pack-${a}.promisor`, + `objects/pack/pack-${'f'.repeat(64)}.idx`]) { + if (kind === 'gitfile') writeFileSync(f.work('.git'), `gitdir: ${outside}\n`) + else if (kind === 'symlink') symlinkSync(outside, f.work('.git')) + else { + f.git('init', '--quiet', '--initial-branch=main', '--object-format=sha1', '--template=') + if (['refs/replace', 'reftable'].includes(kind)) mkdirSync(f.meta(kind)) + else { + mkdirSync(dirname(f.meta(kind)), { recursive: true }) + symlinkSync(outside, f.meta(kind)) + } + } + const io = f.open() + assert.equal(io.state, 'unsupported_layout', kind) + assert.throws(() => io.readMeta('HEAD', 64), { code: 'unsupported_git_layout' }) + io.verify() + io.close() + const path = resolve(f.work('.git')) + assert.equal(path, f.root + sep + '.git') + rmSync(path, { recursive: true, force: true }) + } +}) + +test('rejects replace refs and unsupported object formats stored in parseable metadata', linux, t => { + const f = fixture(t) + writeFileSync(f.meta('packed-refs'), `${b} refs/replace/${a}\n`) + assert.throws(() => readGitRefs(f.open()), { code: 'unsupported_git_layout' }) + writeFileSync(f.meta('packed-refs'), `${b} refs/heads/valid\n${a} refs/heads/valid\n`) + assert.throws(() => readGitRefs(f.open()), { code: 'git_corrupt' }) + writeFileSync(f.meta('HEAD'), `ref: refs/remotes/origin/main\n`) + assert.throws(() => readGitRefs(f.open()), { code: 'unsupported_git_layout' }) + writeFileSync(f.meta('HEAD'), `${'9'.repeat(64)}\n`) + assert.throws(() => readGitRefs(f.open()), { code: 'unsupported_git_layout' }) +}) + +test('working file states enforce names, content signatures, type, links and permission', linux, t => { + const f = fixture(t) + const outside = join(f.base, 'other.txt') + writeFileSync(outside, 'outside') + chmodSync(f.work('.git'), 0o700) + symlinkSync(outside, f.work('symlink.txt')) + symlinkSync(f.base, f.work('outside-dir')) + linkSync(outside, f.work('hardlink.txt')) + linkSync(outside, f.meta('index')) + writeFileSync(f.work('credentials.json'), '{}') + writeFileSync(f.work('.env'), 'sensitive name') + writeFileSync(f.work('sample.txt'), 'comment\n-----BEGIN OPENSSH PRIVATE KEY-----\n') + writeFileSync(f.work('denied.txt'), 'unreadable', { mode: 0 }) + mkdirSync(f.work('locked')) + writeFileSync(f.work('locked/document.txt'), 'unsearchable') + writeFileSync(f.work('public.txt'), 'hello', { mode: 0o755 }) + writeFileSync(f.work('group-execute.txt'), 'hello') + chmodSync(f.work('group-execute.txt'), 0o654) + chmodSync(f.work('locked'), 0o600) + try { + const io = f.open() + assert.deepEqual(io.workFile('public.txt', 5), { state: 'regular', bytes: Buffer.from('hello'), executable: true }) + assert.deepEqual(io.workFile('group-execute.txt', 5), { state: 'regular', bytes: Buffer.from('hello'), executable: false }) + assert.deepEqual(io.workFile('public.txt', 4), { state: 'too_large' }) + assert.deepEqual(io.workFile('missing', 4), { state: 'missing' }) + for (const path of ['public.txt/no', '../other.txt', '/etc/passwd', 'symlink.txt', 'outside-dir/other.txt', + 'hardlink.txt', 'credentials.json', '.env', 'sample.txt', 'denied.txt', 'locked/document.txt', '.git/HEAD']) { + assert.deepEqual(io.workFile(path, 4096), { state: 'unsafe' }, path) + } + assert.throws(() => io.readMeta('index', 25), { code: 'git_unsafe' }) + io.verify() + } finally { chmodSync(f.work('locked'), 0o700) } +}) + +test('pins special file types without opening them for data', linux, async t => { + const f = fixture(t) + const server = createServer() + await new Promise((resolve, reject) => { + server.once('error', reject) + server.listen(f.work('special.sock'), resolve) + }) + try { + symlinkSync(f.work('special.sock'), f.meta('shallow')) + const io = f.open() + assert.deepEqual(io.workFile('special.sock', 4096), { state: 'unsafe' }) + assert.throws(() => io.readMeta('shallow', 4096), { code: 'git_unsafe' }) + io.verify() + } finally { await new Promise(resolve => server.close(resolve)) } +}) + +test('enforces cumulative read budget across metadata and work files', linux, t => { + const f = fixture(t) + writeFileSync(f.meta('index'), '') + writeFileSync(f.work('large.bin'), '') + truncateSync(f.meta('index'), 32 * 1024 * 1024) + truncateSync(f.work('large.bin'), 33 * 1024 * 1024) + const io = f.open() + assert.equal(io.readMeta('index', 64 * 1024 * 1024).length, 32 * 1024 * 1024) + assert.throws(() => io.workFile('large.bin', 64 * 1024 * 1024), { code: 'git_limit' }) + assert.throws(() => io.readMeta('index', -1), { code: 'git_limit' }) + io.verify() +}) + +test('detects changes to nested observed leaves and a replaced granted directory', linux, t => { + const f = fixture(t) + mkdirSync(f.work('docs')) + writeFileSync(f.work('docs/file.txt'), 'one') + const io = f.open() + assert.equal(io.workFile('docs/file.txt', 100).bytes.toString(), 'one') + assert.deepEqual(io.workFile('docs/absent.txt', 100), { state: 'missing' }) + writeFileSync(f.work('docs/file.txt'), 'two') + assert.throws(() => io.verify(), { code: 'git_stale' }) + assert.throws(() => io.workFile('docs/file.txt', 100), { code: 'git_stale' }) + const fresh = f.open() + const old = resolve(f.root) + assert.equal(old, f.base + sep + 'project') + renameSync(old, join(f.base, 'previous')) + mkdirSync(f.root) + assert.throws(() => fresh.verify(), { code: 'git_stale' }) + assert.throws(() => f.project.assertCurrent(), { code: 'ERR_WORKSPACE_UNAVAILABLE' }) +}) + +test('worker thread owns its copied pin; wrong mount and closed views fail with domain codes', linux, async t => { + const f = fixture(t) + assert.throws(() => openGitIo({ fd: f.project.fd, mount: '0' }), { code: 'git_stale' }) + const worker = new Worker(` + const { parentPort, workerData } = require('node:worker_threads'); + const fs = require('node:fs'); + import(workerData.module).then(({openGitIo}) => { + const native = fs.fstatSync; + fs.fstatSync = function(fd, options) { + const stat = native(fd, options); + if (options?.bigint && stat.isDirectory()) stat.birthtimeNs = process.hrtime.bigint(); + return stat; + }; + require('node:module').syncBuiltinESMExports(); + const io = openGitIo(workerData); + const state = io.state; + io.verify(); + io.close(); io.close(); + try { io.verify(); } catch (error) { parentPort.postMessage([state, error.code]); } + }).catch(error => { throw error; }); + `, { eval: true, workerData: { module: new URL('../src/git/repository.mjs', import.meta.url).href, + fd: f.project.fd, mount: f.project.mount } }) + const result = await new Promise((res, rej) => { + worker.once('message', res) + worker.once('error', rej) + worker.once('exit', code => rej(new Error(`worker exit ${code}`))) + }) + assert.deepEqual(result, ['ready', 'git_stale']) + assert.ok(fstatSync(f.project.fd).isDirectory()) + f.project.assertCurrent() +}) diff --git a/apps/headless/test/git-view-http.test.mjs b/apps/headless/test/git-view-http.test.mjs new file mode 100644 index 00000000..10d2e9d1 --- /dev/null +++ b/apps/headless/test/git-view-http.test.mjs @@ -0,0 +1,109 @@ +import assert from 'node:assert/strict' +import { randomBytes } from 'node:crypto' +import { mkdir, rename, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import test from 'node:test' +import { requestControl } from '../src/control/socket.mjs' +import { gitProjectNames } from '../src/git/access.mjs' +import { openGitService } from '../src/git/service.mjs' +import { startWorkbench } from '../src/server.mjs' +import { initializeMasterKey } from '../src/storage/vault.mjs' +import { makeGitViewRoot, seedGitViewFixture, headLine, stagedLine, worktreeLine } from '../../../scripts/workbench/e2e-git-view-fixture.mjs' + +async function workbench(t, approved) { + const root = await makeGitViewRoot() + let app + t.after(async () => { try { await app?.close() } finally { await root.close() } }) + const fixture = await seedGitViewFixture(root) + const keyFile = join(root.root, 'master.key'), runDir = join(root.root, 'run') + await initializeMasterKey(keyFile) + app = await startWorkbench({dataDir:join(root.root,'data'), keyFile, runDir, webDir:join(root.root,'assets'), port:0, + businessOptions:{workspaceRoot:fixture.workspaceRoot, gitProjects:approved}}) + const call=(path, method='GET', body, login, extra={})=>fetch(app.origin+'/api/v1/'+path, {method, + headers:{...(login?{cookie:login.cookie}:{}), ...(body===undefined?{}:{origin:app.origin,'content-type':'application/json',...(login?{'x-deva-csrf':login.csrf}:{})}),...extra}, + ...(body===undefined?{}:{body:JSON.stringify(body)})}) + const login=async response=>{assert.equal(response.status,200);return {cookie:response.headers.get('set-cookie').split(';')[0],csrf:(await response.json()).csrf}} + const password=randomBytes(24).toString('base64url'), {credential}=await requestControl({runDir,op:'claim'}) + const a=await login(await call('auth/claim','POST',{credential,password})), b=await login(await call('auth/login','POST',{password})) + const projects=(await (await call('workspaces','GET',undefined,a)).json()).workspaces + const alpha=projects.find(p=>p.name==='Alpha').id, beta=projects.find(p=>p.name==='Beta').id + const api=(wid,op,body,who=a,extra)=>call(`workspaces/${wid}/git/${op}`,'POST',body,who,extra) + async function ok(wid,op,body,who) {const r=await api(wid,op,body,who),v=await r.json();assert.equal(r.status,200,`${op}: ${v.error??''}`);return v} + async function error(response,status,code) {const r=await response;assert.equal(r.status,status);assert.deepEqual(await r.json(),{error:code})} + return { fixture,a,b,alpha,beta,call,api,ok,error } +} + +test('a mounted workspace is not an implicit Git history grant', {timeout:20_000}, async t=>{ + const f=await workbench(t, undefined) + const {capabilities}=await (await f.call('bootstrap','GET',undefined,f.a)).json() + assert.equal(capabilities.workspaceFiles,true);assert.equal(capabilities.gitInspect,false) + await f.error(f.api(f.alpha,'status',{}),403,'git_not_granted') + await f.fixture.assertUnchanged() + for(const names of ['["*"]','["../other"]','["Alpha","Alpha"]','[".keys"]',{},[null]]) assert.throws(()=>gitProjectNames(names)) +}) + +test('two owner logins get scoped, read-only projections of a real packed repository', {timeout:30_000}, async t=>{ + const f=await workbench(t, ['Alpha']) + const {capabilities}=await (await f.call('bootstrap','GET',undefined,f.a)).json();assert.equal(capabilities.gitInspect,true) + assert.deepEqual(await f.ok(f.alpha,'available',{}), {available:true,mode:'read-only',workspaceId:f.alpha}) + await f.error(f.api(f.beta,'available',{}),403,'git_not_granted') + await f.error(f.api(f.alpha,'status',{},f.a,{'x-deva-csrf':''}),401,'auth') + await f.error(f.api(f.alpha,'status',{},f.a,{origin:'https://elsewhere.invalid'}),403,'origin') + await f.error(f.api(f.beta,'status',{}),403,'git_not_granted') + await f.error(f.api(f.alpha,'log',{limit:101}),400,'invalid_git_request') + await f.error(f.api(f.alpha,'log',{limit:2,ref:'qa-main'}),400,'invalid_git_request') + const names=await f.ok(f.alpha,'branches',{}) + assert.equal(names.state,'ready');assert.deepEqual(names.branches,[{name:'qa-main',current:true,remote:null},{name:'qa-review',current:false,remote:null}]) + const history=await f.ok(f.alpha,'log',{limit:2}) + assert.equal(history.traversal,'first-parent');assert.deepEqual(history.commits.map(c=>c.oid),[f.fixture.head,f.fixture.first]); assert.equal(history.more,false) + const s=await f.ok(f.alpha,'status',{});assert.equal(s.state,'ready');assert.equal(s.workspaceId,f.alpha);assert.ok(s.limitations.includes('tracked_only')) + assert.match(s.viewId,/^v_[a-f0-9]{32}$/); const [entry]=s.entries + assert.deepEqual([entry.rel,entry.staged,entry.worktree,entry.conflicted],['notes.txt','M','M',false]);assert.match(entry.entryId,/^e_[a-f0-9]{32}$/) + const req={viewId:s.viewId,entryId:entry.entryId,side:'staged'} + await f.error(f.api(f.alpha,'diff',{...req,path:'notes.txt'}),400,'invalid_git_request') + await f.error(f.api(f.alpha,'diff',req,f.b),409,'git_stale') + const staged=await f.ok(f.alpha,'diff',req), work=await f.ok(f.alpha,'diff',{...req,side:'worktree'}) + const contains=(d,k,v)=>d.lines.some(l=>l.type===k&&l.text===v) + assert.ok(contains(staged,'del',headLine));assert.ok(contains(staged,'add',stagedLine));assert.ok(contains(work,'del',stagedLine));assert.ok(contains(work,'add',worktreeLine)) + for(const data of [s,names,history,staged,work]) for(const marker of f.fixture.privateMarkers) assert.equal(JSON.stringify(data).includes(marker),false) + await f.fixture.assertUnchanged() + await writeFile(join(f.fixture.workspaceRoot,'Alpha','notes.txt'),'explicit synthetic external edit\n') + await f.error(f.api(f.alpha,'diff',req),409,'git_stale') + const newer=await f.ok(f.alpha,'status',{}); assert.notEqual(newer.viewId,s.viewId) + await f.error(f.api(f.alpha,'diff',req),409,'git_stale') + await f.call('auth/logout','POST',{},f.a);await f.error(f.api(f.alpha,'status',{}),401,'auth') + assert.equal((await f.ok(f.alpha,'status',{},f.b)).state,'ready') + const alpha=join(f.fixture.workspaceRoot,'Alpha') + await rename(alpha,join(f.fixture.workspaceRoot,'retired'));await mkdir(alpha,{mode:0o700}) + await f.error(f.api(f.alpha,'branches',{},f.b),404,'workspace_unavailable') + const fresh=(await (await f.call('workspaces','GET',undefined,f.b)).json()).workspaces.find(p=>p.name==='Alpha') + assert.notEqual(fresh.id,f.alpha);await f.error(f.api(fresh.id,'branches',{},f.b),403,'git_not_granted') +}) + +test('a diff is bound to its allowed comparison side, project and short-lived view', async()=>{ + let clock=0, reads=0 + const actor={role:'owner',ownerId:'owner',loginSessionId:'binding'} + const grants={enabled:true,pin:()=>({fd:1,mount:'1',assertCurrent(){},close(){}})} + const service=openGitService({grants,auth:{isLoginActive:()=>true,onSessionRevoked:()=>()=>{}},now:()=>clock, + run:async()=>{reads++; return {state:'ready',branch:'main',detached:false,unborn:false,mergeInProgress:false,limitations:['tracked_only'], + fingerprint:'a'.repeat(64),entries:[{rel:'doc.txt',staged:'A',worktree:null,conflicted:false,diffSides:['staged']}]}}}) + try { + const view=await service.inspect(actor,'wid','status',{}), request={viewId:view.viewId,entryId:view.entries[0].entryId,side:'staged'} + await assert.rejects(service.inspect(actor,'other-project','diff',request),{status:409,code:'git_stale'}) + await assert.rejects(service.inspect(actor,'wid','diff',{...request,side:'worktree'}),{status:409,code:'git_stale'}) + clock=60_000;await assert.rejects(service.inspect(actor,'wid','diff',request),{status:409,code:'git_stale'});assert.equal(reads,1) + } finally { await service.close() } +}) + +test('explicit Git work is cancelled on revocation, and shutdown drains borrowed project handles', async()=>{ + const actor={role:'owner',ownerId:'owner',loginSessionId:'one'} + let active=true,listener,resolve,closed=0,signal + const auth={isLoginActive:()=>active,onSessionRevoked(cb){listener=cb;return ()=>{}}} + const grants={enabled:true,pin:()=>({fd:1,mount:'1',assertCurrent(){},close(){closed++}})} + const service=openGitService({grants,auth,run(pin,job,s){signal=s;return new Promise(yes=>{resolve=yes})}}) + const ab=new AbortController(), pending=service.inspect(actor,'wid','status',{},ab.signal) + await assert.rejects(service.inspect(actor,'wid','status',{},ab.signal),{status:409,code:'git_busy'}) + active=false;listener('one');assert.equal(signal.aborted,true) + let done=false;const close=service.close().then(()=>{done=true});await Promise.resolve();assert.equal(closed,0);assert.equal(done,false) + resolve({});await assert.rejects(pending);await close;assert.equal(closed,1);assert.equal(done,true) +}) diff --git a/compose.git-inspect.yaml b/compose.git-inspect.yaml new file mode 100644 index 00000000..c53e8a8f --- /dev/null +++ b/compose.git-inspect.yaml @@ -0,0 +1,6 @@ +# Add alongside compose.workspaces.yaml to allow read-only Git inspection of ONLY named projects. +# Example: DEVA_GIT_PROJECTS='["Documentation"]'. This is not implied by file browsing or chat. +services: + workbench: + environment: + DEVA_GIT_PROJECTS: ${DEVA_GIT_PROJECTS:?Supply a JSON array of approved direct project directory names} diff --git a/docs/development/web-workbench/README.md b/docs/development/web-workbench/README.md index aa514639..561089cd 100644 --- a/docs/development/web-workbench/README.md +++ b/docs/development/web-workbench/README.md @@ -1,6 +1,6 @@ # Web Workbench 能力清单与门禁 -[能力清单](./parity-manifest.json)按桌面 [preload 运行时 `const api`](../../../apps/desktop/src/preload/index.ts)逐项登记:**21 组、186 个方法(含 18 个订阅)、1 个值 `platform`**。当前有 **32 个 `implemented`**:模型与设置 9 项、个人资料 3 项、分域记忆 4 项、角色管理 7 项、授权项目文件读取 2 项、网页文件选择与粘贴上传 2 项、会话模型与归档及列表订阅 3 项、授权交付清单与定位 2 项;其余 **150 个 `pending`、4 个 `desktop-only`**。交付下载覆盖明确的成品格式;静态图预览与整个桌面缩略图机制仍有差别。空闲会话可以改名;在途改名和非默认思考档位仍属部分覆盖。上传格式与模型协议限制在部署说明中列出;目录拖放及图片缩略资源仍按部分覆盖登记。手动选项目和受限文本保存另记为部分覆盖:尚不包含会话挂载或新建文件。角色删除可处理未被引用的自定义角色,对受保护的默认角色和已有引用报冲突;未将其列为桌面级联删除已完成。`platform` 的完整工作台投影仍为 `pending`:为启动页面传递服务器平台名称不等于已经处理完整外壳的快捷键和客户端布局。已有手机版 PWA/relay 和桌面 IPC 都是参照,不是 Workbench 覆盖证明。 +[能力清单](./parity-manifest.json)按桌面 [preload 运行时 `const api`](../../../apps/desktop/src/preload/index.ts)逐项登记:**21 组、186 个方法(含 18 个订阅)、1 个值 `platform`**。当前有 **33 个 `implemented`**:模型与设置 9 项、个人资料 3 项、分域记忆 4 项、角色管理 7 项、授权项目文件读取 2 项、网页文件选择与粘贴上传 2 项、会话模型与归档及列表订阅 3 项、授权交付清单与定位 2 项、Git 只读能力探测 1 项;其余 **149 个 `pending`、4 个 `desktop-only`**。Git 的已跟踪状态、暂存与工作树差异、分支和首父历史按部分覆盖登记;写入及远程操作仍待移植。交付下载覆盖明确的成品格式;静态图预览与整个桌面缩略图机制仍有差别。空闲会话可以改名;在途改名和非默认思考档位仍属部分覆盖。上传格式与模型协议限制在部署说明中列出;目录拖放及图片缩略资源仍按部分覆盖登记。手动选项目和受限文本保存另记为部分覆盖:尚不包含会话挂载或新建文件。角色删除可处理未被引用的自定义角色,对受保护的默认角色和已有引用报冲突;未将其列为桌面级联删除已完成。`platform` 的完整工作台投影仍为 `pending`:为启动页面传递服务器平台名称不等于已经处理完整外壳的快捷键和客户端布局。已有手机版 PWA/relay 和桌面 IPC 都是参照,不是 Workbench 覆盖证明。 通用文本阶段另外给七个 `chat` 条目登记了 `web.partial`:`createSession`、`send`、`abort`、`listSessions`、`loadSession`、`attachSession`、`onEvent`。每项记录已验证范围、专有测试和仍缺的桌面行为;它们仍计入 `pending`,不等同于附件、工具、成员或审批均已接通。[通用文本协议与阶段限制](../../../apps/headless/src/chat/README.md)。 diff --git a/docs/development/web-workbench/parity-manifest.json b/docs/development/web-workbench/parity-manifest.json index 8eefcd7d..09caabe6 100644 --- a/docs/development/web-workbench/parity-manifest.json +++ b/docs/development/web-workbench/parity-manifest.json @@ -177,15 +177,15 @@ "name": "git", "host": "apps/desktop/src/main/services/git.ts", "methods": [ - {"name":"available","kind":"invoke","channel":"git:available","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"聚焦工作区 Git 小组件探测系统 Git"},"web":{"status":"pending","target":"rpc","semantic":"以宿主能力判定是否显示 Git UI,避免暴露 Git 可执行文件物理路径。"}}, - {"name":"status","kind":"invoke","channel":"git:status","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"Git 菜单和提交面板显示分支、合并与改动状态"},"web":{"status":"pending","target":"rpc","semantic":"受信工作区返回分支/upstream、ahead/behind 和冲突分组。"}}, - {"name":"diff","kind":"invoke","channel":"git:diff","desktop":{"surface":"bridge-only","use":"仓库文件 diff IPC:暂存、工作树或未跟踪文件"},"web":{"status":"pending","target":"rpc","semantic":"若接入变更详情,明确三类 diff 的比较基线并限制输出体积。"}}, + {"name":"available","kind":"invoke","channel":"git:available","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"聚焦工作区 Git 小组件探测系统 Git"},"web":{"status":"implemented","target":"rpc","semantic":"以宿主能力判定是否显示 Git UI,避免暴露 Git 可执行文件物理路径。","implementation":{"handler":"apps/headless/src/git/service.mjs","test":"apps/headless/test/git-view-http.test.mjs"}}}, + {"name":"status","kind":"invoke","channel":"git:status","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"Git 菜单和提交面板显示分支、合并与改动状态"},"web":{"status":"pending","target":"rpc","semantic":"受信工作区返回分支/upstream、ahead/behind 和冲突分组。","partial":{"scope":"额外授权的普通 SHA-1 仓返回当前分支、合并状态、真实已跟踪文件暂存/工作树/冲突,缺失数据和超限明确标记。","remaining":"未跟踪项、上游与 ahead/behind、过滤器及所有特殊仓库布局。","handler":"apps/headless/src/git/inspect.mjs","test":"apps/headless/test/git-inspect.test.mjs"}}}, + {"name":"diff","kind":"invoke","channel":"git:diff","desktop":{"surface":"bridge-only","use":"仓库文件 diff IPC:暂存、工作树或未跟踪文件"},"web":{"status":"pending","target":"rpc","semantic":"若接入变更详情,明确三类 diff 的比较基线并限制输出体积。","partial":{"scope":"人工选定受权状态项后,分别查看 HEAD 对索引及索引对工作树的有界真实文本差异与行号。","remaining":"未跟踪差异、原生属性/文本转换器和重命名等扩展比较语义。","handler":"apps/headless/src/git/inspect.mjs","test":"apps/headless/test/git-inspect.test.mjs"}}}, {"name":"stage","kind":"invoke","channel":"git:stage","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"提交面板提交前重新读取状态并暂存全部未暂存改动"},"web":{"status":"pending","target":"rpc","semantic":"在授权仓库基于提交时的状态暂存工作树变更;出现冲突即停止,暂存成功后才能提交。"}}, {"name":"unstage","kind":"invoke","channel":"git:unstage","desktop":{"surface":"bridge-only","use":"批量移出暂存区的 IPC"},"web":{"status":"pending","target":"rpc","semantic":"索引撤销不改工作树,记录操作后状态并保留原文件。"}}, {"name":"discard","kind":"invoke","channel":"git:discard","desktop":{"surface":"bridge-only","use":"恢复跟踪文件或删除未跟踪文件的 IPC"},"web":{"status":"pending","target":"rpc","semantic":"将还原与删除分开列出并明确确认范围;宿主复核选择与路径归属。"}}, {"name":"commit","kind":"invoke","channel":"git:commit","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"提交面板发送已编辑的提交消息"},"web":{"status":"pending","target":"rpc","semantic":"以真实索引为准,保留空提交、冲突及缺身份错误。"}}, {"name":"setConfig","kind":"invoke","channel":"git:set-config","desktop":{"surface":"bridge-only","use":"Git 作者姓名与邮箱写入桥(repo/global)"},"web":{"status":"pending","target":"rpc","semantic":"仓库身份与宿主全局身份要独立授权;明确写入目标,勿误作 Web 账户资料。"}}, - {"name":"branches","kind":"invoke","channel":"git:branches","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"分支菜单加载本地与远程分支以及上游"},"web":{"status":"pending","target":"rpc","semantic":"以完整分支身份呈现当前分支、远程和跟踪关系。"}}, + {"name":"branches","kind":"invoke","channel":"git:branches","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"分支菜单加载本地与远程分支以及上游"},"web":{"status":"pending","target":"rpc","semantic":"以完整分支身份呈现当前分支、远程和跟踪关系。","partial":{"scope":"读取 loose 和 packed refs,区分本地、当前、缓存的远程跟踪分支及 detached/unborn。","remaining":"仓库配置里的上游绑定、远程同步及特殊引用后端。","handler":"apps/headless/src/git/inspect.mjs","test":"apps/headless/test/git-inspect.test.mjs"}}}, {"name":"checkout","kind":"invoke","channel":"git:checkout","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"分支菜单切换已有本地分支"},"web":{"status":"pending","target":"rpc","semantic":"保留脏工作树被阻止的状态并在切换后更新 Git 卡。"}}, {"name":"createBranch","kind":"invoke","channel":"git:create-branch","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"分支菜单创建并切换新分支"},"web":{"status":"pending","target":"rpc","semantic":"校验分支名,对是否切换有明确意图,回显最终分支。"}}, {"name":"checkoutRemote","kind":"invoke","channel":"git:checkout-remote","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"分支菜单把远程分支检出为本地跟踪分支"},"web":{"status":"pending","target":"rpc","semantic":"区分检出现有本地分支与创建跟踪分支,避免名称歧义。"}}, @@ -194,7 +194,7 @@ {"name":"deleteBranch","kind":"invoke","channel":"git:delete-branch","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"分支菜单删除本地分支,未合并时二次确认"},"web":{"status":"pending","target":"rpc","semantic":"保留未合并提交数与显式强删;不把失败自动转成强删。"}}, {"name":"renameBranch","kind":"invoke","channel":"git:rename-branch","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"分支菜单重命名本地分支"},"web":{"status":"pending","target":"rpc","semantic":"用稳定原分支名和校验后的新名称执行,随后刷新当前分支。"}}, {"name":"deleteRemoteBranch","kind":"invoke","channel":"git:delete-remote-branch","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"分支菜单确认后删除远程分支"},"web":{"status":"pending","target":"rpc","semantic":"确认远程与该分支组合;成功后同步远程引用列表。"}}, - {"name":"log","kind":"invoke","channel":"git:log","desktop":{"surface":"bridge-only","use":"按深度读取提交历史的 IPC"},"web":{"status":"pending","target":"rpc","semantic":"限制历史条数,投影提交标识、作者和摘要。"}}, + {"name":"log","kind":"invoke","channel":"git:log","desktop":{"surface":"bridge-only","use":"按深度读取提交历史的 IPC"},"web":{"status":"pending","target":"rpc","semantic":"限制历史条数,投影提交标识、作者和摘要。","partial":{"scope":"授权项目 HEAD 的有界首父提交历史,包含可展示作者名、时间、OID 和摘要;支持 loose 和常见已打包对象。","remaining":"非首父合并历史、桌面深度上限、其他对象格式。","handler":"apps/headless/src/git/inspect.mjs","test":"apps/headless/test/git-inspect.test.mjs"}}}, {"name":"init","kind":"invoke","channel":"git:init","desktop":{"surface":"bridge-only","use":"在选定工作区初始化仓库的 IPC"},"web":{"status":"pending","target":"rpc","semantic":"如果提供建仓入口,只允许操作授权目录,结果回到真实状态。"}}, {"name":"fetch","kind":"invoke","channel":"git:fetch","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"Git 菜单取回上游引用"},"web":{"status":"pending","target":"rpc","semantic":"只刷新远程追踪和状态;不把 fetch 等同于 pull。"}}, {"name":"pull","kind":"invoke","channel":"git:pull","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/redesign/GitWidget.tsx","use":"Git 菜单拉取更新"},"web":{"status":"pending","target":"rpc","semantic":"返回鉴权、网络、脏工作树或冲突分类,不自动吞并错误。"}}, diff --git a/scripts/workbench/e2e-git-view-fixture.mjs b/scripts/workbench/e2e-git-view-fixture.mjs new file mode 100644 index 00000000..2a54f347 --- /dev/null +++ b/scripts/workbench/e2e-git-view-fixture.mjs @@ -0,0 +1,150 @@ +import { execFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { basename, dirname, join } from 'node:path' +import { isDeepStrictEqual, promisify } from 'node:util' + +export class GitViewCheckError extends Error {} +export function check(condition, description) { + if (!condition) throw new GitViewCheckError(description) +} + +export const alpha = 'Alpha', beta = 'Beta', notes = 'notes.txt', betaFile = 'beta-only.txt' +export const branch = 'qa-main', extraBranch = 'qa-review' +export const earlierSubject = 'QA records the initial notes', headSubject = 'QA revises the committed notes' +export const headLine = 'HEAD-only previous note', stagedLine = 'Index-only previous note', worktreeLine = 'Worktree-only new note' +const stagedLead = 'Index inserts a numbered line' +const initialText = 'QA header\nInitial committed note\nQA footer\n' +const headText = `QA header\n${headLine}\nQA footer\n` +const stagedText = `QA header\n${stagedLead}\n${stagedLine}\nQA footer\n` +const worktreeText = `QA header\n${stagedLead}\n${worktreeLine}\nQA footer\n` +const author = 'Git View QA' +export const email = 'git-view-qa@example.invalid', configMarker = 'QA-native-config-only-marker' + +const exec = promisify(execFile) +const gitBin = '/usr/bin/git' +const sha1 = /^[0-9a-f]{40}$/ +const mkdirPrivate = path => mkdir(path, { mode: 0o700 }) + +/** Only delete the original private mkdtemp inode, after its identity is rechecked. */ +export async function makeGitViewRoot() { + const parent = await realpath(tmpdir()) + const prefix = join(parent, 'deva-wb-git-view-') + const root = await mkdtemp(prefix) + const identity = await lstat(root) + check(dirname(root) === parent && root.startsWith(prefix) && /^[A-Za-z0-9]{6}$/.test(root.slice(prefix.length)), + 'Unexpected Git View temporary directory') + async function verify() { + const current = await lstat(root) + check(current.isDirectory() && current.uid === process.geteuid() && (current.mode & 0o777) === 0o700 && + current.dev === identity.dev && current.ino === identity.ino && await realpath(root) === root, + 'Git View temporary directory identity changed') + } + await verify() + return { root, verify, async close() { await verify(); await rm(root, { recursive: true }) } } +} + +async function seedRepository({ temp, alphaDir, signal }) { + const { root } = temp + const home = join(root, 'git-home'), empty = join(root, 'git-no-hooks') + await mkdirPrivate(home) + await mkdirPrivate(empty) + const file = join(alphaDir, notes) + const env = { + PATH: '/usr/bin:/bin', LANG: 'C.UTF-8', HOME: home, XDG_CONFIG_HOME: home, TMPDIR: root, + GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_ATTR_NOSYSTEM: '1', + GIT_ALLOW_PROTOCOL: '', GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0', + GIT_AUTHOR_NAME: author, GIT_COMMITTER_NAME: author, GIT_AUTHOR_EMAIL: email, GIT_COMMITTER_EMAIL: email + } + async function git(args, date = '2024-01-01T12:00:00Z') { + await temp.verify() + check(await realpath(alphaDir) === alphaDir && (await lstat(alphaDir)).isDirectory(), 'Git fixture project escaped its directory') + try { + const { stdout } = await exec(gitBin, ['-c', `core.hooksPath=${empty}`, '-c', 'core.autocrlf=false', + '-c', 'commit.gpgSign=false', '-c', 'gc.auto=0', ...args], { + cwd: alphaDir, env: { ...env, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date }, + signal, timeout: 12_000, maxBuffer: 128 * 1024 + }) + return stdout + } catch { + throw new GitViewCheckError(`Synthetic fixture git ${args[0]} failed (requires ${gitBin})`) + } + } + await git(['init', '--quiet', '--template=', '--object-format=sha1', `--initial-branch=${branch}`]) + await git(['config', '--local', 'qa.nativeConfigOnly', configMarker]) + await writeFile(file, initialText, { mode: 0o600, flag: 'wx' }) + await git(['add', '--', notes]) + await git(['commit', '--quiet', '-m', earlierSubject]) + const first = (await git(['rev-parse', 'HEAD'])).trim() + await git(['branch', '--', extraBranch, first]) + await writeFile(file, headText) + await git(['add', '--', notes]) + await git(['commit', '--quiet', '-m', headSubject], '2024-01-02T12:00:00Z') + const head = (await git(['rev-parse', 'HEAD'])).trim() + check(sha1.test(first) && sha1.test(head) && first !== head && await git(['status', '--porcelain=v1']) === '', + 'Expected two SHA-1 commits and a clean baseline') + await writeFile(file, stagedText) + await git(['add', '--', notes]) + await writeFile(file, worktreeText) + await git(['gc', '--quiet']) + + const gitDir = join(alphaDir, '.git') + const packNames = await readdir(join(gitDir, 'objects', 'pack')) + const pack = packNames.find(name => /^pack-[0-9a-f]{40}\.pack$/.test(name)) + const stats = await git(['count-objects', '-v']) + check((await lstat(gitDir)).isDirectory() && await realpath(gitDir) === gitDir && + pack !== undefined && packNames.includes(`${basename(pack, '.pack')}.idx`) && /^count: 0$/m.test(stats) && + /^in-pack: [1-9]\d*$/m.test(stats), 'Git gc did not leave the real SHA-1 repository backed by a pack and index') + check(await git(['rev-parse', '--show-object-format']) === 'sha1\n' && + await git(['rev-list', '--first-parent', 'HEAD']) === `${head}\n${first}\n` && + await git(['for-each-ref', '--sort=refname', '--format=%(refname:short):%(objectname)', 'refs/heads']) === + `${branch}:${head}\n${extraBranch}:${first}\n` && await git(['remote']) === '', 'Unexpected synthetic Git history or configuration') + check(await git(['log', '-2', '--format=%s']) === `${headSubject}\n${earlierSubject}\n` && + await git(['status', '--porcelain=v1', '--untracked-files=all']) === `MM ${notes}\n` && + await git(['show', `HEAD:${notes}`]) === headText && await git(['show', `:${notes}`]) === stagedText && + await readFile(file, 'utf8') === worktreeText, 'Expected one tracked file with three distinct Git baselines') + return { first, head } +} + +/** Capture every directory and regular file in both projects, including HEAD, config, index, + * refs, the pack, and worktree files. Reads may advance atime; content and mtime must stay put. */ +async function snapshotProjects(workspaceRoot) { + check(await realpath(workspaceRoot) === workspaceRoot, 'Workspace parent identity changed') + const entries = [] + async function visit(relative) { + const path = join(workspaceRoot, relative) + const stat = await lstat(path, { bigint: true }) + const identity = { relative, ino: stat.ino, dev: stat.dev, mode: stat.mode, mtime: stat.mtimeNs } + if (stat.isDirectory()) { + entries.push(identity) + for (const name of (await readdir(path)).sort()) await visit(join(relative, name)) + } else { + check(stat.isFile() && stat.nlink === 1n, 'Unexpected special or hard-linked Git fixture file') + entries.push({ ...identity, size: stat.size, hash: createHash('sha256').update(await readFile(path)).digest('hex') }) + } + } + await visit('') + return entries +} + +export async function seedGitViewFixture(temp, signal) { + await temp.verify() + const workspaceRoot = join(temp.root, 'projects') + const alphaDir = join(workspaceRoot, alpha), betaDir = join(workspaceRoot, beta) + await mkdirPrivate(workspaceRoot) + await mkdirPrivate(alphaDir) + await mkdirPrivate(betaDir) + await writeFile(join(betaDir, betaFile), 'Synthetic Beta project; Git access is not granted.\n', { mode: 0o600, flag: 'wx' }) + const commits = await seedRepository({ temp, alphaDir, signal }) + const before = await snapshotProjects(workspaceRoot) + return { + workspaceRoot, ...commits, + privateMarkers: [temp.root, email, configMarker, '[core]', 'repositoryformatversion'], + async assertUnchanged() { + await temp.verify() + check(isDeepStrictEqual(await snapshotProjects(workspaceRoot), before), + 'Git inspection changed workspace contents, metadata, or file timestamps') + } + } +} diff --git a/scripts/workbench/e2e-git-view.mjs b/scripts/workbench/e2e-git-view.mjs new file mode 100644 index 00000000..423f095b --- /dev/null +++ b/scripts/workbench/e2e-git-view.mjs @@ -0,0 +1,401 @@ +import { randomBytes } from 'node:crypto' +import { access } from 'node:fs/promises' +import { join } from 'node:path' +import { + alpha, beta, betaFile, branch, check, earlierSubject, extraBranch, GitViewCheckError, headLine, headSubject, + makeGitViewRoot, notes, seedGitViewFixture, stagedLine, worktreeLine +} from './e2e-git-view-fixture.mjs' +import { startLocalWebDriver, waitFor, WebDriverError } from './webdriver-local.mjs' + +const hook = name => `[data-testid="${name}"]` +const workspace = name => hook(`workbench-workspace-${name}`) +const dialog = `dialog${workspace('dialog')}[open]` +const git = name => hook(`workspace-git-${name}`) +const toggle = `${dialog} ${git('toggle')}` +const panel = `${dialog} ${git('panel')}` +const inside = name => `${panel} ${git(name)}` +const chat = hook('workbench-chat') +const wid = /^w_[0-9a-f]{32}$/ +const gitPath = /^\/api\/v1\/workspaces\/(w_[0-9a-f]{32})\/git\/(status|branches|log|diff)$/ +const gitContent = [branch, extraBranch, headSubject, earlierSubject, headLine, stagedLine, worktreeLine] + +// Observe only real requests passed through the production business handler. Do not consume +// bodies, alter dispatch or responses, or keep cookies, CSRF tokens, URLs, or Git contents. +function observeWire(openBusiness, signal) { + let pending = [], otherWrites = 0 + return { + async factory(options) { + const business = await openBusiness(options) + return { + ...business, + handle(req, res, context) { + const url = req.url ?? '' + const path = url.split('?', 1)[0] + const match = gitPath.exec(path) + if (path.startsWith('/api/v1/workspaces/') && path.includes('/git')) { + const observation = { + project: match?.[1], action: match?.[2], + sameOrigin: req.headers.origin === context.policy.origin && req.headers['sec-fetch-site'] === 'same-origin', + owner: Boolean(context.policy.cookie(req)), csrf: Boolean(req.headers['x-deva-csrf']), + post: req.method === 'POST' && url === path && /^application\/json(?:;|$)/i.test(req.headers['content-type'] ?? '') + } + pending.push(observation) + res.once('finish', () => { observation.status = res.statusCode }) + } else if (req.method === 'POST' && url === path && /^\/api\/v1\/workspaces\/w_[a-f0-9]{32}\/list$/u.test(path)) { + // Selecting an ordinary workspace legitimately reads one directory by POST to keep + // its path out of URLs. Still require a real verified read; never exempt file writes, + // chat turns, provider probes or any Git operation from their respective counters. + if (!context.policy.cookie(req) || !req.headers['x-deva-csrf'] || req.headers.origin !== context.policy.origin) ++otherWrites + res.once('finish', () => { if (res.statusCode !== 200) ++otherWrites }) + } else if ((req.method !== 'GET' && req.method !== 'HEAD') || path === '/api/v1/provider-models') { + ++otherWrites + } + return business.handle(req, res, context) + } + } + }, + assertNoWrites() { + check(otherWrites === 0, 'The workspace flow invoked a chat, model, or other non-Git write route') + }, + idle() { + check(pending.length === 0, 'A Git request arrived without the expected explicit click') + this.assertNoWrites() + }, + async clicked(project, action, status = 200) { + const observation = await waitFor(() => pending[0]?.status ? pending[0] : null, `real HTTP response to Git ${action}`, { signal }) + check(pending.length === 1 && observation.project === project && observation.action === action && + observation.status === status && observation.post && observation.sameOrigin && observation.owner && observation.csrf, + `Git ${action} did not send one same-origin owner JSON POST with CSRF and the expected status`) + pending = [] + this.idle() + } + } +} + +// Synchronous browser scripts only inspect DOM. All user interactions go through the native +// W3C element click/keys commands from the shared helper, including the project selection. +function controls(browser, signal) { + const until = (probe, description) => waitFor(probe, description, { signal }) + const visible = (selector, description) => until(() => browser.execute(` + return [...document.querySelectorAll(arguments[0])].find(node => node.getClientRects().length && + getComputedStyle(node).visibility === 'visible' && !node.matches(':disabled')) ?? null; + `, selector), description) + const click = async (selector, description) => browser.click(await visible(selector, description)) + return { + until, visible, click, + async openWorkspace() { + await click(workspace('open'), 'workspace toolbar button') + await visible(dialog, 'original native workspace dialog') + }, + absent(selector, description) { + return until(() => browser.execute('return !document.querySelector(arguments[0]);', selector), description) + }, + async catalog() { + const field = await visible(`${dialog} select${workspace('select')}`, 'loaded workspace selector') + const rows = await browser.execute(` + const [field, names] = arguments; + const options = [...field.options]; + if (options.length !== 3 || options[0].value !== '' || field.value !== '') return null; + return names.map(name => options.find(row => !row.disabled && row.textContent.trim() === name)?.value ?? null); + `, field, [alpha, beta]) + check(rows?.length === 2 && rows.every(id => typeof id === 'string' && wid.test(id)) && rows[0] !== rows[1], + 'The workspace selector did not contain exactly Alpha and Beta as distinct projects') + return { alphaId: rows[0], betaId: rows[1] } + }, + async select(project, file) { + const field = await visible(`${dialog} select${workspace('select')}`, 'enabled workspace selector') + const option = await until(() => browser.execute(` + return [...arguments[0].options].find(row => !row.disabled && row.value === arguments[1]) ?? null; + `, field, project), 'authorized workspace option') + await browser.click(option) + await until(() => browser.execute('return arguments[0].value === arguments[1];', field, project), 'selected workspace') + await visible(`${dialog} ${workspace('entry')}[data-path="${file}"]`, 'tree for the selected project') + }, + async privacy(markers) { + check(await browser.execute(` + const [markers] = arguments; + return markers.every(marker => !document.body.innerText.includes(marker) && !document.body.innerHTML.includes(marker)); + `, markers), 'Private or stale Git information appeared in the Workbench DOM') + } + } +} + +async function claim(browser, ui, origin, runDir, requestControl) { + const { credential } = await requestControl({ runDir, op: 'claim' }) + await browser.navigate(`${origin}/#claim=${encodeURIComponent(credential)}`) + const field = await ui.visible('.wb-auth input[name="password"][type="password"][autocomplete="new-password"]', 'owner claim form') + check(await browser.execute('return location.origin === arguments[0] && location.pathname === "/" && !location.search && !location.hash;', origin), + 'Workbench claim did not remain on the expected same-origin page') + await browser.keys(field, randomBytes(24).toString('base64url')) + await ui.click('.wb-auth button[type="submit"]', 'explicitly claim the owner account') + await ui.visible(chat, 'authenticated Workbench shell') + check((await requestControl({ runDir, op: 'status' })).claimed === true, 'Local control did not confirm the claimed owner') +} + +async function showStatus({ browser, ui, wire, fixture }, project, action) { + await ui.click(action === 'open' ? `${toggle}[aria-expanded="false"]` : inside('refresh'), `explicit Git ${action}`) + await ui.visible(panel, 'visible Git inspection panel') + await ui.until(() => browser.execute(` + const [toggle, status, branch] = arguments; + return document.querySelector(toggle)?.textContent.trim() === branch && + ['ready', 'partial'].includes(document.querySelector(status)?.dataset.status); + `, toggle, inside('status'), branch), 'Git status and real current branch') + await wire.clicked(project, 'status') + await ui.privacy(fixture.privateMarkers) +} + +async function showBranchesAndHistory({ browser, ui, wire, fixture }, project) { + await ui.click(inside('branches'), 'explicit Git Branches') + await ui.until(() => browser.execute(` + const [selector, current, extra] = arguments; + const rows = [...document.querySelectorAll(selector + ' li')]; + const named = label => rows.find(row => row.querySelector('bdi')?.textContent === label); + return rows.length === 2 && named(current)?.getAttribute('aria-current') === 'true' && + named(extra)?.getAttribute('aria-current') === null; + `, inside('branch-list'), branch, extraBranch), 'real current and additional local branches') + await wire.clicked(project, 'branches') + await ui.privacy(fixture.privateMarkers) + + await ui.click(inside('history'), 'explicit Git History') + await ui.until(() => browser.execute(` + const [selector, expected] = arguments; + const rows = [...document.querySelectorAll(selector + ' li')]; + return rows.length === expected.length && rows.every((row, i) => { + const [oid, subject] = expected[i]; + const short = row.querySelector('code'); + return row.getClientRects().length && row.querySelector('.wb-git__subject')?.textContent === subject && + short?.title === oid && /^[a-f0-9]{4,40}$/.test(short.textContent) && oid.startsWith(short.textContent); + }); + `, inside('commit-list'), [[fixture.head, headSubject], [fixture.first, earlierSubject]]), 'both packed commit subjects and their real SHA-1 identifiers') + await ui.absent(inside('load-more'), 'two-commit history is fully loaded') + await wire.clicked(project, 'log') + await ui.privacy(fixture.privateMarkers) +} + +async function showDiffs({ browser, ui, wire, fixture }, project) { + await ui.click(`${panel} .wb-git__tabs button:first-child`, 'return to Git Changes') + wire.idle() + const entry = await ui.until(() => browser.execute(` + const [panel, path] = arguments; + const rows = [...(document.querySelector(panel)?.querySelectorAll('button[data-testid^="workspace-git-entry-"]') ?? [])]; + if (rows.length !== 1 || rows[0].disabled || !rows[0].getClientRects().length || rows[0].querySelector('bdi')?.textContent !== path) return null; + return /^workspace-git-entry-(e_[0-9a-f]{32})$/.exec(rows[0].dataset.testid)?.[1] ?? null; + `, panel, notes), 'one visible tracked change with an opaque entry ID') + for (const [side, before, after, oldNo, newNo, otherBaseline] of [ + ['staged', headLine, stagedLine, '2', '3', worktreeLine], + ['worktree', stagedLine, worktreeLine, '3', '3', headLine] + ]) { + await ui.click(inside(`diff-${entry}-${side}`), `explicit ${side} comparison for the selected notes row`) + const diff = `${inside('diff')}[data-state="ready"][data-side="${side}"]` + await ui.until(() => browser.execute(` + const [selector, path, before, after, oldNo, newNo, otherBaseline] = arguments; + const diff = document.querySelector(selector); + if (!diff?.getClientRects().length || diff.querySelector('h4 bdi')?.textContent !== path || + diff.textContent.includes(otherBaseline)) return false; + const line = (kind, text, a, b) => [...diff.querySelectorAll('.diffview__line.' + kind)].some(row => { + const nums = [...row.querySelectorAll('.diffview__no')].map(node => node.textContent.trim()); + const sign = row.querySelector('.diffview__sign')?.textContent; + return row.getClientRects().length && nums.length === 2 && nums[0] === a && nums[1] === b && + sign === (kind === 'del' ? '−' : '+') && row.querySelector('.diffview__text')?.textContent === text; + }); + return line('del', before, oldNo, '') && line('add', after, '', newNo); + `, diff, notes, before, after, oldNo, newNo, otherBaseline), `visible ${side} deletion and addition with correct old and new line numbers`) + await wire.clicked(project, 'diff') + await ui.privacy(fixture.privateMarkers) + } +} + +async function verifyReset(ctx, alphaId, betaId) { + const { ui, wire, fixture } = ctx + const hidden = async () => { + await ui.absent(git('panel'), 'Git panel removed, including all previous rows') + await ui.privacy([...fixture.privateMarkers, ...gitContent]) + wire.idle() + } + await ui.select(betaId, betaFile) + await hidden() + await ui.click(`${toggle}[aria-expanded="false"]`, 'explicitly try the ungranted Beta Git panel') + await ui.visible(`${inside('status')}[data-status="not_granted"] [role="alert"]`, 'Git grant denial in the Beta workspace') + await wire.clicked(betaId, 'status', 403) + await ui.privacy([...fixture.privateMarkers, ...gitContent]) + + await ui.select(alphaId, notes) + await hidden() + await showStatus(ctx, alphaId, 'open') + await ui.click(`${toggle}[aria-expanded="true"]`, 'close the Git panel without leaving the workspace dialog') + await hidden() + await showStatus(ctx, alphaId, 'open') + await ui.click(`${dialog} ${workspace('close')}`, 'close the native workspace dialog') + await ui.absent(dialog, 'closed workspace dialog') + await hidden() + await ui.openWorkspace() + await hidden() + await ui.click(`${dialog} ${workspace('close')}`, 'close the reopened workspace dialog') + await ui.absent(dialog, 'closed reopened workspace dialog') + await hidden() +} + +// These isolated, read-only negative probes run only after all actual browser assertions. +// Keep bootstrap CSRF and wire error bodies in the page and return only fixed outcomes. +async function verifyHttpGuards(browser, origin, alphaId, betaId) { + check(wid.test(alphaId) && wid.test(betaId) && alphaId !== betaId, 'Unexpected workspace IDs for the HTTP probes') + const result = await browser.executeAsync(` + const [origin, alpha, beta, rawPath, finish] = arguments; + if (location.origin !== origin) return finish(1); + const fetchApi = (path, init = {}) => fetch('/api/v1/' + path, { + credentials: 'same-origin', mode: 'same-origin', redirect: 'error', cache: 'no-store', ...init + }); + const path = (project, action) => 'workspaces/' + project + '/git/' + action; + const post = (body, csrf, credentials = 'same-origin') => ({ + method: 'POST', credentials, body: JSON.stringify(body), + headers: { 'content-type': 'application/json', ...(csrf ? { 'x-deva-csrf': csrf } : {}) } + }); + (async () => { + const bootstrap = await fetchApi('bootstrap'); + if (!bootstrap.ok) return 2; + const { csrf } = await bootstrap.json(); + if (typeof csrf !== 'string' || !csrf.length) return 2; + for (const action of ['status', 'diff']) { + const response = await fetchApi(path(alpha, action)); + const { error } = await response.json(); + // Browsers can omit Origin on same-origin GET. The origin or method guard must reject it. + if (!(response.status === 403 && error === 'origin') && + !(response.status === 405 && error === 'method' && response.headers.get('allow') === 'POST')) return 3; + } + const anonymous = await fetchApi(path(alpha, 'status'), post({}, csrf, 'omit')); + if (anonymous.status !== 401 || (await anonymous.json()).error !== 'auth') return 4; + const noCsrf = await fetchApi(path(alpha, 'status'), post({})); + const csrfError = (await noCsrf.json()).error; + if (!(noCsrf.status === 401 && csrfError === 'auth') && !(noCsrf.status === 403 && csrfError === 'csrf_failed')) return 5; + async function status() { + const response = await fetchApi(path(alpha, 'status'), post({}, csrf)); + if (response.status !== 200) return null; + const data = await response.json(); + const entry = data.entries?.find(row => row.rel === rawPath && row.diffSides?.includes('staged')); + return data.workspaceId === alpha && /^v_[a-f0-9]{32}$/.test(data.viewId) && /^e_[a-f0-9]{32}$/.test(entry?.entryId) + ? { viewId: data.viewId, entryId: entry.entryId, side: 'staged' } : null; + } + const before = await status(); + if (!before) return 6; + const raw = await fetchApi(path(alpha, 'diff'), post({ ...before, path: rawPath }, csrf)); + if (raw.status !== 400 || (await raw.json()).error !== 'invalid_git_request') return 7; + const denied = await fetchApi(path(beta, 'status'), post({}, csrf)); + if (denied.status !== 403 || (await denied.json()).error !== 'git_not_granted') return 8; + const after = await status(); + if (!after || after.viewId === before.viewId || after.entryId === before.entryId) return 6; + const stale = await fetchApi(path(alpha, 'diff'), post(before, csrf)); + if (stale.status !== 409 || (await stale.json()).error !== 'git_stale') return 9; + return 0; + })().then(finish, () => finish(10)); + `, origin, alphaId, betaId, notes) + const failures = [null, 'Browser lost the Workbench origin', 'Owner bootstrap unavailable', 'Git unexpectedly served a GET request', + 'Git did not require an owner session', 'Git did not require a CSRF header', 'Git did not issue distinct opaque status views', + 'Git accepted a raw diff path', 'Registered Beta was not denied the extra Git grant', + 'Git did not reject a superseded status view', 'Read-only HTTP probe failed'] + check(result === 0, failures[result] ?? 'Unexpected HTTP probe result') +} + +async function driveBrowser(ctx, setStage) { + const { browser, ui, wire, fixture, origin } = ctx + setStage('select registered Alpha with Git still closed') + await ui.openWorkspace() + const { alphaId, betaId } = await ui.catalog() + await ui.select(alphaId, notes) + await ui.visible(`${toggle}[aria-expanded="false"]`, 'closed Git toggle for Alpha') + await ui.absent(git('panel'), 'Git panel absent by default') + await ui.privacy([...fixture.privateMarkers, ...gitContent]) + wire.idle() + + setStage('click Git and refresh the real repository status') + await showStatus(ctx, alphaId, 'open') + await showStatus(ctx, alphaId, 'refresh') + setStage('click Branches and History') + await showBranchesAndHistory(ctx, alphaId) + setStage('click the notes staged and worktree diffs') + await showDiffs(ctx, alphaId) + setStage('switch projects and close Git and the workspace') + await verifyReset(ctx, alphaId, betaId) + setStage('check read-only HTTP method, owner scope, CSRF, raw paths and stale views') + await verifyHttpGuards(browser, origin, alphaId, betaId) + wire.assertNoWrites() +} + +async function runBrowser(resources, fixture, signal, setStage) { + setStage('check non-root browser environment and build outputs') + check(process.platform === 'linux' && process.getuid?.() > 0 && process.geteuid?.() > 0, 'Run the browser E2E on Linux as a non-root user') + await Promise.all(['provider', 'chat', 'library'].map(entry => + access(new URL(`../../apps/headless/dist/${entry}-core.mjs`, import.meta.url)))).catch(() => { + throw new GitViewCheckError('Build the headless cores with pnpm --filter @deva/headless build') + }) + const { DEFAULT_WEB_DIR, startWorkbench } = await import('../../apps/headless/src/server.mjs') + await access(join(DEFAULT_WEB_DIR, 'index.html')).catch(() => { throw new GitViewCheckError('Build the Workbench with pnpm workbench:build') }) + setStage('start the real Workbench on loopback') + const [{ requestControl }, { initializeMasterKey }, { openBusiness }] = await Promise.all([ + import('../../apps/headless/src/control/socket.mjs'), import('../../apps/headless/src/storage/vault.mjs'), + import('../../apps/headless/src/business/handlers.mjs') + ]) + const root = resources.temp.root + const keyFile = join(root, 'master.key'), runDir = join(root, 'run') + const wire = observeWire(openBusiness, signal) + await initializeMasterKey(keyFile) + const workbench = resources.workbench = await startWorkbench({ dataDir: join(root, 'data'), keyFile, runDir, host: '127.0.0.1', + webDir: DEFAULT_WEB_DIR, port: 0, businessFactory: wire.factory, + businessOptions: { workspaceRoot: fixture.workspaceRoot, gitProjects: [alpha] } }) + const origin = workbench.origin + check(workbench.address.address === '127.0.0.1' && origin === `http://127.0.0.1:${workbench.address.port}`, 'Unexpected Workbench listener or origin') + const ready = await fetch(`${origin}/readyz`, { redirect: 'error', signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) }) + await ready.body?.cancel() + check(ready.status === 200, 'Workbench readiness did not report HTTP 200') + + setStage('start non-root sandboxed Chrome') + const browser = resources.browser = await startLocalWebDriver({ root, profile: join(root, 'chrome-profile'), origin, signal }) + const ui = controls(browser, signal) + setStage('claim Workbench through its owner form and private Unix control') + await claim(browser, ui, origin, runDir, requestControl) + await driveBrowser({ browser, ui, wire, fixture, origin }, setStage) +} + +function detail(error) { + return error instanceof GitViewCheckError || error instanceof WebDriverError ? error.message : 'unexpected error (raw diagnostics withheld)' +} + +async function run(fixtureOnly) { + const stop = new AbortController() + const abort = () => stop.abort() + process.once('SIGINT', abort) + process.once('SIGTERM', abort) + const signal = AbortSignal.any([stop.signal, AbortSignal.timeout(180_000)]) + let fixture, stage = 'create isolated packed SHA-1 fixture', failed = false + const resources = {} + try { + resources.temp = await makeGitViewRoot() + fixture = await seedGitViewFixture(resources.temp, signal) + if (!fixtureOnly) await runBrowser(resources, fixture, signal, next => { stage = next }) + } catch (error) { + failed = true + console.error(`Workbench Git View ${fixtureOnly ? 'fixture' : 'E2E'} failed at ${stage}: ${signal.aborted ? 'interrupted or timed out' : detail(error)}`) + } finally { + for (const [name, cleanup] of [ + ['browser shutdown', () => resources.browser?.close()], ['Workbench shutdown', () => resources.workbench?.close()], + ['fixture Git and worktree integrity', () => fixture?.assertUnchanged()], ['temporary directory cleanup', () => resources.temp?.close()] + ]) { + try { await cleanup() } catch (error) { + failed = true + console.error(`Workbench Git View ${name} failed: ${detail(error)}`) + } + } + process.removeListener('SIGINT', abort) + process.removeListener('SIGTERM', abort) + } + if (failed || signal.aborted) process.exitCode = 1 + else if (fixtureOnly) console.log('Workbench Git View fixture passed: two genuine SHA-1 commits, pack and index, and distinct HEAD/index/worktree bytes. Browser E2E was not run.') + else console.log('Workbench Git View E2E passed: explicit owner clicks, real packed history and branches, both numbered diffs, cleared views, HTTP guards, and unchanged Git and worktree files.') +} + +const args = process.argv.slice(2) +if (!args.length) await run(false) +else if (args.length === 1 && args[0] === '--fixture-only') await run(true) +else { + console.error('Usage: node scripts/workbench/e2e-git-view.mjs [--fixture-only]') + process.exitCode = 1 +} diff --git a/scripts/workbench/git-view-ui.test.mjs b/scripts/workbench/git-view-ui.test.mjs new file mode 100644 index 00000000..04491643 --- /dev/null +++ b/scripts/workbench/git-view-ui.test.mjs @@ -0,0 +1,321 @@ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import test from 'node:test' + +const require = createRequire(new URL('../../apps/desktop/package.json', import.meta.url)) +const ts = require('typescript') +const src = new URL('../../apps/desktop/src/workbench/', import.meta.url) +async function load(name, dependencies = {}) { + const js = ts.transpileModule(await readFile(new URL(name, src), 'utf8'), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX } + }).outputText + const module = { exports: {} } + new Function('require', 'module', 'exports', js)((name) => Object.hasOwn(dependencies, name) ? dependencies[name] : require(name), module, module.exports) + return module.exports +} +const base = await load('transport.ts') +const gitTransport = await load('git-view-transport.ts') +const gitController = await load('git-view-controller.ts', { './transport': base, './git-view-transport': gitTransport }) +const filesController = await load('workspace-files.ts', { './transport': base }) +const { createTransport, HttpFailure } = base +const { createGitViewTransport } = gitTransport +const { bindWorkspaceGitView, createWorkspaceGitView } = gitController + +const a = `w_${'a'.repeat(32)}`, b = `w_${'b'.repeat(32)}`, foreign = `w_${'c'.repeat(32)}` +const viewId = `v_${'1'.repeat(32)}`, nextViewId = `v_${'2'.repeat(32)}`, entryId = `e_${'3'.repeat(32)}` +const rel = 'docs/名字 .md' +const entry = { entryId, rel, staged: 'M', worktree: 'M', conflicted: false, diffSides: ['staged', 'worktree'] } +const head = { state: 'ready', branch: 'main', detached: false, unborn: false, limitations: ['tracked_only', 'upstream_unknown'] } +const status = (workspaceId = a, extra = {}) => ({ ...head, workspaceId, mergeInProgress: false, viewId, entries: [entry], ...extra }) +const branches = { ...head, branches: [{ name: 'main', current: true, remote: null }, { name: 'origin/main', current: false, remote: 'origin' }] } +const oid = '0cb22ba9'.repeat(5) +const log = { state: 'ready', branch: 'main', commits: [{ oid, short: oid.slice(0, 7), subject: '', timestamp: 1_701_234_567 }], traversal: 'first-parent', more: true, limitations: ['first_parent'] } +const diff = { state: 'ready', rel, side: 'worktree', lines: [{ type: 'hunk', text: '@@ -1,1 +1,2 @@' }, + { type: 'del', oldNo: 1, text: '' }, { type: 'add', newNo: 1, text: 'new ' }, { type: 'ctx', oldNo: 2, newNo: 2, text: 'ctx' }], + truncated: true, limitations: ['git_limit'] } +const bootstrap = { protocol: 1, version: '1', platform: 'linux', config: {}, csrf: 'owner-csrf', expiresAt: 1_900_000_000_000 } +const json = (value, status = 200) => new Response(JSON.stringify(value), { status }) +function deferred() { + let resolve, reject + const promise = new Promise((r, j) => { resolve = r; reject = j }) + return { promise, resolve, reject } +} + +function fixture(overrides = {}) { + const calls = [] + let expired = 0 + const requests = { + status: async (id) => status(id), branches: async () => branches, log: async () => log, + diff: async (_id, selection) => ({ ...diff, side: selection.side }), ...overrides + } + const transport = Object.fromEntries(Object.entries(requests).map(([method, run]) => [method, (...args) => { + calls.push({ method, args, signal: args.at(-1) }) + return run(...args) + }])) + return { git: createWorkspaceGitView(transport, () => { expired++ }), calls, expired: () => expired } +} + +test('strict bootstrap gating; each Git method uses the four same-origin POST projections only', async () => { + const signal = new AbortController().signal + const steps = [ + ['GET', '/bootstrap', undefined, { ...bootstrap, capabilities: { gitInspect: 'true', workspaceFiles: true } }], + ['GET', '/bootstrap', undefined, { ...bootstrap, capabilities: { gitInspect: true, workspaceFiles: true } }], + ['POST', `/workspaces/${a}/git/status`, {}, { ...status(), hostPath: '/host/hidden' }], + ['POST', `/workspaces/${a}/git/branches`, {}, { ...branches, branches: branches.branches.map((branch) => ({ ...branch, upstream: 'hidden' })) }], + ['POST', `/workspaces/${a}/git/log`, { limit: 20 }, log], + ['POST', `/workspaces/${a}/git/diff`, { viewId, entryId, side: 'worktree' }, diff] + ] + const transport = createTransport(async (url, init) => { + const [method, route, body, result] = steps.shift() + assert.equal(url, `/api/v1${route}`) + assert.equal(init.method, method) + assert.deepEqual(init.body ? JSON.parse(init.body) : undefined, body) + assert.equal(init.credentials, 'same-origin') + assert.equal(init.mode, 'same-origin') + assert.equal(init.redirect, 'error') + assert.equal(init.cache, 'no-store') + assert.equal(init.headers.accept, 'application/json') + assert.ok(!url.includes(bootstrap.csrf)) + if (method === 'POST') { + assert.equal(init.signal, signal) + assert.equal(init.headers['x-deva-csrf'], bootstrap.csrf) + assert.equal(init.headers['content-type'], 'application/json') + assert.equal(init.referrerPolicy, 'same-origin') + assert.equal(init.headers.origin, undefined) // Browser appends Origin, not script input. + } + return json(result) + }) + assert.deepEqual((await transport.inspect()).bootstrap.capabilities, { workspaceFiles: true }) + assert.deepEqual((await transport.inspect()).bootstrap.capabilities, { workspaceFiles: true, gitInspect: true }) + const api = createGitViewTransport(transport, bootstrap.csrf) + assert.deepEqual(await api.status(a, signal), status()) + assert.deepEqual(await api.branches(a, signal), branches) + assert.deepEqual(await api.log(a, 20, signal), log) + assert.deepEqual(await api.diff(a, { viewId, entryId, side: 'worktree', path: rel, ref: 'HEAD', oid, args: ['--all'] }, signal), diff) + assert.deepEqual(steps, []) +}) + +test('transport rejects malformed scope, ids, pagination and cross-projection data', async () => { + const signal = new AbortController().signal + const responseQueue = [status(b), status(a, { viewId: 'host-file' }), status(a, { entries: [entry, entry] }), + { ...log, traversal: 'all-parents' }, { ...log, commits: [{ ...log.commits[0], oid: 'a'.repeat(64) }] }, + { ...diff, side: 'staged' }, { ...diff, lines: [{ ...diff.lines[0], type: 'command' }] }] + const api = createGitViewTransport(createTransport(async () => json(responseQueue.shift())), bootstrap.csrf) + const error = /Invalid Git inspection/ + for (const value of ['other', '/x', `${a}\n`, `${a}?secret=x`, `${a}/../git`, `${a}%2f`, `${a}#hash`]) await assert.rejects(api.status(value, signal), error) + for (const value of [0, -1, 1.5, 101, '20', undefined]) await assert.rejects(api.log(a, value, signal), error) + for (const selection of [{ viewId: `${viewId}\n`, entryId, side: 'staged' }, { viewId, entryId: '../path', side: 'staged' }, { viewId, entryId, side: 'HEAD' }]) + await assert.rejects(api.diff(a, selection, signal), error) + assert.equal(responseQueue.length, 7) + for (let i = 0; i < 3; i++) await assert.rejects(api.status(a, signal), error) + for (let i = 0; i < 2; i++) await assert.rejects(api.log(a, 20, signal), error) + for (let i = 0; i < 2; i++) await assert.rejects(api.diff(a, { viewId, entryId, side: 'worktree' }, signal), error) + assert.deepEqual(responseQueue, []) +}) + +test('the real workspace selector binds authorization without Git access on opening, selecting or locating files', async () => { + const files = filesController.createWorkspaceFiles({ + projects: async () => [{ id: a, name: 'A' }, { id: b, name: 'B' }], + list: async (_id, path) => ({ entries: path === '' ? [{ type: 'dir', path: 'docs', name: 'docs' }] : + [{ type: 'file', path: rel, name: rel.split('/').at(-1) }], writable: false }), + read: async () => ({ path: rel, kind: 'text', writable: false, content: 'A file', revision: 'old' }) + }) + const { git, calls } = fixture() + const close = bindWorkspaceGitView(git, files) + await git.open() + await files.loadProjects() + await files.select(foreign) + assert.equal(git.snapshot().workspaceId, undefined) + await files.select(a) + assert.equal(git.snapshot().workspaceId, a) + assert.deepEqual(calls, []) + await git.open() + assert.equal(git.snapshot().status.workspaceId, a) + assert.equal(await files.reveal(a, rel, new AbortController().signal), true) + await files.list('', true) + await files.select(a) + assert.deepEqual(calls.map(({ method }) => method), ['status']) + assert.equal(await files.reveal(b, rel, new AbortController().signal), true) + assert.equal(git.snapshot().open, false) + assert.equal(git.snapshot().status, undefined) + close() + assert.equal(git.snapshot().workspaceId, undefined) + assert.deepEqual(calls.map(({ method }) => method), ['status']) +}) + +test('each trusted control reads its own projection; the change list emits no Git reads of its own', async () => { + const { git, calls } = fixture() + git.selectWorkspace(a) + await git.refresh() + await git.branches() + await git.history() + await git.diff(entryId, 'staged') + assert.deepEqual(calls, []) + await git.open() + await git.open() + await git.branches() + assert.deepEqual(git.snapshot().branches, branches) + await git.history() + await git.history(true) + assert.equal(git.snapshot().limit, 40) + await git.diff(entryId, 'staged') // Wrong tab; no request. + git.changes() + await git.diff(`e_${'f'.repeat(32)}`, 'worktree') + await git.diff(entryId, 'HEAD') + await git.diff(entryId, 'staged') + assert.deepEqual(git.snapshot().diff, { ...diff, side: 'staged' }) + await git.diff(entryId, 'worktree') + assert.deepEqual(git.snapshot().diff, diff) + await git.refresh() + assert.equal(git.snapshot().selection, undefined) + assert.equal(git.snapshot().log, undefined) + assert.deepEqual(calls.map(({ method, args }) => [method, ...args.slice(0, -1)]), [ + ['status', a], ['branches', a], ['log', a, 20], ['log', a, 40], + ['diff', a, { viewId, entryId, side: 'staged' }], ['diff', a, { viewId, entryId, side: 'worktree' }], ['status', a] + ]) + await git.history() + for (let i = 0; i < 8; i++) await git.history(true) + assert.deepEqual(calls.filter(({ method }) => method === 'log').slice(2).map(({ args }) => args[1]), [20, 40, 60, 80, 100]) +}) + +test('switches, departure and latest views abort immediately and discard late data or auth errors', async () => { + const old = deferred(), pendingBranches = deferred(), pendingDiff = deferred(), pendingLog = deferred() + const f = fixture({ status: async (id) => id === a ? old.promise : status(b), + branches: async () => pendingBranches.promise, diff: async () => pendingDiff.promise, log: async () => pendingLog.promise }) + f.git.selectWorkspace(a) + const first = f.git.open() + f.git.selectWorkspace(b) + assert.equal(f.calls[0].signal.aborted, true) + await f.git.open() + old.resolve(status(a)) + await first + assert.equal(f.git.snapshot().status.workspaceId, b) + const readingBranches = f.git.branches() + const readingLog = f.git.history() + assert.equal(f.calls[2].signal.aborted, true) + pendingBranches.reject(new HttpFailure(401, 'auth')) + await readingBranches + assert.equal(f.expired(), 0) + assert.equal(f.git.snapshot().tab, 'history') + pendingLog.resolve(log) + await readingLog + f.git.changes() + const readingDiff = f.git.diff(entryId, 'worktree') + f.git.selectWorkspace(undefined) // same reset as logout, capability/authority loss or modal departure + assert.equal(f.calls.at(-1).signal.aborted, true) + pendingDiff.resolve(diff) + await readingDiff + assert.equal(f.git.snapshot().workspaceId, undefined) + assert.equal(f.git.snapshot().diff, undefined) + assert.equal(f.git.snapshot().status, undefined) + assert.equal(f.git.snapshot().open, false) +}) + +test('an expired view invalidates exact diff authority and only a manual refresh issues a new status request', async () => { + let states = 0, diffs = 0 + const { git, calls } = fixture({ status: async () => status(a, { viewId: ++states === 1 ? viewId : nextViewId }), + diff: async () => { if (++diffs === 1) throw new HttpFailure(409, 'git_stale'); return diff } }) + git.selectWorkspace(a) + await git.open() + await git.diff(entryId, 'worktree') + assert.equal(git.snapshot().issue, 'stale') + assert.equal(git.snapshot().diff, undefined) + assert.equal(git.snapshot().status.viewId, null) + await git.diff(entryId, 'worktree') + await git.branches() + assert.deepEqual(calls.map(({ method }) => method), ['status', 'diff']) + await git.refresh() + assert.equal(git.snapshot().issue, undefined) + assert.equal(git.snapshot().diff, undefined) + assert.deepEqual(calls.map(({ method }) => method), ['status', 'diff', 'status']) + await git.diff(entryId, 'worktree') + assert.equal(calls.at(-1).args[1].viewId, nextViewId) + assert.deepEqual(git.snapshot().diff, diff) +}) + +test('origin, authentication, grant, repository conditions, resource limits and busy are distinct', async () => { + for (const [statusCode, code, issue, expires] of [[401, 'auth', 'auth', 1], [403, 'origin', 'origin', 0], [403, 'csrf_failed', 'csrf', 0], + [403, 'git_not_granted', 'not_granted', 0], [404, 'workspace_unavailable', 'workspace_unavailable', 0], [403, 'git_unsafe', 'unsafe', 0], + [413, 'git_limit', 'budget', 0], [503, 'git_timeout', 'budget', 0], [409, 'git_busy', 'busy', 0], + [422, 'unsupported_git_layout', 'unsupported_layout', 0], [422, 'git_corrupt', 'incomplete', 0], [503, 'git_unavailable', 'unavailable', 0]]) { + const f = fixture({ diff: async () => { throw new HttpFailure(statusCode, code) } }) + f.git.selectWorkspace(a) + await f.git.open() + await f.git.diff(entryId, 'worktree') + assert.equal(f.git.snapshot().issue, issue) + assert.equal(f.expired(), expires) + assert.equal(f.git.snapshot().diff, undefined) + assert.equal(f.git.snapshot().status?.viewId, statusCode < 409 ? undefined : viewId) + assert.deepEqual(f.calls.map(({ method }) => method), ['status', 'diff']) + } + for (const state of ['not_repo', 'unsupported_layout', 'unavailable']) { + const { git, calls } = fixture({ status: async () => status(a, { state, entries: [], viewId: null }) }) + git.selectWorkspace(a) + await git.open() + assert.equal(git.snapshot().status.state, state) + await git.branches() + await git.history() + await git.diff(entryId, 'staged') + assert.deepEqual(calls.map(({ method }) => method), ['status']) + } +}) + +const React = require('react') +const { renderToStaticMarkup } = require('react-dom/server') +const { WorkspaceGitPanel } = await load('git-view-panel.tsx', { + '../renderer/src/i18n/i18n': { useI18n: () => ({ locale: 'en', t: (key) => key }) }, + '../renderer/src/redesign/GitBranchPill': await load('../renderer/src/redesign/GitBranchPill.tsx'), + './git-view-copy': await load('git-view-copy.ts'), './git-view-controller': gitController, './git-view-transport': gitTransport, + './git-view.css': {} +}) +const render = (controller, workspaceId = a) => renderToStaticMarkup(React.createElement(WorkspaceGitPanel, { workspaceId, controller })) + +test('the real panel renders scoped read-only text, repository states, and escaped desktop-style results', async () => { + const { git } = fixture() + git.selectWorkspace(a) + assert.match(render(git), /class="cf-gitchip wb-git__toggle"/) + assert.doesNotMatch(render(git), /workspace-git-panel/) + assert.equal(render(git, b), '') + await git.open() + assert.match(render(git), /Git · Read-only.*SHA-1.*tracked changes only.*first parents.*local cache.*unknown/s) + assert.match(render(git), new RegExp(`data-testid="workspace-git-entry-${entryId}"`)) + await git.branches() + assert.match(render(git), /Cached locally/) + assert.match(render(git), /aria-current="true".*main/s) + await git.history() + assert.match(render(git), /workspace-git-load-more/) + assert.match(render(git), /<script>alert\(1\)<\/script>/) + git.changes() + await git.diff(entryId, 'worktree') + assert.match(render(git), /diffview__line (hunk|del|add|ctx)/) + assert.match(render(git), /<img src=x>/) + assert.match(render(git), /The diff was truncated/) + assert.doesNotMatch(render(git), /|