fix(adapters): restore IM /projects beyond the default project (#1191)

Since v0.5.1 every IM channel listed only the default project. All five
adapters passed the default work dir to AdapterHttpClient as the sole
allowed project root, so listRecentProjects filtered out everything else;
matchProject, listSessions, sessionExists, createSession and listSkills
were clamped the same way. Feishu is where it was reported, but telegram,
wechat, dingtalk and whatsapp were identical.

defaultWorkDir is documented as where a new IM session starts, not as an
access boundary. Using it as the boundary failed both ways: configured, it
hid every other project; blank, it falls back to PWD/cwd(), which is "/"
for a GUI-launched sidecar, so the boundary allowed the whole filesystem.

Split the two concepts. allowedProjectRoots is now its own setting (global,
per-platform, or ADAPTER_ALLOWED_PROJECT_ROOTS), resolved together with the
work dir by resolveAdapterWorkspace so the default project is always inside
the boundary and /new cannot fail on inconsistent config. The default is the
home directory; it refuses to inherit "/" or any ancestor of home. Pairing
remains the primary authorization control, so unusable roots warn and fall
back rather than locking the bot out.

All five entrypoints now build their client through createAdapterClient
instead of repeating the wiring, which is what let one defect appear in five
places at once.

Known gap, left for a follow-up: a project outside the boundary is still
reported as "not found" rather than "outside the allowed directories".
This commit is contained in:
程序员阿江(Relakkes)
2026-08-05 23:38:30 +08:00
parent 8d38020fda
commit 94168b3b57
23 changed files with 864 additions and 31 deletions
@@ -0,0 +1,169 @@
import { afterEach, describe, expect, it, mock } from 'bun:test'
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
import { fileURLToPath } from 'node:url'
import { createAdapterClient } from '../adapter-client.js'
import { loadConfig } from '../config.js'
const ADAPTERS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
const PLATFORMS = ['telegram', 'feishu', 'wechat', 'dingtalk', 'whatsapp'] as const
const HOME = fs.realpathSync(os.homedir())
const ORIGINAL_ENV = {
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR,
ADAPTER_ALLOWED_PROJECT_ROOTS: process.env.ADAPTER_ALLOWED_PROJECT_ROOTS,
ADAPTER_DEFAULT_PROJECT_DIR: process.env.ADAPTER_DEFAULT_PROJECT_DIR,
CLAUDE_ADAPTER_DEFAULT_WORK_DIR: process.env.CLAUDE_ADAPTER_DEFAULT_WORK_DIR,
PWD: process.env.PWD,
}
const ORIGINAL_CWD = process.cwd()
const ORIGINAL_FETCH = globalThis.fetch
afterEach(() => {
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
if (value === undefined) delete process.env[key]
else process.env[key] = value
}
process.chdir(ORIGINAL_CWD)
globalThis.fetch = ORIGINAL_FETCH
})
/** Boot an adapter config from a throwaway config dir with a clean env. */
function bootConfig(file: Record<string, unknown>): ReturnType<typeof loadConfig> {
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-client-cfg-'))
fs.writeFileSync(path.join(configDir, 'adapters.json'), JSON.stringify(file))
process.env.CLAUDE_CONFIG_DIR = configDir
delete process.env.ADAPTER_ALLOWED_PROJECT_ROOTS
delete process.env.ADAPTER_DEFAULT_PROJECT_DIR
delete process.env.CLAUDE_ADAPTER_DEFAULT_WORK_DIR
return loadConfig()
}
/** What the bot would actually show for /projects, given what the server returns. */
async function listedProjects(
client: { listRecentProjects: () => Promise<{ projectName: string }[]> },
projects: { projectName: string; realPath: string }[],
): Promise<string[]> {
globalThis.fetch = mock(() => Promise.resolve(Response.json({ projects }))) as any
return (await client.listRecentProjects()).map((p) => p.projectName)
}
describe('createAdapterClient', () => {
// The regression that started #1191, now pinned behaviourally rather than by
// grepping the entrypoints.
it('keeps every project under home reachable when a default project is set', async () => {
const base = fs.mkdtempSync(path.join(HOME, '.cc-haha-test-'))
const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-haha-outside-'))
try {
const myApp = path.join(base, 'work', 'my-app')
const sibling = path.join(base, 'side', 'blog')
for (const dir of [myApp, sibling]) fs.mkdirSync(dir, { recursive: true })
for (const platform of PLATFORMS) {
const config = bootConfig({ defaultProjectDir: myApp })
const { httpClient, defaultWorkDir } = createAdapterClient(config, config[platform])
expect(defaultWorkDir).toBe(fs.realpathSync(myApp))
const names = await listedProjects(httpClient, [
{ projectName: 'my-app', realPath: myApp },
{ projectName: 'blog', realPath: sibling },
{ projectName: 'not-mine', realPath: outside },
])
expect(names).toEqual(['my-app', 'blog'])
}
} finally {
fs.rmSync(base, { recursive: true, force: true })
fs.rmSync(outside, { recursive: true, force: true })
}
})
// A GUI-launched sidecar inherits cwd "/" (Electron passes no cwd). Inheriting
// that as a boundary would allow the whole filesystem while the docs and the
// settings UI both promise "your home directory".
it('never inherits a filesystem root as the boundary', async () => {
process.chdir('/')
delete process.env.PWD
for (const platform of PLATFORMS) {
const config = bootConfig({})
const { httpClient, defaultWorkDir } = createAdapterClient(config, config[platform])
const names = await listedProjects(httpClient, [
{ projectName: 'etc', realPath: '/etc' },
{ projectName: 'home-project', realPath: HOME },
])
expect(names).toEqual(['home-project'])
expect(defaultWorkDir).toBe(HOME)
}
})
// Narrowing the roots must not brick /new: the client rejects a workDir outside
// the boundary, and every adapter passes defaultWorkDir straight to createSession.
it('always yields a default work dir inside the allowed roots', async () => {
const allowed = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-haha-allowed-'))
const elsewhere = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-haha-elsewhere-'))
try {
process.chdir('/')
delete process.env.PWD
for (const platform of PLATFORMS) {
// Boundary narrowed to one dir, default project pointing somewhere else.
const config = bootConfig({ allowedProjectRoots: [allowed], defaultProjectDir: elsewhere })
const { httpClient, defaultWorkDir } = createAdapterClient(config, config[platform])
expect(defaultWorkDir).toBe(fs.realpathSync(allowed))
globalThis.fetch = mock(() => Promise.resolve(Response.json({ sessionId: 'ok' }))) as any
await expect(httpClient.createSession(defaultWorkDir)).resolves.toBe('ok')
}
} finally {
fs.rmSync(allowed, { recursive: true, force: true })
fs.rmSync(elsewhere, { recursive: true, force: true })
}
})
it('honours an explicitly narrowed boundary', async () => {
const allowed = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-haha-allowed-'))
const denied = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-haha-denied-'))
try {
const config = bootConfig({ allowedProjectRoots: [allowed] })
const { httpClient } = createAdapterClient(config, config.feishu)
const names = await listedProjects(httpClient, [
{ projectName: 'allowed', realPath: allowed },
{ projectName: 'denied', realPath: denied },
{ projectName: 'home', realPath: HOME },
])
expect(names).toEqual(['allowed'])
} finally {
fs.rmSync(allowed, { recursive: true, force: true })
fs.rmSync(denied, { recursive: true, force: true })
}
})
})
/**
* Structural guard for the five entrypoints. They boot a live bot on import
* (credentials are read and process.exit is called), so they cannot be imported
* in a test. The behaviour above is covered by exercising the factory directly;
* this only pins that each entrypoint actually delegates to it.
*/
describe('IM adapter entrypoint wiring', () => {
for (const platform of PLATFORMS) {
it(`${platform} builds its client through createAdapterClient`, () => {
const source = fs.readFileSync(path.join(ADAPTERS_DIR, platform, 'index.ts'), 'utf-8')
// Strip comments so a mention in prose cannot satisfy the assertions.
.replace(/\/\*[\s\S]*?\*\//g, '')
.replace(/(^|[^:])\/\/.*$/gm, '$1')
expect(source).toMatch(
new RegExp(`createAdapterClient\\s*\\(\\s*config\\s*,\\s*config\\.${platform}\\s*\\)`),
)
// Constructing a client here would bypass the resolved boundary entirely,
// which is exactly how all five adapters shared the #1191 defect.
expect(source).not.toMatch(/new\s+AdapterHttpClient/)
// Nor may an entrypoint re-derive the boundary or the work dir itself.
expect(source).not.toMatch(/resolveAllowedProjectRoots|getConfiguredWorkDir/)
})
}
})
+184 -1
View File
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from 'bun:test'
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
import { getConfiguredWorkDir, loadConfig } from '../config.js'
import { getConfiguredWorkDir, loadConfig, resolveAllowedProjectRoots } from '../config.js'
describe('adapter config defaults', () => {
const originalConfigDir = process.env.CLAUDE_CONFIG_DIR
@@ -130,6 +130,189 @@ describe('adapter config defaults', () => {
})
})
describe('resolveAllowedProjectRoots', () => {
const originalConfigDir = process.env.CLAUDE_CONFIG_DIR
const originalEnvRoots = process.env.ADAPTER_ALLOWED_PROJECT_ROOTS
const originalAdapterDefaultWorkDir = process.env.CLAUDE_ADAPTER_DEFAULT_WORK_DIR
const originalPwd = process.env.PWD
const home = fs.realpathSync(os.homedir())
afterEach(() => {
restoreEnv('CLAUDE_CONFIG_DIR', originalConfigDir)
restoreEnv('ADAPTER_ALLOWED_PROJECT_ROOTS', originalEnvRoots)
restoreEnv('CLAUDE_ADAPTER_DEFAULT_WORK_DIR', originalAdapterDefaultWorkDir)
restoreEnv('PWD', originalPwd)
})
function withConfig<T>(file: Record<string, unknown>, run: (configDir: string) => T): T {
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-config-'))
try {
fs.writeFileSync(path.join(configDir, 'adapters.json'), JSON.stringify(file))
process.env.CLAUDE_CONFIG_DIR = configDir
delete process.env.ADAPTER_ALLOWED_PROJECT_ROOTS
return run(configDir)
} finally {
fs.rmSync(configDir, { recursive: true, force: true })
}
}
// The #1191 regression: `defaultProjectDir` is the default work dir for NEW
// sessions, not the boundary. Deriving the only allowed root from it hid every
// other project from /projects on all five IM channels.
it('does not collapse the boundary onto the configured default project', () => {
const defaultProjectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-project-'))
try {
withConfig({ defaultProjectDir }, () => {
const config = loadConfig()
for (const platform of [config.telegram, config.feishu, config.wechat, config.dingtalk, config.whatsapp]) {
const roots = resolveAllowedProjectRoots(config, platform)
expect(roots).not.toEqual([fs.realpathSync(defaultProjectDir)])
expect(roots).toContain(home)
expect(roots).toContain(fs.realpathSync(defaultProjectDir))
}
})
} finally {
fs.rmSync(defaultProjectDir, { recursive: true, force: true })
}
})
it('defaults to the home directory so sibling projects stay reachable', () => {
withConfig({}, () => {
const config = loadConfig()
expect(resolveAllowedProjectRoots(config, config.feishu)).toContain(home)
})
})
it('uses explicitly configured global roots instead of the default', () => {
const rootA = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-root-a-'))
const rootB = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-root-b-'))
try {
withConfig({ allowedProjectRoots: [rootA, rootB] }, () => {
const config = loadConfig()
expect(resolveAllowedProjectRoots(config, config.feishu)).toEqual([
fs.realpathSync(rootA),
fs.realpathSync(rootB),
])
})
} finally {
fs.rmSync(rootA, { recursive: true, force: true })
fs.rmSync(rootB, { recursive: true, force: true })
}
})
it('lets a platform narrow the global roots', () => {
const globalRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-root-global-'))
const feishuRoot = fs.mkdtempSync(path.join(globalRoot, 'feishu-'))
try {
withConfig({ allowedProjectRoots: [globalRoot], feishu: { allowedProjectRoots: [feishuRoot] } }, () => {
const config = loadConfig()
expect(resolveAllowedProjectRoots(config, config.feishu)).toEqual([fs.realpathSync(feishuRoot)])
// Other platforms keep the global roots.
expect(resolveAllowedProjectRoots(config, config.telegram)).toEqual([fs.realpathSync(globalRoot)])
})
} finally {
fs.rmSync(globalRoot, { recursive: true, force: true })
}
})
// A relative entry would resolve against the sidecar's cwd — "/" for a
// GUI-launched app — making the boundary depend on how the app was started.
it('rejects relative roots', () => {
const realRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-root-'))
try {
withConfig({ allowedProjectRoots: ['..', 'relative/path', realRoot] }, () => {
const config = loadConfig()
expect(resolveAllowedProjectRoots(config, config.feishu)).toEqual([fs.realpathSync(realRoot)])
})
} finally {
fs.rmSync(realRoot, { recursive: true, force: true })
}
})
it('does not warn about duplicates as if they were missing', () => {
const realRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-root-'))
const warnings: string[] = []
const originalWarn = console.warn
console.warn = (...args: unknown[]) => { warnings.push(args.join(' ')) }
try {
withConfig({ allowedProjectRoots: [realRoot, realRoot, '~', os.homedir()] }, () => {
const config = loadConfig()
expect(resolveAllowedProjectRoots(config, config.feishu)).toEqual([
fs.realpathSync(realRoot),
home,
])
})
expect(warnings.filter((line) => line.includes('do not exist') || line.includes('does not exist')))
.toEqual([])
} finally {
console.warn = originalWarn
fs.rmSync(realRoot, { recursive: true, force: true })
}
})
it('expands ~ and drops entries that do not exist', () => {
const realRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-root-'))
try {
withConfig({ allowedProjectRoots: [realRoot, path.join(os.tmpdir(), 'definitely-missing-root'), '~'] }, () => {
const config = loadConfig()
expect(resolveAllowedProjectRoots(config, config.feishu)).toEqual([fs.realpathSync(realRoot), home])
})
} finally {
fs.rmSync(realRoot, { recursive: true, force: true })
}
})
// Failing closed here would brick every IM command on a typo. The pairing gate
// is the primary authorization control; these roots are defense-in-depth.
it('falls back to the default when no configured root exists', () => {
withConfig({ allowedProjectRoots: [path.join(os.tmpdir(), 'missing-a'), path.join(os.tmpdir(), 'missing-b')] }, () => {
const config = loadConfig()
const roots = resolveAllowedProjectRoots(config, config.feishu)
expect(roots).toContain(home)
expect(roots.length).toBeGreaterThan(0)
})
})
it('reads roots from ADAPTER_ALLOWED_PROJECT_ROOTS for standalone runs', () => {
const rootA = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-env-root-a-'))
const rootB = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-env-root-b-'))
const configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-config-'))
try {
process.env.CLAUDE_CONFIG_DIR = configDir
process.env.ADAPTER_ALLOWED_PROJECT_ROOTS = [rootA, rootB].join(path.delimiter)
const config = loadConfig()
expect(resolveAllowedProjectRoots(config, config.feishu)).toEqual([
fs.realpathSync(rootA),
fs.realpathSync(rootB),
])
} finally {
fs.rmSync(rootA, { recursive: true, force: true })
fs.rmSync(rootB, { recursive: true, force: true })
fs.rmSync(configDir, { recursive: true, force: true })
}
})
it('lets the env override win over both file scopes', () => {
const envRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-env-root-'))
const fileRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'adapter-file-root-'))
try {
withConfig(
{ allowedProjectRoots: [fileRoot], feishu: { allowedProjectRoots: [fileRoot] } },
() => {
process.env.ADAPTER_ALLOWED_PROJECT_ROOTS = envRoot
const config = loadConfig()
expect(resolveAllowedProjectRoots(config, config.feishu)).toEqual([fs.realpathSync(envRoot)])
expect(resolveAllowedProjectRoots(config, config.telegram)).toEqual([fs.realpathSync(envRoot)])
},
)
} finally {
fs.rmSync(envRoot, { recursive: true, force: true })
fs.rmSync(fileRoot, { recursive: true, force: true })
}
})
})
function restoreEnv(key: string, value: string | undefined): void {
if (value === undefined) {
delete process.env[key]
@@ -85,6 +85,50 @@ describe('AdapterHttpClient', () => {
}
})
// #1191: /projects showed only the default project on every IM channel because
// the allowed root was the default work dir itself. With the boundary resolved
// from the user's home instead, sibling projects must survive the filter.
it('keeps sibling projects that live outside the default work dir', async () => {
const homeRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'im-home-'))
try {
const defaultWorkDir = path.join(homeRoot, 'work', 'my-app')
const sibling = path.join(homeRoot, 'work', 'other-app')
const elsewhere = path.join(homeRoot, 'side', 'blog')
const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'im-outside-'))
for (const dir of [defaultWorkDir, sibling, elsewhere]) fs.mkdirSync(dir, { recursive: true })
// The roots an adapter now gets from resolveAllowedProjectRoots(): the home
// directory, not the default work dir.
client = new AdapterHttpClient('ws://127.0.0.1:3456', {
allowedProjectRoots: [homeRoot, defaultWorkDir],
})
globalThis.fetch = mock(() =>
Promise.resolve(Response.json({
projects: [
{ projectName: 'my-app', realPath: defaultWorkDir, sessionCount: 9 },
{ projectName: 'other-app', realPath: sibling, sessionCount: 4 },
{ projectName: 'blog', realPath: elsewhere, sessionCount: 2 },
{ projectName: 'not-mine', realPath: outside, sessionCount: 1 },
],
}))
) as any
const projects = await client.listRecentProjects()
expect(projects.map((p) => p.projectName)).toEqual(['my-app', 'other-app', 'blog'])
// Picking any of them by name must work too — matchProject shares the filter.
await expect(client.matchProject('blog')).resolves.toMatchObject({
project: { projectName: 'blog' },
})
// The boundary still holds for anything outside it.
await expect(client.matchProject('not-mine')).resolves.toEqual({})
fs.rmSync(outside, { recursive: true, force: true })
} finally {
fs.rmSync(homeRoot, { recursive: true, force: true })
}
})
it('filters recent projects before index, name, and fuzzy matching', async () => {
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'im-root-'))
const allowedDir = fs.mkdtempSync(path.join(rootDir, 'allowed-'))
+34
View File
@@ -0,0 +1,34 @@
import {
resolveAdapterWorkspace,
type AdapterConfig,
type AdapterPlatformConfig,
} from './config.js'
import { AdapterHttpClient } from './http-client.js'
export type AdapterWorkspace = {
httpClient: AdapterHttpClient
/** Where a new IM session starts. Guaranteed to sit inside the allowed roots. */
defaultWorkDir: string
}
/**
* Build the HTTP client and the default work dir for an IM adapter.
*
* Every adapter entrypoint goes through here instead of constructing the client
* itself. The five entrypoints previously repeated the wiring, and all five
* repeated the same defect (#1191): they passed the default work dir as the only
* allowed project root, so /projects listed a single project. Keeping the
* construction in one importable place makes that class of mistake unreachable
* without editing this file, and makes it testable — the entrypoints boot a live
* bot on import and cannot be exercised directly.
*/
export function createAdapterClient(
config: AdapterConfig,
platformConfig: AdapterPlatformConfig,
): AdapterWorkspace {
const { defaultWorkDir, allowedProjectRoots } = resolveAdapterWorkspace(config, platformConfig)
return {
httpClient: new AdapterHttpClient(config.serverUrl, { allowedProjectRoots }),
defaultWorkDir,
}
}
+167 -3
View File
@@ -25,6 +25,7 @@ export type TelegramConfig = {
allowedUsers: number[]
pairedUsers: PairedUser[]
defaultWorkDir: string
allowedProjectRoots: string[]
}
export type FeishuConfig = {
@@ -36,6 +37,7 @@ export type FeishuConfig = {
pairedUsers: PairedUser[]
defaultWorkDir: string
streamingCard: boolean
allowedProjectRoots: string[]
}
export type WechatConfig = {
@@ -46,6 +48,7 @@ export type WechatConfig = {
allowedUsers: string[]
pairedUsers: PairedUser[]
defaultWorkDir: string
allowedProjectRoots: string[]
}
export type DingtalkConfig = {
@@ -56,6 +59,7 @@ export type DingtalkConfig = {
defaultWorkDir: string
endpoint: string
permissionCardTemplateId: string
allowedProjectRoots: string[]
}
export type WhatsAppConfig = {
@@ -64,12 +68,14 @@ export type WhatsAppConfig = {
allowedUsers: string[]
pairedUsers: PairedUser[]
defaultWorkDir: string
allowedProjectRoots: string[]
}
export type AdapterConfig = {
serverUrl: string
defaultProjectDir: string
pairing: PairingState
allowedProjectRoots: string[]
telegram: TelegramConfig
feishu: FeishuConfig
wechat: WechatConfig
@@ -121,11 +127,15 @@ export function loadConfig(): AdapterConfig {
expiresAt: pairing.expiresAt ?? null,
createdAt: pairing.createdAt ?? null,
},
// File scope only. ADAPTER_ALLOWED_PROJECT_ROOTS is applied by
// resolveAllowedProjectRoots so this field keeps one meaning.
allowedProjectRoots: readProjectRoots(file.allowedProjectRoots),
telegram: {
botToken: process.env.TELEGRAM_BOT_TOKEN || tg.botToken || '',
allowedUsers: tg.allowedUsers ?? [],
pairedUsers: tg.pairedUsers ?? [],
defaultWorkDir: tg.defaultWorkDir || fallbackWorkDir,
allowedProjectRoots: readProjectRoots(tg.allowedProjectRoots),
},
feishu: {
appId: process.env.FEISHU_APP_ID || fs_.appId || '',
@@ -136,6 +146,7 @@ export function loadConfig(): AdapterConfig {
pairedUsers: fs_.pairedUsers ?? [],
defaultWorkDir: fs_.defaultWorkDir || fallbackWorkDir,
streamingCard: fs_.streamingCard ?? false,
allowedProjectRoots: readProjectRoots(fs_.allowedProjectRoots),
},
wechat: {
accountId: process.env.WECHAT_ACCOUNT_ID || wc.accountId || '',
@@ -145,6 +156,7 @@ export function loadConfig(): AdapterConfig {
allowedUsers: wc.allowedUsers ?? [],
pairedUsers: wc.pairedUsers ?? [],
defaultWorkDir: wc.defaultWorkDir || fallbackWorkDir,
allowedProjectRoots: readProjectRoots(wc.allowedProjectRoots),
},
dingtalk: {
clientId: process.env.DINGTALK_CLIENT_ID || dt.clientId || '',
@@ -154,6 +166,7 @@ export function loadConfig(): AdapterConfig {
defaultWorkDir: dt.defaultWorkDir || fallbackWorkDir,
endpoint: process.env.DINGTALK_STREAM_ENDPOINT || dt.endpoint || 'https://api.dingtalk.com',
permissionCardTemplateId: process.env.DINGTALK_PERMISSION_CARD_TEMPLATE_ID || dt.permissionCardTemplateId || '',
allowedProjectRoots: readProjectRoots(dt.allowedProjectRoots),
},
whatsapp: {
accountJid: process.env.WHATSAPP_ACCOUNT_JID || wa.accountJid || '',
@@ -161,6 +174,7 @@ export function loadConfig(): AdapterConfig {
allowedUsers: wa.allowedUsers ?? [],
pairedUsers: wa.pairedUsers ?? [],
defaultWorkDir: wa.defaultWorkDir || fallbackWorkDir,
allowedProjectRoots: readProjectRoots(wa.allowedProjectRoots),
},
}
}
@@ -169,21 +183,167 @@ export function getConfiguredWorkDir(config: AdapterConfig, platformConfig: Adap
return config.defaultProjectDir || platformConfig.defaultWorkDir
}
/**
* Resolve the directories an IM adapter is allowed to reach.
*
* This is deliberately NOT derived from `defaultWorkDir` (#1191). That field is
* documented as the *default* work dir for new IM sessions, not a boundary, and
* using it as the sole allowed root broke both directions:
*
* - configured → /projects listed only that one project, and picking any other
* recent project by name or path failed;
* - blank → it falls back to PWD/cwd(), which for a Finder-launched .app
* is "/", so the boundary silently allowed the entire filesystem.
*
* Precedence: ADAPTER_ALLOWED_PROJECT_ROOTS > platform-specific roots > global
* roots > default (home ∪ default work dir). The pairing gate is the primary
* authorization control; these roots are defense-in-depth, so a misconfigured
* value falls back to the default with a warning instead of bricking the bot.
*
* Explicitly configured roots are honoured verbatim — if someone types "/" they
* own the machine and mean it. The *default* branch refuses to inherit such a
* root, because that is how the boundary silently became vacuous before.
*/
export function resolveAllowedProjectRoots(
config: AdapterConfig,
platformConfig: AdapterPlatformConfig,
): string[] {
// Env wins over both file scopes, matching how every other field in this
// module resolves.
const configured = readEnvProjectRoots()
?? (platformConfig.allowedProjectRoots.length > 0
? platformConfig.allowedProjectRoots
: config.allowedProjectRoots)
if (configured.length > 0) {
const candidates = configured.map(resolveExistingDirectory)
// Count the misses before dedup — duplicates are not missing directories.
const missing = candidates.filter((value) => !value).length
const resolved = dedupePaths(candidates)
if (resolved.length > 0) {
if (missing > 0) {
console.warn(
missing === 1
? '[Config] Ignoring 1 allowedProjectRoots entry that does not exist'
: `[Config] Ignoring ${missing} allowedProjectRoots entries that do not exist`,
)
}
return resolved
}
console.warn(
'[Config] None of the configured allowedProjectRoots exist; ' +
'falling back to the default roots (home directory + default project dir)',
)
}
const home = resolveExistingDirectory(os.homedir())
const defaults = dedupePaths([
home,
// Only inherit the default work dir as a boundary when it is a real project
// directory. "/" and "/Users" reach every project on the machine, so taking
// them from the PWD/cwd() fallback would make the boundary meaningless.
usableAsBoundary(resolveExistingDirectory(getConfiguredWorkDir(config, platformConfig))),
])
if (defaults.length > 0) return defaults
// Only reachable if the home directory itself does not resolve. The adapter
// client drops unresolvable roots, so this is a best effort, not a guarantee.
return [os.homedir()]
}
/**
* Directories the IM boundary must never inherit implicitly: a filesystem root,
* or any strict ancestor of the home directory (`/`, `/Users`, `/home`).
*/
function usableAsBoundary(dir: string | null): string | null {
if (!dir) return null
if (path.parse(dir).root === dir) return null
return isStrictAncestor(dir, os.homedir()) ? null : dir
}
function isStrictAncestor(candidate: string, target: string): boolean {
const relative = path.relative(candidate, target)
return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)
}
/**
* The work dir a new IM session starts in, paired with the boundary it must sit
* inside. Resolving them together is the point: the two are configured
* separately, and a default project outside the allowed roots would otherwise
* make every `/new` (and every first message in a fresh chat) fail the client's
* own boundary check.
*/
export function resolveAdapterWorkspace(
config: AdapterConfig,
platformConfig: AdapterPlatformConfig,
): { defaultWorkDir: string; allowedProjectRoots: string[] } {
const allowedProjectRoots = resolveAllowedProjectRoots(config, platformConfig)
const configured = resolveExistingDirectory(getConfiguredWorkDir(config, platformConfig))
if (configured && isPathWithinRoots(configured, allowedProjectRoots)) {
return { defaultWorkDir: configured, allowedProjectRoots }
}
const fallback = allowedProjectRoots[0] ?? os.homedir()
if (configured) {
console.warn(
`[Config] Default project ${configured} is outside the allowed project roots; ` +
`new sessions will start in ${fallback}`,
)
}
return { defaultWorkDir: fallback, allowedProjectRoots }
}
function isPathWithinRoots(target: string, roots: string[]): boolean {
return roots.some((root) => {
const relative = path.relative(root, target)
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
})
}
function readProjectRoots(value: unknown): string[] {
if (!Array.isArray(value)) return []
return value
.filter((item): item is string => typeof item === 'string')
.map((item) => item.trim())
.filter(Boolean)
}
function readEnvProjectRoots(): string[] | null {
const raw = process.env.ADAPTER_ALLOWED_PROJECT_ROOTS?.trim()
if (!raw) return null
const roots = readProjectRoots(raw.split(path.delimiter))
// A delimiter-only value (an unset "$A:$B" in a launcher script) must not read
// as "the env configured an empty boundary" and discard the file config.
return roots.length > 0 ? roots : null
}
function dedupePaths(values: (string | null)[]): string[] {
const seen = new Set<string>()
const result: string[] = []
for (const value of values) {
if (!value || seen.has(value)) continue
seen.add(value)
result.push(value)
}
return result
}
function resolveUserDefaultWorkDir(): string {
const candidates = [
process.env.ADAPTER_DEFAULT_PROJECT_DIR,
process.env.CLAUDE_ADAPTER_DEFAULT_WORK_DIR,
process.env.PWD,
process.cwd(),
os.homedir(),
]
for (const candidate of candidates) {
const resolved = resolveExistingDirectory(candidate)
// A GUI-launched sidecar inherits cwd "/" (Electron passes no cwd), which is
// useless as a place to start a session and unusable as a boundary.
const resolved = usableAsBoundary(resolveExistingDirectory(candidate))
if (resolved) return resolved
}
return os.homedir()
return resolveExistingDirectory(os.homedir()) ?? os.homedir()
}
function resolveExistingDirectory(value: string | undefined): string | null {
@@ -196,6 +356,10 @@ function resolveExistingDirectory(value: string | undefined): string | null {
? path.join(os.homedir(), trimmed.slice(2))
: trimmed
// Relative entries would resolve against the sidecar's cwd ("/" for a packaged
// app), making the boundary depend on how the app was launched.
if (!path.isAbsolute(expanded)) return null
try {
const realPath = fs.realpathSync(expanded)
return fs.statSync(realPath).isDirectory() ? realPath : null
+4 -4
View File
@@ -11,7 +11,7 @@ import { WsBridge, type ServerMessage, type AttachmentRef } from '../common/ws-b
import { MessageDedup } from '../common/message-dedup.js'
import { MessageBuffer } from '../common/message-buffer.js'
import { enqueue } from '../common/chat-queue.js'
import { getConfiguredWorkDir, loadConfig } from '../common/config.js'
import { loadConfig } from '../common/config.js'
import { formatImHelp, formatImStatus, formatPermissionRequest, splitMessage } from '../common/format.js'
import {
formatPermissionDecisionStatus,
@@ -20,7 +20,8 @@ import {
type PermissionDecision,
} from '../common/permission.js'
import { SessionStore } from '../common/session-store.js'
import { AdapterHttpClient, type RecentProject } from '../common/http-client.js'
import { type RecentProject } from '../common/http-client.js'
import { createAdapterClient } from '../common/adapter-client.js'
import { restoreStoredSessionBinding } from '../common/session-recovery.js'
import { isAllowedUser, tryPair } from '../common/pairing.js'
import { AttachmentStore } from '../common/attachment/attachment-store.js'
@@ -54,12 +55,11 @@ if (!config.dingtalk.clientId || !config.dingtalk.clientSecret) {
console.error('[DingTalk] Missing DINGTALK_CLIENT_ID / DINGTALK_CLIENT_SECRET. Bind with QR auth in Desktop Settings or set env.')
process.exit(1)
}
const defaultWorkDir = getConfiguredWorkDir(config, config.dingtalk)
const { httpClient, defaultWorkDir } = createAdapterClient(config, config.dingtalk)
const bridge = new WsBridge(config.serverUrl, 'dingtalk')
const dedup = new MessageDedup()
const sessionStore = new SessionStore()
const httpClient = new AdapterHttpClient(config.serverUrl, { allowedProjectRoots: [defaultWorkDir] })
const attachmentStore = new AttachmentStore()
const media = new DingTalkMediaService(attachmentStore)
const aiCards = new DingTalkAiCardService(getAccessToken, config.dingtalk.clientId)
+4 -4
View File
@@ -13,7 +13,7 @@ import { WsBridge, type ServerMessage, type AttachmentRef } from '../common/ws-b
import { MessageDedup } from '../common/message-dedup.js'
import { StreamingCard } from './streaming-card.js'
import { enqueue } from '../common/chat-queue.js'
import { getConfiguredWorkDir, loadConfig } from '../common/config.js'
import { loadConfig } from '../common/config.js'
import {
formatImHelp,
formatImStatus,
@@ -26,7 +26,8 @@ import {
type PermissionDecision,
} from '../common/permission.js'
import { SessionStore } from '../common/session-store.js'
import { AdapterHttpClient, type RecentProject } from '../common/http-client.js'
import { type RecentProject } from '../common/http-client.js'
import { createAdapterClient } from '../common/adapter-client.js'
import { restoreStoredSessionBinding } from '../common/session-recovery.js'
import { isAllowedUser, tryPair } from '../common/pairing.js'
import { extractInboundPayload } from './extract-payload.js'
@@ -56,8 +57,7 @@ const larkClient = new Lark.Client({
const bridge = new WsBridge(config.serverUrl, 'feishu')
const dedup = new MessageDedup()
const sessionStore = new SessionStore()
const defaultWorkDir = getConfiguredWorkDir(config, config.feishu)
const httpClient = new AdapterHttpClient(config.serverUrl, { allowedProjectRoots: [defaultWorkDir] })
const { httpClient, defaultWorkDir } = createAdapterClient(config, config.feishu)
// Attachment plumbing — shared by inbound (download) and outbound (upload) paths.
const attachmentStore = new AttachmentStore()
+3 -4
View File
@@ -11,7 +11,7 @@ import { WsBridge, type ServerMessage } from '../common/ws-bridge.js'
import { MessageBuffer } from '../common/message-buffer.js'
import { MessageDedup } from '../common/message-dedup.js'
import { enqueue } from '../common/chat-queue.js'
import { getConfiguredWorkDir, loadConfig } from '../common/config.js'
import { loadConfig } from '../common/config.js'
import {
formatImStatus,
formatPermissionRequest,
@@ -31,7 +31,7 @@ import {
type PermissionDecision,
} from '../common/permission.js'
import { SessionStore } from '../common/session-store.js'
import { AdapterHttpClient } from '../common/http-client.js'
import { createAdapterClient } from '../common/adapter-client.js'
import { restoreStoredSessionBinding } from '../common/session-recovery.js'
import { isAllowedUser, tryPair } from '../common/pairing.js'
import { TelegramMediaService } from './media.js'
@@ -59,8 +59,7 @@ const bot = new Bot(config.telegram.botToken)
const bridge = new WsBridge(config.serverUrl, 'tg')
const dedup = new MessageDedup()
const sessionStore = new SessionStore()
const defaultWorkDir = getConfiguredWorkDir(config, config.telegram)
const httpClient = new AdapterHttpClient(config.serverUrl, { allowedProjectRoots: [defaultWorkDir] })
const { httpClient, defaultWorkDir } = createAdapterClient(config, config.telegram)
const attachmentStore = new AttachmentStore()
const media = new TelegramMediaService(bot, attachmentStore)
attachmentStore.gc().catch((err) => {
+3 -4
View File
@@ -3,7 +3,7 @@ import { WsBridge, type ServerMessage, type AttachmentRef } from '../common/ws-b
import { MessageDedup } from '../common/message-dedup.js'
import { MessageBuffer } from '../common/message-buffer.js'
import { enqueue } from '../common/chat-queue.js'
import { getConfiguredWorkDir, loadConfig } from '../common/config.js'
import { loadConfig } from '../common/config.js'
import {
formatImHelp,
formatImStatus,
@@ -16,7 +16,7 @@ import {
parsePermissionCommand,
} from '../common/permission.js'
import { SessionStore } from '../common/session-store.js'
import { AdapterHttpClient } from '../common/http-client.js'
import { createAdapterClient } from '../common/adapter-client.js'
import { restoreStoredSessionBinding } from '../common/session-recovery.js'
import { isAllowedUser, tryPair } from '../common/pairing.js'
import { AttachmentStore } from '../common/attachment/attachment-store.js'
@@ -48,8 +48,7 @@ const botToken = config.wechat.botToken
const bridge = new WsBridge(config.serverUrl, 'wechat')
const dedup = new MessageDedup()
const sessionStore = new SessionStore()
const defaultWorkDir = getConfiguredWorkDir(config, config.wechat)
const httpClient = new AdapterHttpClient(config.serverUrl, { allowedProjectRoots: [defaultWorkDir] })
const { httpClient, defaultWorkDir } = createAdapterClient(config, config.wechat)
const attachmentStore = new AttachmentStore()
const media = new WechatMediaService(attachmentStore)
const pendingProjectSelection = new Map<string, boolean>()
+3 -4
View File
@@ -13,7 +13,7 @@ import {
import { WsBridge, type ServerMessage, type AttachmentRef } from '../common/ws-bridge.js'
import { MessageDedup } from '../common/message-dedup.js'
import { enqueue } from '../common/chat-queue.js'
import { getConfiguredWorkDir, loadConfig } from '../common/config.js'
import { loadConfig } from '../common/config.js'
import {
formatImHelp,
formatImStatus,
@@ -26,7 +26,7 @@ import {
type PermissionDecision,
} from '../common/permission.js'
import { SessionStore } from '../common/session-store.js'
import { AdapterHttpClient } from '../common/http-client.js'
import { createAdapterClient } from '../common/adapter-client.js'
import { restoreStoredSessionBinding } from '../common/session-recovery.js'
import { isAllowedUser, tryPair } from '../common/pairing.js'
import { AttachmentStore } from '../common/attachment/attachment-store.js'
@@ -62,8 +62,7 @@ if (!hasWhatsAppAuth(authDir)) {
const bridge = new WsBridge(config.serverUrl, 'whatsapp')
const dedup = new MessageDedup()
const sessionStore = new SessionStore()
const defaultWorkDir = getConfiguredWorkDir(config, config.whatsapp)
const httpClient = new AdapterHttpClient(config.serverUrl, { allowedProjectRoots: [defaultWorkDir] })
const { httpClient, defaultWorkDir } = createAdapterClient(config, config.whatsapp)
const attachmentStore = new AttachmentStore()
attachmentStore.gc().catch((err) => {
console.warn('[WhatsApp] AttachmentStore.gc failed:', err instanceof Error ? err.message : err)