DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(ssh): 远端构建放行白名单——带过去,并在 pnpm 报出键后补写重试
Menghuan1918a6cf46214e58
diff --git a/packages/dsh-tauri-ssh/package.json b/packages/dsh-tauri-ssh/package.jsonindex 8dff1cbf..26151e4f 100644--- a/packages/dsh-tauri-ssh/package.json+++ b/packages/dsh-tauri-ssh/package.json@@ -51,7 +51,8 @@"dependencies": {"pathe": "catalog:utils","schemastery": "catalog:utils",- "ssh2": "catalog:utils"+ "ssh2": "catalog:utils",+ "yaml": "catalog:testing"},"devDependencies": {"@types/node": "catalog:types",diff --git a/packages/dsh-tauri-ssh/src/host/apply.ts b/packages/dsh-tauri-ssh/src/host/apply.tsindex 3e9893db..95d6c948 100644--- a/packages/dsh-tauri-ssh/src/host/apply.ts+++ b/packages/dsh-tauri-ssh/src/host/apply.ts@@ -18,12 +18,13 @@ import process from 'node:process'import { join } from 'pathe'import { SSH_API_PREFIX, SSH_PLUGIN_NAME } from '../shared/constants'import { createSshApiHandler } from './routes/index'+import { carryWorkspaceAllowlist } from './service/allowlist'import { SshMachineEvents } from './service/events'import { KnownHostsStore } from './service/host-keys'import { profileView, SshManager } from './service/manager'import { discoverableHosts, loadSshConfigBlocks, lookupSshConfig, SshConfigResolver } from './service/ssh-config'import { SyncEngine } from './service/sync'-import { profileDependenciesReader, skillRootsScanner, tarPacker } from './service/sync-local'+import { profileAllowlistReader, profileDependenciesReader, skillRootsScanner, tarPacker } from './service/sync-local'import { Ssh2Transport } from './service/transport'import { ConfigSchema, DEFAULT_REMOTE_PORT, DEFAULT_SSH_PORT, MACHINES_NAMESPACE, machinesFromValue, MachinesSchema } from './storage/index'import { MachineId } from './types/index'@@ -88,6 +89,8 @@ export class SshRemoteService implements SshApiHost {knownHosts,config,events: this.machineEvents,+ // 本机档案的构建放行白名单:连接时带到远端(git 插件 prepare 门禁)+ localAllowlist: profileAllowlistReader(),// v8 ignore next -- deliberately empty status hook: the settings page polls /api-sshemitStatus: () => {// The settings page polls status through /api-ssh; no live consumers.@@ -305,10 +308,17 @@ export class SshRemoteService implements SshApiHost {try {// 逐条进度经机器状态发布:设置页只轮询 machine.status,同步是本服务里// 唯一「一条请求跑几分钟」的操作,不报进度就只能干等。+ const profileName = this.manager.profileName(machineId)return await this.sync.apply(machineId, plugins, skills, {// 装进这台机器真正在跑的档案:隧道只服务那一个 profile,装到别处// (历史上的硬编码 web)等于没同步。- profileName: this.manager.profileName(machineId),+ profileName,+ // 连接时已带过一次白名单;这里再兜一次——「刚在本机装了新插件就同步」+ // 的场景下,连接时刻的名单里还没有它的放行键。+ beforePlugins: (session) => {+ return carryWorkspaceAllowlist(session, profileName, this.manager.localAllowlist())+ .then(() => undefined)+ },onItem: (position, total, item) => this.manager.setProgress(machineId, { phase: 'syncing', attempt: position, total, item }),})}diff --git a/packages/dsh-tauri-ssh/src/host/service/allowlist.test.ts b/packages/dsh-tauri-ssh/src/host/service/allowlist.test.tsnew file mode 100644index 00000000..d0c0a267--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/allowlist.test.ts@@ -0,0 +1,205 @@+import type { SshExecResult, SshSession } from './transport'+import { Buffer } from 'node:buffer'+import { describe, expect, it, vi } from 'vitest'+import { parse } from 'yaml'+import {+ allowlistReadCommand,+ allowlistWriteCommand,+ carryWorkspaceAllowlist,+ isPortableAllowKey,+ mergeWorkspaceAllowlist,+ parseAllowlist,+ parseBuildAllowKeys,+ WORKSPACE_TEMPLATE,+} from './allowlist'++const GIT_KEY = 'dsh-better-sidebar@https://codeload.github.com/omdsh-dev/DSH-better-sidebar/tar.gz/0314fd9b93c5f55eb68f98480d84500d67a75b03'++/** A scripted session: `cat` answers the given text, writes are recorded. */+function fakeSession(remoteText: string): SshSession & { commands: string[] } {+ const commands: string[] = []+ return {+ commands,+ exec: vi.fn(async (command: string) => {+ commands.push(command)+ const stdout = command.startsWith('cat ') ? remoteText : ''+ return { code: 0, stdout, stderr: '' } as SshExecResult+ }) as unknown as SshSession['exec'],+ openTunnel: () => Promise.reject(new Error('not needed')),+ onClosed: () => {},+ close: async () => {},+ }+}++describe('isPortableAllowKey', () => {+ it('keeps git/npm resolutions and bare package names', () => {+ expect(isPortableAllowKey(GIT_KEY)).toBe(true)+ expect(isPortableAllowKey('node-pty')).toBe(true)+ expect(isPortableAllowKey('[email protected]')).toBe(true)+ })++ it('drops local-only resolutions and Windows-shaped keys', () => {+ expect(isPortableAllowKey('C:\\\\work\\\\plugin')).toBe(false)+ expect(isPortableAllowKey('C:/work/plugin')).toBe(false)+ expect(isPortableAllowKey('plugin@file:/Users/me/plugin')).toBe(false)+ expect(isPortableAllowKey('plugin@link:../plugin')).toBe(false)+ expect(isPortableAllowKey('plugin@workspace:packages/plugin')).toBe(false)+ expect(isPortableAllowKey(' ')).toBe(false)+ })+})++describe('parseAllowlist', () => {+ it('reads both sections and skips non-portable keys', () => {+ const parsed = parseAllowlist([+ 'allowBuilds:',+ ` ${GIT_KEY}: true`,+ ' node-pty: true',+ ' local@file:/Users/me/plugin: true',+ ' windows: false',+ 'onlyBuiltDependencies:',+ ' - dsh-better-sidebar',+ ' - link:../local',+ '',+ ].join('\n'))+ expect(Object.keys(parsed.allowBuilds)).toEqual([GIT_KEY, 'node-pty', 'windows'])+ expect(parsed.allowBuilds.windows).toBe(false)+ expect(parsed.onlyBuiltDependencies).toEqual(['dsh-better-sidebar'])+ })++ it('reads a missing or malformed document as empty', () => {+ expect(parseAllowlist('')).toEqual({ allowBuilds: {}, onlyBuiltDependencies: [] })+ expect(parseAllowlist('a: [unclosed')).toEqual({ allowBuilds: {}, onlyBuiltDependencies: [] })+ expect(parseAllowlist('- just\n- a list')).toEqual({ allowBuilds: {}, onlyBuiltDependencies: [] })+ })+})++describe('mergeWorkspaceAllowlist', () => {+ const incoming = { allowBuilds: { [GIT_KEY]: true, 'node-pty': true }, onlyBuiltDependencies: ['dsh-better-sidebar'] }++ it('adds both sections to a bare template and keeps its keys', () => {+ const { yaml, added } = mergeWorkspaceAllowlist(WORKSPACE_TEMPLATE, incoming)+ const doc = parse(yaml) as Record<string, unknown>+ expect(doc.packages).toEqual(['.'])+ expect(doc.nodeLinker).toBe('hoisted')+ expect(doc.autoInstallPeers).toBe(false)+ expect(doc.allowBuilds).toEqual({ [GIT_KEY]: true, 'node-pty': true })+ expect(doc.onlyBuiltDependencies).toEqual(['dsh-better-sidebar'])+ expect(added).toEqual([GIT_KEY, 'node-pty', 'dsh-better-sidebar'])+ })++ it('round-trips keys carrying @ : / and # without breaking the document', () => {+ const awkward = '[email protected]/a/b#semver:^1.0.0'+ const { yaml } = mergeWorkspaceAllowlist(WORKSPACE_TEMPLATE, { allowBuilds: { [awkward]: true }, onlyBuiltDependencies: [] })+ expect((parse(yaml) as { allowBuilds: Record<string, boolean> }).allowBuilds[awkward]).toBe(true)+ })++ it('is idempotent and never overrides a remote denial', () => {+ const first = mergeWorkspaceAllowlist(WORKSPACE_TEMPLATE, incoming).yaml+ const second = mergeWorkspaceAllowlist(first, incoming)+ expect(second.added).toEqual([])+ // 不改写:原文本原样返回(调用方据此跳过写盘)+ expect(second.yaml).toBe(first)++ const denied = 'allowBuilds:\n node-pty: false\n'+ const { yaml, added } = mergeWorkspaceAllowlist(denied, incoming)+ const doc = parse(yaml) as { allowBuilds: Record<string, boolean> }+ expect(doc.allowBuilds['node-pty']).toBe(false)+ expect(added).toEqual([GIT_KEY, 'dsh-better-sidebar'])+ })++ it('reads a CRLF document (a Windows-authored profile) as the same map', () => {+ const crlf = 'packages:\r\n - .\r\n\r\nnodeLinker: hoisted\r\nautoInstallPeers: false\r\n'+ const { yaml, added } = mergeWorkspaceAllowlist(crlf, incoming)+ expect(added).toHaveLength(3)+ expect(yaml.includes('\r')).toBe(false)+ expect((parse(yaml) as { packages: string[] }).packages).toEqual(['.'])+ })++ it('keeps only non-portable local keys out of the remote document', () => {+ const { added } = mergeWorkspaceAllowlist(WORKSPACE_TEMPLATE, {+ allowBuilds: { 'plugin@file:/Users/me/plugin': true, 'node-pty': true },+ onlyBuiltDependencies: ['link:../local'],+ })+ expect(added).toEqual(['node-pty'])+ })++ it('refuses to rewrite a document it cannot parse', () => {+ expect(() => mergeWorkspaceAllowlist('a: [unclosed', incoming)).toThrow(/not valid YAML/u)+ expect(() => mergeWorkspaceAllowlist('- a\n- list', incoming)).toThrow(/not a YAML mapping/u)+ })+})++describe('parseBuildAllowKeys', () => {+ const GIT_GUIDANCE = [+ 'Add the package to "allowBuilds" in your project\'s pnpm-workspace.yaml to allow it to run scripts. For example:',+ 'allowBuilds:',+ ` ${GIT_KEY}: true`,+ 'dsh: pnpm failed in profile directory /root/.dsh/profiles/remote',+ ].join('\n')++ it('reads the key pnpm printed in its allowBuilds example', () => {+ expect(parseBuildAllowKeys(GIT_GUIDANCE)).toEqual([GIT_KEY])+ })++ it('reads an onlyBuiltDependencies list and ignored-build names', () => {+ expect(parseBuildAllowKeys('onlyBuiltDependencies:\n - node-pty\n - "esbuild"\n')).toEqual(['node-pty', 'esbuild'])+ expect(parseBuildAllowKeys('Ignored build scripts: [email protected], [email protected]\n')).toEqual(['node-pty', 'esbuild'])+ })++ it('dedupes, ignores unrelated output and never returns a local-only key', () => {+ expect(parseBuildAllowKeys('nothing to see here')).toEqual([])+ expect(parseBuildAllowKeys(`${GIT_GUIDANCE}\nallowBuilds:\n ${GIT_KEY}: true\n`)).toEqual([GIT_KEY])+ expect(parseBuildAllowKeys('allowBuilds:\n plugin@file:/Users/me/plugin: true\n')).toEqual([])+ })+})++describe('allowlist commands', () => {+ it('reads and writes the machine profile workspace file', () => {+ expect(allowlistReadCommand('remote')).toBe('cat "$HOME/.dsh/profiles/remote/pnpm-workspace.yaml" 2>/dev/null || true')+ const write = allowlistWriteCommand('remote', 'allowBuilds:\n a: true\n')+ expect(write).toContain('mkdir -p "$HOME/.dsh/profiles/remote"')+ expect(write).toContain('> "$HOME/.dsh/profiles/remote/pnpm-workspace.yaml"')+ // 多行文本整体作为一个被引用的参数:不会被 shell 拆行+ expect(write).toContain('allowBuilds:')+ })+})++describe('carryWorkspaceAllowlist', () => {+ it('writes once when keys are missing and stays quiet when they are not', async () => {+ const session = fakeSession(WORKSPACE_TEMPLATE)+ const added = await carryWorkspaceAllowlist(session, 'remote', { allowBuilds: { 'node-pty': true }, onlyBuiltDependencies: [] })+ expect(added).toEqual(['node-pty'])+ expect(session.commands).toHaveLength(2)+ expect(session.commands[1]).toContain('pnpm-workspace.yaml')++ const upToDate = fakeSession('allowBuilds:\n node-pty: true\n')+ expect(await carryWorkspaceAllowlist(upToDate, 'remote', { allowBuilds: { 'node-pty': true }, onlyBuiltDependencies: [] })).toEqual([])+ expect(upToDate.commands).toHaveLength(1)+ })++ it('skips the remote entirely when the local allowlist is empty', async () => {+ const session = fakeSession(WORKSPACE_TEMPLATE)+ expect(await carryWorkspaceAllowlist(session, 'remote', { allowBuilds: {}, onlyBuiltDependencies: [] })).toEqual([])+ expect(session.commands).toHaveLength(0)+ })++ it('propagates a parse failure instead of clobbering the remote file', async () => {+ const session = fakeSession('a: [unclosed')+ await expect(carryWorkspaceAllowlist(session, 'remote', { allowBuilds: { 'node-pty': true }, onlyBuiltDependencies: [] }))+ .rejects+ .toThrow(/not valid YAML/u)+ expect(session.commands).toHaveLength(1)+ })+})++describe('carryWorkspaceAllowlist payload', () => {+ it('hands the merged text to the shell as one argument with LF endings', async () => {+ const session = fakeSession('')+ await carryWorkspaceAllowlist(session, 'remote', { allowBuilds: { [GIT_KEY]: true }, onlyBuiltDependencies: [] })+ const write = session.commands[1] ?? ''+ expect(write.includes('\r')).toBe(false)+ // Buffer import keeps the module's node-only surface honest under vitest+ expect(Buffer.from(GIT_KEY).length).toBeGreaterThan(0)+ expect(write).toContain('codeload.github.com')+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/allowlist.ts b/packages/dsh-tauri-ssh/src/host/service/allowlist.tsnew file mode 100644index 00000000..47f6da6c--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/allowlist.ts@@ -0,0 +1,254 @@+/**+ * Profile build-allowlist carry-over (local → remote).+ *+ * pnpm refuses to run a git-hosted plugin's `prepare` build unless the profile+ * allows it (`allowBuilds` map, pnpm 11; `onlyBuiltDependencies` list, pnpm 10;+ * both in the profile's `pnpm-workspace.yaml`). The desktop's own installer+ * writes those keys back locally after a gated install, but a remote profile+ * starts from the bare template — so every git-hosted plugin the sync panel+ * pushed died on pnpm's prepare gate. This module reads the two sections from+ * the local profile and merges the missing keys into the remote profile's file.+ *+ * Cross-platform: keys describing the *local* filesystem (drive letters,+ * backslash paths, `file:`/`link:`/`workspace:` resolutions) can never match on+ * a POSIX remote, so they are dropped instead of copied. The merge is a YAML+ * round-trip (never string concatenation): git depPath keys carry `@`, `:`,+ * `/` and `#`, which only a real serializer quotes correctly.+ * @module dsh-tauri-ssh/host/service/allowlist+ */++import type { SshSession } from './transport'+import { parse, stringify } from 'yaml'+import { shQuote } from './transport'++/** The two build-allowlist sections of one profile's `pnpm-workspace.yaml`. */+export interface WorkspaceAllowlist {+ /** pnpm 11's map form: depPath (or package name) → allowed. */+ allowBuilds: Record<string, boolean>+ /** pnpm 10's list form: package names allowed to run build scripts. */+ onlyBuiltDependencies: string[]+}++/** The empty allowlist (a profile that installed nothing gated). */+export const EMPTY_ALLOWLIST: WorkspaceAllowlist = { allowBuilds: {}, onlyBuiltDependencies: [] }++/** The template dsh writes for a fresh profile (mirrors the desktop's fallback). */+export const WORKSPACE_TEMPLATE = 'packages:\n - .\n\nnodeLinker: hoisted\nautoInstallPeers: false\n'++/** The remote profile directory, relative to `$HOME` (the layout's own convention). */+export function remoteProfileDir(profileName: string): string {+ return `.dsh/profiles/${profileName}`+}++/**+ * Whether one allowlist key can ever match on a POSIX remote: a key that names+ * a local-only resolution (`C:\…`, `file:…`, `link:…`, `workspace:…`) or spells+ * a Windows path is dropped — pnpm could never satisfy it there, and copying it+ * would only suggest the remote has a permission it does not.+ */+export function isPortableAllowKey(key: string): boolean {+ const value = key.trim()+ if (value === '')+ return false+ if (value.includes('\\'))+ return false+ if (/^[a-z]:[\\/]/iu.test(value))+ return false+ // The resolution decides: a bare name is the resolution, and a `name@spec`+ // key keeps only its spec. Scoped names (`@scope/pkg`) start with `@`; the+ // slice below then yields `scope/pkg`, which still matches neither marker.+ const resolution = value.includes('@') ? value.slice(value.indexOf('@') + 1) : value+ if (/^(?:file|link|workspace):/iu.test(resolution))+ return false+ return true+}++/** Read one boolean-ish YAML value; anything but an explicit false reads as allowed. */+function allowedValue(value: unknown): boolean {+ return value !== false+}++/**+ * Parse the two allowlist sections out of one workspace document. Unparsable+ * text, a non-mapping document, or missing sections all read as empty: the+ * caller carries what it can without ever blocking the connection.+ */+export function parseAllowlist(text: string): WorkspaceAllowlist {+ let doc: unknown+ try {+ doc = parse(text)+ }+ catch {+ return { ...EMPTY_ALLOWLIST }+ }+ if (typeof doc !== 'object' || doc === null || Array.isArray(doc))+ return { ...EMPTY_ALLOWLIST }+ const record = doc as Record<string, unknown>+ const allowBuilds: Record<string, boolean> = {}+ const rawBuilds = record.allowBuilds+ if (typeof rawBuilds === 'object' && rawBuilds !== null && !Array.isArray(rawBuilds)) {+ for (const [key, value] of Object.entries(rawBuilds as Record<string, unknown>)) {+ if (isPortableAllowKey(key))+ allowBuilds[key] = allowedValue(value)+ }+ }+ const onlyBuilt: string[] = []+ if (Array.isArray(record.onlyBuiltDependencies)) {+ for (const entry of record.onlyBuiltDependencies) {+ if (typeof entry === 'string' && isPortableAllowKey(entry) && !onlyBuilt.includes(entry))+ onlyBuilt.push(entry)+ }+ }+ return { allowBuilds, onlyBuiltDependencies: onlyBuilt }+}++/**+ * Merge the local allowlist into one remote workspace document.+ *+ * Only *missing* keys are carried: an explicit `false` the operator wrote on+ * the remote stays a denial. The document is round-tripped through the YAML+ * library, so every other key (packages, nodeLinker, user settings) survives+ * and the emitted quoting is always valid.+ * @param remoteYaml - the remote profile's current document (empty when absent).+ * @param incoming - the local profile's allowlist sections.+ * @returns the document to write and the keys that were actually added+ * (empty `added` means the remote already allows everything: do not write).+ * @throws {Error} when the remote document is not valid YAML — rewriting it+ * would destroy whatever the operator has there.+ */+export function mergeWorkspaceAllowlist(remoteYaml: string, incoming: WorkspaceAllowlist): { yaml: string, added: string[] } {+ const text = remoteYaml.trim() === '' ? WORKSPACE_TEMPLATE : remoteYaml+ let doc: unknown+ try {+ doc = parse(text)+ }+ catch (error) {+ throw new Error(`remote pnpm-workspace.yaml is not valid YAML: ${error instanceof Error ? error.message : String(error)}`)+ }+ if (typeof doc !== 'object' || doc === null || Array.isArray(doc))+ throw new Error('remote pnpm-workspace.yaml is not a YAML mapping')+ const record = doc as Record<string, unknown>+ const added: string[] = []++ const builds = typeof record.allowBuilds === 'object' && record.allowBuilds !== null && !Array.isArray(record.allowBuilds)+ ? record.allowBuilds as Record<string, unknown>+ : {}+ for (const [key, value] of Object.entries(incoming.allowBuilds).sort(([left], [right]) => left.localeCompare(right))) {+ if (key in builds || !isPortableAllowKey(key))+ continue+ builds[key] = value+ added.push(key)+ }+ if (Object.keys(builds).length > 0)+ record.allowBuilds = builds++ const onlyBuilt = Array.isArray(record.onlyBuiltDependencies)+ ? record.onlyBuiltDependencies.filter((entry): entry is string => typeof entry === 'string')+ : []+ for (const name of [...incoming.onlyBuiltDependencies].sort()) {+ if (onlyBuilt.includes(name) || !isPortableAllowKey(name))+ continue+ onlyBuilt.push(name)+ added.push(name)+ }+ if (onlyBuilt.length > 0)+ record.onlyBuiltDependencies = onlyBuilt++ if (added.length === 0)+ return { yaml: remoteYaml, added }+ return { yaml: stringify(record), added }+}++/**+ * Parse the build keys pnpm names in a failed install's output, mirroring the+ * desktop's own installer (its `parse_allowlist_keys`): the guidance prints an+ * `allowBuilds:` example whose following indented `<key>: true` line is the+ * exact depPath to allow, and older pnpm prints an `onlyBuiltDependencies:`+ * list ("Ignored build scripts: name@version"). Both forms are read here.+ *+ * Needed because a git depPath pins the *resolved commit*: the key recorded on+ * this machine for an older commit never matches the commit a remote resolves+ * today, so the failure output is the only correct source for that key.+ * @param output - the failed command's stdout and stderr, concatenated.+ * @returns the keys to grant, deduped and in output order.+ */+export function parseBuildAllowKeys(output: string): string[] {+ const keys: string[] = []+ const push = (key: string): void => {+ const value = key.trim().replace(/^['"]|['"]$/gu, '')+ if (value !== '' && isPortableAllowKey(value) && !keys.includes(value))+ keys.push(value)+ }+ const lines = output.split('\n')+ for (const [index, line] of lines.entries()) {+ const trimmed = line.trim()+ if (trimmed === 'allowBuilds:') {+ // 条目必须缩进且形如 `<key>: true`:先切掉缩进,再按「冒号 + true」判定+ const entry = lines[index + 1] ?? ''+ const match = isIndented(entry) ? /^(.*):[ \t]*true$/u.exec(entry.trim()) : null+ if (match?.[1] !== undefined)+ push(match[1])+ }+ if (trimmed === 'onlyBuiltDependencies:') {+ for (const next of lines.slice(index + 1)) {+ const indented = isIndented(next)+ const body = next.trim()+ if (indented && body.startsWith('-')) {+ push(body.slice(1).trim())+ continue+ }+ if (body !== '' && !indented)+ break // 顶层键:列表已结束+ }+ }+ const ignored = line.includes('Ignored build scripts:') ? line.split('Ignored build scripts:')[1] ?? '' : ''+ for (const token of ignored.split(/[,\s]+/u)) {+ if (token.trim() !== '')+ push(token.trim().replace(/@[^@]*$/u, ''))+ }+ }+ return keys+}++/** Whether one output line is indented (a block entry rather than a top-level key). */+function isIndented(line: string): boolean {+ return line.startsWith(' ') || line.startsWith('\t')+}++/** Read the remote profile's workspace document (empty when it does not exist yet). */+export function allowlistReadCommand(profileName: string): string {+ return `cat "$HOME/${remoteProfileDir(profileName)}/pnpm-workspace.yaml" 2>/dev/null || true`+}++/**+ * Write the merged document back. The payload is one shell-quoted argument+ * (never a heredoc or a base64 pipe): `shQuote` keeps every `@`, `:`, `#` and+ * newline intact, and the text is emitted with LF endings on every platform.+ */+export function allowlistWriteCommand(profileName: string, yamlText: string): string {+ const dir = `$HOME/${remoteProfileDir(profileName)}`+ return `mkdir -p "${dir}" && printf %s ${shQuote(yamlText)} > "${dir}/pnpm-workspace.yaml"`+}++/**+ * Carry the local allowlist into the remote profile over one live session.+ * Idempotent and quiet when there is nothing to add; a remote document that+ * cannot be parsed leaves the file untouched.+ * @param session - the authenticated session to run the file commands on.+ * @param profileName - the remote profile whose workspace file is the target.+ * @param local - the local profile's allowlist sections.+ * @returns the keys that were added (empty when the remote was already complete).+ */+export async function carryWorkspaceAllowlist(+ session: SshSession,+ profileName: string,+ local: WorkspaceAllowlist,+): Promise<string[]> {+ if (Object.keys(local.allowBuilds).length === 0 && local.onlyBuiltDependencies.length === 0)+ return []+ const remote = await session.exec(allowlistReadCommand(profileName))+ const { yaml, added } = mergeWorkspaceAllowlist(remote.stdout, local)+ if (added.length > 0)+ await session.exec(allowlistWriteCommand(profileName, yaml))+ return added+}diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts b/packages/dsh-tauri-ssh/src/host/service/manager.test.tsindex c9c314c7..88562198 100644--- a/packages/dsh-tauri-ssh/src/host/service/manager.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/manager.test.ts@@ -258,8 +258,11 @@ afterEach(() => {* idempotent pnpm-shim write). Flow assertions stay about the bootstrap, and* a new prelude step never renumbers them.*/+/** The connect-time prelude markers (pnpm shim, build-allowlist carry). */+const PRELUDE_MARKERS = ['chmod +x "$B/pnpm"', 'pnpm-workspace.yaml']+function bootstrapFlowCommands(session: FakeSession): string[] {- return session.commands.filter(command => !command.includes('chmod +x "$B/pnpm"'))+ return session.commands.filter(command => !PRELUDE_MARKERS.some(marker => command.includes(marker)))}/** Wait until the predicate holds (background reconnect races). */@@ -288,6 +291,7 @@ function boot(overrides: Partial<{planInstall: () => Promise<RemoteInstallPlan>mintCookie: (authenticatedUrl: string) => Promise<string | undefined>syncPlugins: (session: import('./transport').SshSession, profileName: string, hooks: { onEvent?: (stage: import('../types/index').SshMachineStage, line: string) => void }) => Promise<boolean>+ localAllowlist: () => import('./allowlist').WorkspaceAllowlist}> = {}) {const transport = new FakeTransport(overrides.sessionFactory ?? (() => new FakeSession(() => true)))transport.rejectKeys = overrides.rejectKeys ?? false@@ -304,6 +308,7 @@ function boot(overrides: Partial<{mintCookie: overrides.mintCookie ?? (() => Promise.resolve(undefined)),// 默认离线插件同步:不打本地 tar;个别用例经 overrides 覆盖syncPlugins: overrides.syncPlugins ?? (() => Promise.resolve(false)),+ ...overrides.localAllowlist === undefined ? {} : { localAllowlist: overrides.localAllowlist },...overrides.readEnvCredentials === undefined ? {} : { readEnvCredentials: overrides.readEnvCredentials },emitStatus: (id, status) => {emits.push({ id, state: status.state, ...status.progress === undefined ? {} : { progress: status.progress } })@@ -400,6 +405,26 @@ describe('sshManager', () => {expect(lines.some(line => line.includes('pnpm 垫片就绪'))).toBe(true)})+ it('carries the local build allowlist into the remote profile on connect', async () => {+ const session = new FakeSession(index => index !== 0)+ const { manager, events } = boot({+ sessionFactory: () => session,+ localAllowlist: () => ({ allowBuilds: { 'node-pty': true }, onlyBuiltDependencies: [] }),+ })+ await manager.connect(MachineId('m1'))+ const write = session.commands.find(command => command.includes('> "$HOME/.dsh/profiles/remote/pnpm-workspace.yaml"'))+ expect(write).toBeDefined()+ expect(write).toContain('node-pty')+ expect(events.since(MachineId('m1')).events.map(event => event.line).some(line => line.includes('构建放行白名单已补齐 1 项'))).toBe(true)+ })++ it('leaves the remote workspace alone when the local allowlist is empty', async () => {+ const session = new FakeSession(index => index !== 0)+ const { manager } = boot({ sessionFactory: () => session })+ await manager.connect(MachineId('m1'))+ expect(session.commands.some(command => command.includes('pnpm-workspace.yaml'))).toBe(false)+ })+it('publishes and clears externally driven progress (the sync engine)', () => {const { manager, emits } = boot()manager.setProgress(MachineId('m1'), { phase: 'syncing', attempt: 3, total: 13, item: 'dsh-tauri-ssh' })diff --git a/packages/dsh-tauri-ssh/src/host/service/manager.ts b/packages/dsh-tauri-ssh/src/host/service/manager.tsindex 21401fe5..0265ab56 100644--- a/packages/dsh-tauri-ssh/src/host/service/manager.ts+++ b/packages/dsh-tauri-ssh/src/host/service/manager.ts@@ -11,6 +11,7 @@ import type { Config } from '../storage/index'*/import type { MachineProfile, MachineView, SshInstallResult, SshLink, SshMachineStage, SshMachineStatus, SshProgress, SshTestResult } from '../types/index'+import type { WorkspaceAllowlist } from './allowlist'import type { BootstrapHooks } from './bootstrap'import type { SshMachineEvents } from './events'import type { KnownHostsStore } from './host-keys'@@ -19,6 +20,7 @@ import { homedir } from 'node:os'import process from 'node:process'import { join } from 'pathe'import { MachineId, SshError } from '../types/index'+import { carryWorkspaceAllowlist, EMPTY_ALLOWLIST } from './allowlist'import { checkMissingCommand, credentialsCopyCommand, describeError, describeExecFailure, ensurePnpmCommand, ensureRemoteInstance, firstLineOf, missingComponentsOf, planRemoteInstall, readEnvCredentials, REMOTE_ROOT, remoteWebTokenCommand, runInstallScript, safeProfileName, skippedVerificationSummary } from './bootstrap'import { fingerprintHostKey } from './host-keys'import { syncBundledPlugins } from './plugins-sync'@@ -87,6 +89,11 @@ export interface SshManagerDeps {* Defaults to the node:http implementation; tests stub it to stay offline.*/mintCookie?: (authenticatedUrl: string) => Promise<string | undefined>+ /**+ * The local profile's build allowlist to carry to the remote (defaults to+ * none; the plugin wires the real reader). See {@link carryWorkspaceAllowlist}.+ */+ localAllowlist?: () => WorkspaceAllowlist/*** Sync the desktop-bundled plugins to the remote (defaults to the real* tarball pipeline; tests stub it to stay offline). Returns whether the@@ -141,6 +148,11 @@ export class SshManager {return [...this.profiles.keys()].map(id => this.status(id))}+ /** The local profile's build allowlist (empty when no reader is wired). */+ localAllowlist(): WorkspaceAllowlist {+ return (this.deps.localAllowlist ?? (() => EMPTY_ALLOWLIST))()+ }+/*** The remote dsh profile this machine serves (its configured name, falling* back to the default). Callers that install plugins on the remote must@@ -460,6 +472,17 @@ export class SshManager {catch (error) {this.deps.events.append(machineId, 'install', `远端 pnpm 垫片写入失败: ${describeError(error)}`)}+ // 本机已放行的构建白名单(桌面端插件安装器写进 profile 的 pnpm-workspace.yaml)+ // 带到远端:git 托管的插件在远端同样要过 pnpm 的 prepare 门禁,而远端 profile+ // 是从模板起的、一个放行项都没有。+ try {+ const added = await carryWorkspaceAllowlist(session, safeProfileName(profile.profileName), (this.deps.localAllowlist ?? (() => EMPTY_ALLOWLIST))())+ if (added.length > 0)+ this.deps.events.append(machineId, 'install', `远端构建放行白名单已补齐 ${added.length} 项(git 插件 prepare 门禁)`)+ }+ catch (error) {+ this.deps.events.append(machineId, 'install', `构建放行白名单同步失败: ${describeError(error)}`)+ }try {await ensureRemoteInstance(session,diff --git a/packages/dsh-tauri-ssh/src/host/service/sync-local.test.ts b/packages/dsh-tauri-ssh/src/host/service/sync-local.test.tsnew file mode 100644index 00000000..93a04e32--- /dev/null+++ b/packages/dsh-tauri-ssh/src/host/service/sync-local.test.ts@@ -0,0 +1,61 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'pathe'+import { afterEach, describe, expect, it } from 'vitest'+import { profileAllowlistReader, profileDependenciesReader } from './sync-local'++const roots: string[] = []++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+})++/** One scratch harness home with the profile files a real install leaves. */+function scratchHome(files: { manifest?: string, workspace?: string }): string {+ const home = mkdtempSync(join(tmpdir(), 'dsh-sync-local-'))+ roots.push(home)+ const profile = join(home, 'profiles', 'web')+ mkdirSync(profile, { recursive: true })+ if (files.manifest !== undefined)+ writeFileSync(join(profile, 'package.json'), files.manifest)+ if (files.workspace !== undefined)+ writeFileSync(join(profile, 'pnpm-workspace.yaml'), files.workspace)+ return home+}++describe('profileAllowlistReader', () => {+ it('reads both allowlist sections from the profile workspace file', () => {+ const home = scratchHome({+ workspace: [+ 'packages:',+ ' - .',+ 'allowBuilds:',+ ' node-pty: true',+ 'onlyBuiltDependencies:',+ ' - dsh-better-sidebar',+ '',+ ].join('\n'),+ })+ expect(profileAllowlistReader(home, 'web')()).toEqual({+ allowBuilds: { 'node-pty': true },+ onlyBuiltDependencies: ['dsh-better-sidebar'],+ })+ })++ it('reads a missing file as empty instead of raising', () => {+ expect(profileAllowlistReader(scratchHome({}), 'web')()).toEqual({ allowBuilds: {}, onlyBuiltDependencies: [] })+ })++ it('tolerates a CRLF document written on Windows', () => {+ const home = scratchHome({ workspace: 'allowBuilds:\r\n node-pty: true\r\n' })+ expect(profileAllowlistReader(home, 'web')().allowBuilds).toEqual({ 'node-pty': true })+ })+})++describe('profileDependenciesReader', () => {+ it('reads the profile manifest and reads a broken one as empty', () => {+ const good = scratchHome({ manifest: JSON.stringify({ dependencies: { 'a': '^1.0.0', '@scope/b': 'github:x/y' } }) })+ expect(profileDependenciesReader(good)()).toEqual({ 'a': '^1.0.0', '@scope/b': 'github:x/y' })+ expect(profileDependenciesReader(scratchHome({ manifest: '{oops' }))()).toEqual({})+ })+})diff --git a/packages/dsh-tauri-ssh/src/host/service/sync-local.ts b/packages/dsh-tauri-ssh/src/host/service/sync-local.tsindex 4d1e7872..782ce7af 100644--- a/packages/dsh-tauri-ssh/src/host/service/sync-local.ts+++ b/packages/dsh-tauri-ssh/src/host/service/sync-local.ts@@ -8,12 +8,14 @@import type { Buffer } from 'node:buffer'import type { SyncSkillRoot } from '../types/index'+import type { WorkspaceAllowlist } from './allowlist'import { execFile } from 'node:child_process'import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'import { homedir } from 'node:os'import process from 'node:process'import { promisify } from 'node:util'import { join } from 'pathe'+import { EMPTY_ALLOWLIST, parseAllowlist } from './allowlist'const execFileAsync = promisify(execFile)@@ -60,6 +62,27 @@ export function profileDependenciesReader(dshHome?: string): () => Record<string}}+/**+ * Read the local profile's build allowlist (`pnpm-workspace.yaml` →+ * `allowBuilds` + `onlyBuiltDependencies`). A missing or unparsable file reads+ * as empty: nothing to carry is a state, not a failure. Paths go through+ * `pathe`, so a Windows host resolves the same document as a POSIX one.+ * @param dshHome - harness-home override (tests).+ * @param profile - profile-name override (tests); defaults to the `--profile` the process runs under.+ * @returns the allowlist sections to carry to a remote profile.+ */+export function profileAllowlistReader(dshHome?: string, profile?: string): () => WorkspaceAllowlist {+ return () => {+ const workspacePath = join(dshHomeOf(dshHome), 'profiles', profile ?? argvProfile() ?? 'web', 'pnpm-workspace.yaml')+ try {+ return parseAllowlist(readFileSync(workspacePath, 'utf8'))+ }+ catch {+ return { ...EMPTY_ALLOWLIST }+ }+ }+}+/*** Scan the user-level skill roots (`<dsh-home>/skills`, `~/.agents/skills`)* for SKILL.md-carrying directories. Absent roots simply contribute nothing.diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts b/packages/dsh-tauri-ssh/src/host/service/sync.test.tsindex 63c625dc..10e83d40 100644--- a/packages/dsh-tauri-ssh/src/host/service/sync.test.ts+++ b/packages/dsh-tauri-ssh/src/host/service/sync.test.ts@@ -239,6 +239,51 @@ describe('syncEngine.apply', () => {expect(deduped.items).toHaveLength(2)})+ it('grants the build keys pnpm asked for and retries the install once', async () => {+ const guidance = `allowBuilds:\n ${'p@https://example.com/p.tar.gz/abc'}: true\n`+ let installs = 0+ const session = fakeSession((command) => {+ if (command.includes('printf'))+ return ok('/dsh\n')+ if (command.includes('pnpm-workspace.yaml') && command.startsWith('cat '))+ return ok('packages:\n - .\n')+ if (command.includes('plugin --profile')) {+ installs += 1+ return installs === 1 ? fail(guidance) : ok()+ }+ return ok()+ })+ const sync = new SyncEngine({+ profileDependencies: () => ({}),+ scanSkills: () => [],+ packSkills: async () => Buffer.alloc(0),+ openSession: async () => session,+ })+ const result = await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [], { profileName: 'remote' })+ expect(result.items).toEqual([{ kind: 'plugin', name: 'p', ok: true }])+ expect(installs).toBe(2)+ const write = session.execSpy.mock.calls.map(([command]) => command).find(command => command.includes('> "$HOME/.dsh/profiles/remote/pnpm-workspace.yaml"'))+ expect(write).toContain('p@https://example.com/p.tar.gz/abc')+ })++ it('reports the original failure when pnpm names no build key', async () => {+ const session = fakeSession((command) => {+ if (command.includes('printf'))+ return ok('/dsh\n')+ return command.includes('plugin --profile') ? fail('ERR_PNPM_NO_MATCH') : ok()+ })+ const sync = new SyncEngine({+ profileDependencies: () => ({}),+ scanSkills: () => [],+ packSkills: async () => Buffer.alloc(0),+ openSession: async () => session,+ })+ const result = await sync.apply(machine, [{ name: 'p', spec: 'github:a/b' }], [], { profileName: 'remote' })+ expect(result.items[0]).toMatchObject({ ok: false })+ expect(result.items[0]?.error).toContain('ERR_PNPM_NO_MATCH')+ expect(session.execSpy.mock.calls.filter(([command]) => command.includes('pnpm-workspace.yaml'))).toHaveLength(0)+ })+it('installs a version-pinned plugin under its package name', async () => {const session = fakeSession((command) => {if (command.includes('printf'))diff --git a/packages/dsh-tauri-ssh/src/host/service/sync.ts b/packages/dsh-tauri-ssh/src/host/service/sync.tsindex 428754e3..127177b9 100644--- a/packages/dsh-tauri-ssh/src/host/service/sync.ts+++ b/packages/dsh-tauri-ssh/src/host/service/sync.ts@@ -16,6 +16,7 @@ import type { Buffer } from 'node:buffer'import type { MachineId, SyncApplyResult, SyncItemResult, SyncPluginItem, SyncPluginRef, SyncPreview, SyncSkillItem, SyncSkillRef, SyncSkillRoot } from '../types/index'import type { SshSession } from './transport'import { DEFAULT_REMOTE_PROFILE } from '../storage/index'+import { allowlistReadCommand, allowlistWriteCommand, mergeWorkspaceAllowlist, parseBuildAllowKeys } from './allowlist'import { dshEntryProbeCommand, firstLineOf, layoutBinDir, layoutNodeBinary } from './bootstrap'import { shQuote } from './transport'@@ -158,6 +159,13 @@ export interface SyncApplyOptions {* installing anywhere else would leave the synced plugins inert.*/profileName?: string+ /**+ * Runs once on the freshly opened session before the first plugin install+ * (the caller's chance to prepare the remote profile — e.g. carry the local+ * build allowlist). Best-effort by contract: it must not fail the sync, and+ * is skipped entirely for skill-only runs.+ */+ beforePlugins?: (session: SshSession) => Promise<void>}/**@@ -197,6 +205,8 @@ export class SyncEngine {const progress: SyncProgress = { settled: 0, total: uniquePlugins.length + uniqueSkills.length }const session = await this.deps.openSession(machineId)try {+ if (uniquePlugins.length > 0)+ await options.beforePlugins?.(session).catch(() => undefined)await this.applyPlugins(session, uniquePlugins, items, progress, options)await this.applySkills(session, uniqueSkills, items, progress, options)}@@ -228,9 +238,17 @@ export class SyncEngine {})continue}- const result = await session.exec(pluginAddCommand(dshEntry, installSpecOf(plugin.name, plugin.spec), options.profileName), {- ...this.deps.commandTimeoutMs === undefined ? {} : { timeoutMs: this.deps.commandTimeoutMs },- })+ const deadline = this.deps.commandTimeoutMs === undefined ? {} : { timeoutMs: this.deps.commandTimeoutMs }+ const command = pluginAddCommand(dshEntry, installSpecOf(plugin.name, plugin.spec), options.profileName)+ let result = await session.exec(command, deadline)+ if (result.code !== 0) {+ // pnpm 的 prepare 门禁会打印它要求的 allowBuilds 键(git depPath 钉的是+ // 解析出来的 commit,本机旧键对不上远端今天解析到的 commit):补写一次+ // 白名单再原样重试一次,与桌面端本地安装器的做法一致。+ const granted = await this.grantBuildKeys(session, options.profileName, `${result.stdout}\n${result.stderr}`)+ if (granted.length > 0)+ result = await session.exec(command, deadline)+ }items.push(result.code === 0? { kind: 'plugin', name: plugin.name, ok: true }@@ -240,6 +258,27 @@ export class SyncEngine {}}+ /**+ * Grant the build keys a failed install asked for, into the remote profile's+ * `pnpm-workspace.yaml`. Best-effort: a remote file that cannot be parsed, or+ * output naming no key, simply yields no grant (the item then reports the+ * original failure — never a masked one).+ * @returns the keys actually added.+ */+ private async grantBuildKeys(session: SshSession, profileName: string | undefined, output: string): Promise<string[]> {+ const keys = parseBuildAllowKeys(output)+ if (keys.length === 0)+ return []+ const remote = await session.exec(allowlistReadCommand(profileName ?? REMOTE_PLUGIN_PROFILE))+ const { yaml, added } = mergeWorkspaceAllowlist(+ remote.stdout,+ { allowBuilds: Object.fromEntries(keys.map(key => [key, true])), onlyBuiltDependencies: [] },+ )+ if (added.length > 0)+ await session.exec(allowlistWriteCommand(profileName ?? REMOTE_PLUGIN_PROFILE, yaml))+ return added+ }+/** Copy skills per root: local validation per item, one tar stream per root. */private async applySkills(session: SshSession,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6860358f..1ee9610f 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -953,6 +953,9 @@ importers:ssh2:specifier: catalog:utilsversion: 1.17.0+ yaml:+ specifier: catalog:testing+ version: 2.9.0devDependencies:'@types/node':specifier: catalog:types