feat(config)!: one ordering for configuration sources, and a bootstrap deny rule

$DSH_HOME/.env had just become an ordinary environment layer, which left the
harness resolving user-facing values from a flattened process.env that could
no longer say where a value came from. A key stored through the web page
stayed shadowed by an older key in the user's own .env. An endpoint could be
redirected by the project: the invoking directory's .env is materialized like
every other layer, and a base URL decides where a resolved API key is sent, so
a DEEPSEEK_BASE_URL written into a model-editable workspace would send the
user's credential — and the prompts carrying their code — to whatever host
that file named.

Give every user-facing value one ordering, with four kinds of source:

  explicit for this run     per-operation override, CLI argument
  > authored by deployment  --config / --config-replace
  > this launch's shell     inherited process environment
  > product-managed store   settings.yaml, .credentials.yaml
  > discovered file         $DSH_HOME/.env
  > defaults                schema default, shipped base, public default

The domains differ only in which tiers exist. The earlier split — credentials
ranking the environment over the managed file while settings ranked over the
environment — was inconsistent: the distinguishing fact is who authored the
source, not the domain.

packages/util/environment owns an immutable snapshot with per-layer
provenance. getFrom(name, sources) searches only the layers a caller names,
and omitting one is a refusal rather than a demotion: the adapters ask for
['process', 'user-env'], so no reordering can let a project file back into a
decision it was excluded from.

isBootstrapOnly rejects, before anything is materialized, any .env setting a
variable that governs how a process launches (PATH, SHELL, NODE_OPTIONS,
LD_PRELOAD), where code or model-visible instructions load from (the whole
DSH_* namespace, HOME, XDG_*), or how the network is reached (proxy and CA
variables). The namespace is denied wholesale so a switch added later cannot
become settable by being forgotten, and there is no opt-out.

verify-config-source-ownership keeps both rules: no unregistered process.env
read under packages/*/*/src (26 allowlisted with reasons), and no apiKey,
baseURL, or headers inlined from the environment in shipped Cordis config —
removing those inlines is what makes the deployment tier meaningful.
This commit is contained in:
Yichen Jiang
2026-08-04 16:17:32 +08:00
parent 8ddc53f7a0
commit 0512b12714
59 changed files with 1241 additions and 165 deletions

View File

@@ -27,12 +27,14 @@
],
"license": "BSD-3-Clause",
"dependencies": {
"dotenv": "^17.2.0",
"js-yaml": "^4.2.0"
},
"peerDependencies": {
"@cordisjs/plugin-hmr": "^1.0.15",
"@cordisjs/plugin-include": "^1.0.4",
"@cordisjs/plugin-loader": "^1.0.0-rc.5",
"@deepseek-ai/dsh-environment": "^0.0.1",
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-paths": "^0.0.1",
"@deepseek-ai/dsh-system-prompt": "^0.0.1",
@@ -48,6 +50,7 @@
"@cordisjs/plugin-include": "workspace:^",
"@cordisjs/plugin-loader": "workspace:^",
"@cordisjs/plugin-timer": "workspace:^",
"@deepseek-ai/dsh-environment": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-paths": "workspace:^",
"@deepseek-ai/dsh-system-prompt": "workspace:^",

View File

@@ -9,11 +9,13 @@
import { pathToFileURL } from 'node:url'
import { readFileSync } from 'node:fs'
import { basename, dirname, resolve } from 'node:path'
import { parse as parseDotenv } from 'dotenv'
import * as yaml from 'js-yaml'
import { Context, type FiberState } from 'cordis'
import Loader, { type Entry, type EntryOptions } from '@cordisjs/plugin-loader'
import Include, { applyEntryPatches, entryListSchema, type PatchOptions } from '@cordisjs/plugin-include'
import { dshHomePath, resolveDshHome } from '@deepseek-ai/dsh-paths'
import { createEnvironmentSnapshot, isBootstrapOnly, type EnvironmentSnapshot } from '@deepseek-ai/dsh-environment'
import type {} from '@cordisjs/plugin-hmr'
// Side-effect type import: resolves `ctx.get('systemPrompt')` to the service.
import type {} from '@deepseek-ai/dsh-system-prompt'
@@ -66,12 +68,57 @@ export function loadEnv(
}
/**
* Load the dsh product CLI's user environment: the invoking directory's `.env`
* Parse one directory's `.env` without applying it, rejecting any bootstrap
* variable it declares. A discovered file must not decide how this process
* launches, where its code and model-visible instructions come from, or how it
* reaches the network, so a violation fails the launch BEFORE anything is
* materialized — reporting it afterwards would leave the process already
* running under the value it refused.
* @param binName - the diagnostic prefix on the thrown error.
* @param dir - the directory whose `.env` to read.
* @param warn - sink for the one-line unreadable-file diagnostic.
* @returns the parsed entries, or `undefined` when the file is absent or unreadable.
* @throws when the file declares a name {@link isBootstrapOnly} rejects.
*/
function readEnvLayer(
binName: string, dir: string, warn: (line: string) => void,
): { path: string; values: Record<string, string> } | undefined {
const path = resolve(dir, '.env')
let content: string
try {
content = readFileSync(path, 'utf8')
} catch (error) {
if ((error as NodeJS.ErrnoException | null)?.code !== 'ENOENT') {
warn(`${binName}: failed to load .env: ${String(error)}\n`)
}
// ENOENT (no .env) is fine — rely on the ambient environment.
return undefined
}
const values = parseDotenv(content)
for (const name of Object.keys(values)) {
if (!isBootstrapOnly(name)) continue
throw new Error(
`${binName}: ${path} sets "${name}", which only the launching environment may set`
+ ' (it decides how this process starts, where its code and instructions load from, or how it'
+ ` reaches the network); export ${name} instead of putting it in a .env file`,
)
}
return { path, values }
}
/**
* Load the dsh product CLI's user environment and return it as a snapshot that
* remembers which layer supplied each value: the invoking directory's `.env`
* over the Harness home's `.env`, both under the inherited process
* environment. `process.loadEnvFile` never replaces a name that is already
* set, so loading the project file first and the user file second is what
* makes the layering `user < project < inherited`; the app-boot tests pin all
* three layers because that ordering is the whole contract.
* environment.
*
* Each layer is parsed and checked before anything is applied, then applied in
* the order that makes the layering `user < project < inherited` —
* `process.loadEnvFile` never replaces a name already set. Values do reach
* `process.env`, because a user's own `--config` tree and third-party
* libraries read it; the returned snapshot is the authority for everything the
* harness itself resolves, since `process.env` alone cannot say whether a
* value came from the launching shell or from a file inside the workspace.
*
* The Harness home is resolved from the inherited environment *before* either
* file loads, so a project `.env` can never redirect which user document is
@@ -82,17 +129,28 @@ export function loadEnv(
* These are ordinary environment values with ordinary environment reach. A
* secret the Harness should own and isolate belongs in the credentials
* document, which is never materialized here.
* @param binName - the diagnostic prefix on the warn lines.
* @param binName - the diagnostic prefix on the diagnostics.
* @param cwd - the invoking directory whose `.env` is the project layer.
* @param warn - sink for the one-line misconfiguration diagnostics.
* @returns this run's frozen environment snapshot.
* @throws when either file declares a bootstrap-only variable.
*/
export function loadLayeredEnv(
binName: string, cwd: string = process.cwd(),
warn: (line: string) => void = line => void process.stderr.write(line),
): void {
): EnvironmentSnapshot {
const home = resolveDshHome()
loadEnv(binName, cwd, warn)
loadEnv(binName, home, warn)
const inherited = { ...process.env } as Record<string, string>
// Parse both layers first: a rejection must not leave one file applied.
const project = readEnvLayer(binName, cwd, warn)
const user = home === resolve(cwd) ? undefined : readEnvLayer(binName, home, warn)
if (project !== undefined) process.loadEnvFile(project.path)
if (user !== undefined) process.loadEnvFile(user.path)
return createEnvironmentSnapshot([
{ source: 'process', values: inherited },
...project === undefined ? [] : [{ source: 'project-env' as const, path: project.path, values: project.values }],
...user === undefined ? [] : [{ source: 'user-env' as const, path: user.path, values: user.values }],
])
}
/**

View File

@@ -87,7 +87,7 @@ describe('loadEnv', () => {
})
describe('loadLayeredEnv', () => {
const NAMES = ['DSH_APP_BOOT_LAYERED_SHARED', 'DSH_APP_BOOT_LAYERED_USER', 'DSH_APP_BOOT_LAYERED_PROJECT'] as const
const NAMES = ['APP_BOOT_LAYERED_SHARED', 'APP_BOOT_LAYERED_USER', 'APP_BOOT_LAYERED_PROJECT'] as const
function clear(): void {
for (const name of NAMES) Reflect.deleteProperty(process.env, name)
@@ -99,18 +99,18 @@ describe('loadLayeredEnv', () => {
writeFileSync(join(home, '.env'), [
`${NAMES[0]}=user`,
`${NAMES[1]}=user-only`,
'DSH_APP_BOOT_LAYERED_INHERITED=user-loses',
'APP_BOOT_LAYERED_INHERITED=user-loses',
'',
].join('\n'))
writeFileSync(join(project, '.env'), [
`${NAMES[0]}=project`,
`${NAMES[2]}=project-only`,
'DSH_APP_BOOT_LAYERED_INHERITED=project-loses',
'APP_BOOT_LAYERED_INHERITED=project-loses',
'',
].join('\n'))
clear()
vi.stubEnv('DSH_HOME', home)
vi.stubEnv('DSH_APP_BOOT_LAYERED_INHERITED', 'inherited')
vi.stubEnv('APP_BOOT_LAYERED_INHERITED', 'inherited')
const warn = vi.fn()
try {
loadLayeredEnv(NAME, project, warn)
@@ -119,7 +119,7 @@ describe('loadLayeredEnv', () => {
expect(process.env[NAMES[0]]).toBe('project')
expect(process.env[NAMES[1]]).toBe('user-only')
expect(process.env[NAMES[2]]).toBe('project-only')
expect(process.env['DSH_APP_BOOT_LAYERED_INHERITED']).toBe('inherited')
expect(process.env['APP_BOOT_LAYERED_INHERITED']).toBe('inherited')
expect(warn).not.toHaveBeenCalled()
} finally {
clear()
@@ -127,18 +127,64 @@ describe('loadLayeredEnv', () => {
}
})
it('resolves the harness home before the project file can redirect it', () => {
it.each([
['a harness switch', 'DSH_PERMISSION_MODE=danger-full-access\n'],
['the executable search path', 'PATH=/tmp/evil\n'],
['a module preload', 'NODE_OPTIONS=--require /tmp/evil.js\n'],
['a skill root', 'DSH_AGENTS_HOME=/tmp/injected\n'],
['a network proxy', 'HTTPS_PROXY=http://attacker.example\n'],
['a lowercase network proxy', 'https_proxy=http://attacker.example\n'],
])('refuses to launch when a .env sets %s, before applying anything', (_case, content) => {
const home = tmp()
const project = tmp()
writeFileSync(join(project, '.env'), `${NAMES[1]}=applied-anyway\n${content}`)
clear()
vi.stubEnv('DSH_HOME', home)
try {
expect(() => loadLayeredEnv(NAME, project, vi.fn())).toThrow(/only the launching environment may set/)
// Rejected BEFORE materialization: reporting the violation after the
// file was applied would leave the process running under what it refused.
expect(process.env[NAMES[1]]).toBeUndefined()
} finally {
clear()
vi.unstubAllEnvs()
}
})
it('reports each layer with its absolute path', () => {
const home = tmp()
const project = tmp()
writeFileSync(join(home, '.env'), `${NAMES[1]}=u\n`)
writeFileSync(join(project, '.env'), `${NAMES[2]}=p\n`)
clear()
vi.stubEnv('DSH_HOME', home)
try {
const snapshot = loadLayeredEnv(NAME, project, vi.fn())
expect(snapshot.layers).toEqual([
{ source: 'process' },
{ source: 'project-env', path: join(project, '.env') },
{ source: 'user-env', path: join(home, '.env') },
])
expect(snapshot.get(NAMES[1])).toEqual({ value: 'u', source: 'user-env', path: join(home, '.env') })
// getFrom is a refusal, not a demotion: an omitted layer is invisible.
expect(snapshot.getFrom(NAMES[2], ['process', 'user-env'])).toBeUndefined()
} finally {
clear()
vi.unstubAllEnvs()
}
})
it('resolves the harness home from the inherited environment, never from a file', () => {
const home = tmp()
const decoy = tmp()
const project = tmp()
writeFileSync(join(home, '.env'), `${NAMES[1]}=real-home\n`)
writeFileSync(join(decoy, '.env'), `${NAMES[1]}=decoy-home\n`)
writeFileSync(join(project, '.env'), `DSH_HOME=${decoy}\n`)
writeFileSync(join(project, '.env'), `${NAMES[2]}=set-by-project\n`)
clear()
vi.stubEnv('DSH_HOME', home)
try {
loadLayeredEnv(NAME, project, vi.fn())
expect(process.env[NAMES[1]]).toBe('real-home')
expect(process.env[NAMES[2]]).toBe('set-by-project')
} finally {
clear()
vi.unstubAllEnvs()

View File

@@ -26,6 +26,9 @@
{
"path": "../../core/system-prompt"
},
{
"path": "../../util/environment"
},
{
"path": "../../util/paths"
}