Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: harden provider credential classification (#4612)

[._.]/ Adam Eivyc88a7717052d
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index f9b3e68dab..8a195e3c4f 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -41,7 +41,7 @@ grep -i "what you want to do" client/src/utils/README.md
| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` (explicit http(s) only — safe-href check), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). |
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
| `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. |
-| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `isOrcaRouterBackedProvider` (the OpenCode wrapper that inherits its API key from the sibling `orcarouter` API provider at spawn time), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. `isLocalInstanceProvider(provider)` — the narrower question, mirroring server `localProviderRuntime.js#isLocalInstanceEndpoint`: does this provider talk to a daemon on THIS machine (loopback, or no endpoint at all)? Gate anything that explains a provider by inspecting the host PortOS runs on — install state, "start it from Settings → Local LLM" — since `localBackendForProvider` matches by NAME and would otherwise claim a peer's LM Studio. And `providerCardState(provider, { runtime, status, orcaRouterKeySet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent), or simply switched off? Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, and the same computation `getFallbackProvider` routes on) and adds only what the browser alone can see — the local-app runtime shape; derives the credential checks itself only when an older server publishes nothing. `null` inputs mean "not probed", never "missing". Drives the AI Providers page card colors and grouping — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. `resolvesOutsidePortosPath(provider)` — does this provider resolve its binary somewhere the runtime probe never looked (an explicit path in `command`, or its own `PATH` in `envVars`)? Mirror of the same two guards in the server's `providerRuntimeKey`, and what keeps the card's badge from accusing a working provider the router happily routes. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. |
+| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `isOrcaRouterBackedProvider` (the OpenCode wrapper that inherits its API key from the sibling `orcarouter` API provider at spawn time), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. `isLocalInstanceProvider(provider)` — the narrower question, mirroring server `localProviderRuntime.js#isLocalInstanceEndpoint`: does this provider talk to a daemon on THIS machine (loopback, or no endpoint at all)? Gate anything that explains a provider by inspecting the host PortOS runs on — install state, "start it from Settings → Local LLM" — since `localBackendForProvider` matches by NAME and would otherwise claim a peer's LM Studio. And `credentialSource(provider)` plus `providerCardState(provider, { runtime, status, keySetFor, envVarSet })` + `PROVIDER_CARD_STATE` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent / empty credential environment variable), or simply switched off? Reads the SERVER's `missingPrerequisites` (published per provider on `GET /api/providers` from `server/lib/providerPrerequisites.js`, and the same computation `getFallbackProvider` routes on) and adds the local-app runtime shape plus tri-state checks for stored, inherited, and process environment credentials. Unknown lookup values mean "not probed", never "missing". Drives the AI Providers page card colors and grouping — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. `resolvesOutsidePortosPath(provider)` — does this provider resolve its binary somewhere the runtime probe never looked (an explicit path in `command`, or its own `PATH` in `envVars`)? Mirror of the same two guards in the server's `providerRuntimeKey`, and what keeps the card's badge from accusing a working provider the router happily routes. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. |
| `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |
## Module loading / resilience
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 7e74a27041..3faeaef8a7 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -981,20 +981,21 @@ export const isOllamaBackedProvider = (provider) => {
export const isOrcaRouterBackedProvider = (provider) => provider?.orcarouterBacked === true;
// Environment variables whose names are conventionally credentials. The
-// explicit secretEnvVars list remains the primary source; this small fallback
-// covers shipped providers such as Claude-Ollama, whose fixed local token is
-// useful but not marked secret in the catalog.
-const CREDENTIAL_ENV_VAR_RE = /(?:^|_)(?:API_KEY|AUTH_TOKEN|ACCESS_TOKEN|BEARER_TOKEN|CLIENT_SECRET|PASSWORD|TOKEN|SECRET)(?:_|$)/i;
+// explicit secretEnvVars list remains the primary source, but it is a masking
+// list rather than a credential schema — providers may mark optional values
+// such as AWS_PROFILE secret too. Filter both sources so only actual credential
+// names participate in readiness.
+const CREDENTIAL_ENV_VAR_RE = /(?:^|_)(?:API_KEY|APIKEY|AUTH|ACCESS_KEY|ACCESS_TOKEN|BEARER|CLIENT_SECRET|CREDENTIALS?|PASSWORD|PRIVATE_KEY|SECRET|TOKEN)(?:_|$)/i;
const providerHasStoredKey = (provider) =>
provider?.hasApiKey === true || Boolean(provider?.apiKey);
-const credentialEnvVar = (provider) => {
+const credentialEnvVars = (provider) => {
+ if (!isProcessProvider(provider)) return [];
const envVars = provider?.envVars && typeof provider.envVars === 'object' ? provider.envVars : {};
const secretEnvVars = Array.isArray(provider?.secretEnvVars) ? provider.secretEnvVars : [];
- const explicit = secretEnvVars.find((name) => typeof name === 'string' && name !== '');
- if (explicit) return explicit;
- return Object.keys(envVars).find((name) => CREDENTIAL_ENV_VAR_RE.test(name)) || null;
+ const names = [...secretEnvVars, ...Object.keys(envVars)];
+ return [...new Set(names.filter((name) => typeof name === 'string' && CREDENTIAL_ENV_VAR_RE.test(name)))];
};
/**
@@ -1013,13 +1014,20 @@ export const credentialSource = (provider) => {
if (isApiProvider(provider) && isPrivateNetworkEndpoint(provider?.endpoint)) {
return { kind: 'none', ref: null };
}
- if (providerHasStoredKey(provider)) {
+ // API providers are the only ordinary providers whose stored key is read by
+ // PortOS itself. A legacy apiKey on a CLI/TUI record is not passed to the
+ // process and must not hide an empty process credential.
+ if (isApiProvider(provider)) {
return { kind: 'stored', ref: provider?.id || null };
}
- const envVar = credentialEnvVar(provider);
+ // An OrcaRouter wrapper with its own key is the one process-backed exception:
+ // withOrcaRouterApiKey leaves it untouched, so that key really is used.
+ if (isOrcaRouterBackedProvider(provider) && providerHasStoredKey(provider)) {
+ return { kind: 'stored', ref: provider?.id || null };
+ }
+ const [envVar] = credentialEnvVars(provider);
if (envVar) return { kind: 'env', ref: envVar };
if (isOrcaRouterBackedProvider(provider)) return { kind: 'inherited', ref: 'orcarouter' };
- if (isApiProvider(provider)) return { kind: 'stored', ref: provider?.id || null };
return { kind: 'none', ref: null };
};
@@ -1043,9 +1051,20 @@ const credentialMissing = (provider, { keySetFor = null, envVarSet = null } = {}
const source = credentialSource(provider);
if (source.kind === 'none' || !source.ref) return null;
- const rawState = source.kind === 'env'
- ? (typeof envVarSet === 'function' ? envVarSet(source.ref) : defaultEnvVarSet(provider, source.ref))
- : (typeof keySetFor === 'function' ? keySetFor(source.ref) : defaultKeySetFor(provider, source.ref));
+ if (source.kind === 'env') {
+ return credentialEnvVars(provider)
+ .map((name) => {
+ const rawState = typeof envVarSet === 'function' ? envVarSet(name) : defaultEnvVarSet(provider, name);
+ return normalizeCredentialState(rawState) === false
+ ? { code: 'envVar', label: `${name} environment variable is not set` }
+ : null;
+ })
+ .filter(Boolean);
+ }
+
+ const rawState = typeof keySetFor === 'function'
+ ? keySetFor(source.ref)
+ : defaultKeySetFor(provider, source.ref);
if (normalizeCredentialState(rawState) !== false) return null;
if (source.kind === 'stored') return { code: 'apiKey', label: 'API key is not set' };
@@ -1150,7 +1169,9 @@ export const providerCardState = (provider, {
const published = Array.isArray(provider?.missingPrerequisites) ? provider.missingPrerequisites : null;
const missing = published ? [...published] : [];
const addMissing = (code, label) => {
- if (!missing.some((entry) => entry?.code === code)) missing.push({ code, label });
+ if (!missing.some((entry) => entry?.code === code && (code !== 'envVar' || entry?.label === label))) {
+ missing.push({ code, label });
+ }
};
// Kept client-side even when the server has published: `runtime` here may be
@@ -1178,7 +1199,9 @@ export const providerCardState = (provider, {
const source = credentialSource(provider);
if (!published || source.kind === 'env') {
const missingCredential = credentialMissing(provider, { keySetFor, envVarSet });
- if (missingCredential) addMissing(missingCredential.code, missingCredential.label);
+ for (const entry of Array.isArray(missingCredential) ? missingCredential : [missingCredential]) {
+ if (entry) addMissing(entry.code, entry.label);
+ }
}
if (missing.length > 0) return { state: PROVIDER_CARD_STATE.BLOCKED, missing };
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 1fb7a3107c..38937657d6 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -1235,6 +1235,16 @@ describe('credentialSource', () => {
})).toEqual({ kind: 'env', ref: 'ANTHROPIC_AUTH_TOKEN' });
});
+ it('does not treat API env settings or legacy process keys as credentials', () => {
+ expect(credentialSource({
+ id: 'cloud', type: 'api', endpoint: 'https://api.example.com/v1',
+ envVars: { OPENAI_API_KEY: 'token-example' },
+ })).toEqual({ kind: 'stored', ref: 'cloud' });
+ expect(credentialSource({
+ id: 'custom-cli', type: 'cli', apiKey: 'legacy-key', envVars: {},
+ })).toEqual({ kind: 'none', ref: null });
+ });
+
it('lets a wrapper carrying its own key stand down from inheritance', () => {
expect(credentialSource({ id: 'wrapper', type: 'cli', apiKey: 'sk-example', orcarouterBacked: true }))
.toEqual({ kind: 'stored', ref: 'wrapper' });
@@ -1351,6 +1361,41 @@ describe('providerCardState', () => {
})).state).toBe(PROVIDER_CARD_STATE.READY);
});
+ it('does not let a legacy CLI key satisfy an empty process credential', () => {
+ const readiness = providerCardState(cli({
+ apiKey: 'legacy-key',
+ envVars: { AWS_BEARER_TOKEN_BEDROCK: '' },
+ secretEnvVars: ['AWS_BEARER_TOKEN_BEDROCK'],
+ }));
+ expect(readiness.missing).toEqual([{
+ code: 'envVar',
+ label: 'AWS_BEARER_TOKEN_BEDROCK environment variable is not set',
+ }]);
+ });
+
+ it('ignores optional secret env settings and checks every credential variable', () => {
+ const readiness = providerCardState(cli({
+ envVars: {
+ AWS_PROFILE: '',
+ AWS_ACCESS_KEY_ID: 'key-example',
+ AWS_SECRET_ACCESS_KEY: '',
+ },
+ secretEnvVars: ['AWS_PROFILE', 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'],
+ }));
+ expect(readiness.missing).toEqual([{
+ code: 'envVar',
+ label: 'AWS_SECRET_ACCESS_KEY environment variable is not set',
+ }]);
+ });
+
+ it('does not use API env settings in place of the stored API key', () => {
+ const readiness = providerCardState(cloudApi({
+ hasApiKey: false,
+ envVars: { OPENAI_API_KEY: 'token-example' },
+ }));
+ expect(readiness.missing).toEqual([{ code: 'apiKey', label: 'API key is not set' }]);
+ });
+
it('does not treat an unknown env lookup as a missing credential', () => {
expect(providerCardState(cli({
id: 'claude-code-bedrock',
diff --git a/server/lib/README.md b/server/lib/README.md
index 563201ec8f..8f126384e6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -109,7 +109,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `aiProvider.js` | Shared AI provider utilities for LLM calls. |
| `promptRunner.js` | Shared LLM runner wrapper. |
| `providerCooldown.js` | Provider bench policy — `resolveProviderBench(analysis)` → `null` (don't bench) / a `usage-limit` marker / an `unavailable` marker with the per-category cooldown from `COOLDOWN_MS_BY_CATEGORY`. Declines to bench request/response-specific categories (`isRequestSpecificCategory` / `isSchemaTypeCategory`) so one bad model id or off-shape response can't take a healthy provider offline. Shared by `promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. |
-| `providerPrerequisites.js` | Can a provider run on this host AT ALL — `providerPrerequisites(provider, { runtime, orcaRouterKeySet })` → `{ met, missing: [{ code, label }] }` (CLI binary on PATH, API key stored for a public endpoint, the sibling key an OrcaRouter wrapper inherits), plus `providerRuntimeKey` (`null` for an API provider, for a command carrying an explicit path, and for a provider with its own `PATH` in `envVars` — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), `isPrivateNetworkEndpoint` (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/`.ts.net`/single-label hosts need no key) and `describeMissingPrerequisites`. `runtime: null` = NOT PROBED and never counts as missing. Feeds BOTH `GET /api/providers` and the fallback chain in `aiToolkit/providerStatus.js` (via `services/providerPrerequisites.js`), so a `NEEDS SETUP` card and the router read one computation (#4611). `ROUTING_BLOCKING_CODES`/`blocksRouting(missing)` narrow what ROUTING may act on to the missing binary — a credential finding stays presentation-only until #4612 teaches this module about env-var credentials, since a provider can authenticate through one. Pure. |
+| `providerPrerequisites.js` | Can a provider run on this host AT ALL — `providerPrerequisites(provider, { runtime, orcaRouterKeySet })` → `{ met, missing: [{ code, label }] }` (CLI binary on PATH, API key stored for a public endpoint, the sibling key an OrcaRouter wrapper inherits unless it carries its own), plus `providerRuntimeKey` (`null` for an API provider, for a command carrying an explicit path, and for a provider with its own `PATH` in `envVars` — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), `isPrivateNetworkEndpoint` (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/`.ts.net`/single-label hosts need no key) and `describeMissingPrerequisites`. `runtime: null` = NOT PROBED and never counts as missing. Feeds BOTH `GET /api/providers` and the fallback chain in `aiToolkit/providerStatus.js` (via `services/providerPrerequisites.js`), so a `NEEDS SETUP` card and the router read one computation (#4611). `ROUTING_BLOCKING_CODES`/`blocksRouting(missing)` narrow what ROUTING may act on to the missing binary. Stored, inherited, and environment-backed credential findings stay presentation-only here because the server cannot assume the eventual process environment; the client card classifies sanitized env metadata through tri-state lookups (#4612). Pure. |
| `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). |
| `tuiShellLaunch.js` | `buildTuiShellLaunch(provider)` → `{ commandLine, env }` for launching a TUI provider by hand in a Shell session (the AI Providers card's "Launch in Shell" button). Resolves the command via `tuiHandshake.js#buildTuiInvocation` (so the vendor posture flags and `--model`/`--effort` injection match a real TUI spawn) and the env via `cliChildEnv.js#composeProviderEnv`. **The env is why this is server-side and the deep link carries only a provider ID**: a TUI provider's backend lives in `envVars` (`ANTHROPIC_BASE_URL` for an Ollama-backed or Bedrock `claude`, `OPENCODE_CONFIG_CONTENT` for an OpenCode wrapper), so a shell handed only the command line would run the right binary against the vendor cloud instead of the local daemon the user configured — and those values are secret, so they can't ride a URL. Returns null for a non-TUI provider. Must be given a RAW provider, never a client-sanitized one (redacted `'***'` env reads truthy). |
| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. Also owns `SUBMIT_KEY` — the single Enter byte every PTY writer sends, whether it's submitting a pasted TUI prompt or a command PortOS injected into a shell session. It is CR, never LF: a POSIX pty's ICRNL hides the difference, but cmd.exe under Windows ConPTY accepts only CR and leaves an LF-terminated line typed-but-unexecuted at the prompt. |