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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat([issue-5637]): add a Settings Credentials page for presence and source (#5898)
atomanticagenta05886f85d2c
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex fe8e15bd9a..0546f156c6 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -68,6 +68,7 @@ import {Database,Shield,ShieldCheck,+ KeyRound,Lock,Wand2,Rocket,@@ -295,6 +296,7 @@ export const NAV_PRESENTATION = {'/api-reference/catalog': { icon: Braces },'/settings/autofixer': { icon: Wrench },'/settings/backup': { icon: Download },+ '/settings/credentials': { icon: KeyRound },'/models/code-reviewers': { icon: ShieldCheck },'/settings/database': { icon: Database },'/settings/features': { icon: ListChecks },diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex 963338b3c4..f0c74e6f23 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -136,7 +136,7 @@ describe('Layout — manifest-derived sidebar structure', () => {it('covers all sub-tabs for Settings, Digital Twin, and Messages in NAV_PRESENTATION', () => {const settingsPaths = ['/settings/general', '/settings/ai-assignments', '/settings/api-access', '/settings/autofixer',- '/settings/backup', '/settings/database', '/settings/features',+ '/settings/backup', '/settings/credentials', '/settings/database', '/settings/features','/settings/security', '/settings/sharing','/settings/telegram', '/settings/voice', '/settings/mortalloom','/openclaw', '/prompts', '/ai'diff --git a/client/src/components/settings/CredentialsTab.jsx b/client/src/components/settings/CredentialsTab.jsxnew file mode 100644index 0000000000..3661f9bac2--- /dev/null+++ b/client/src/components/settings/CredentialsTab.jsx@@ -0,0 +1,141 @@+import { useEffect, useState } from 'react';+import { Link } from 'react-router';+import { ExternalLink } from 'lucide-react';+import BrailleSpinner from '../BrailleSpinner';+import { getCredentialInventory } from '../../services/api';++const SOURCE_LABEL = {+ settings: 'Settings',+ 'env-file': '.env',+ env: 'Configured externally',+ cli: 'CLI / keychain',+ config: 'Instance config',+ none: 'Not configured',+};++const TIER_LABEL = {+ free: 'Free',+ metered: 'Metered',+ none: 'No key',+};++export function CredentialsTab() {+ const [payload, setPayload] = useState(null);+ const [error, setError] = useState(null);++ const load = () => {+ setError(null);+ getCredentialInventory({ silent: true })+ .then((data) => {+ setPayload(data);+ })+ .catch((err) => {+ setError(err);+ });+ };++ useEffect(() => {+ load();+ }, []);++ if (error) {+ return (+ <div className="space-y-3 max-w-3xl">+ <p className="text-sm text-port-error">{error.message || 'Failed to load credentials'}</p>+ <button+ type="button"+ onClick={load}+ className="inline-flex items-center justify-center min-h-[44px] px-3 text-sm bg-port-border hover:bg-port-border/70 text-white rounded transition-colors"+ >+ Retry+ </button>+ </div>+ );+ }++ if (payload == null) return <BrailleSpinner text="Loading credentials" />;++ const credentials = payload.credentials || [];++ return (+ <div className="space-y-6 max-w-3xl">+ <div>+ <h2 className="text-lg font-semibold text-white">Credentials</h2>+ <p className="text-sm text-gray-400 mt-1">+ {payload.headline || 'Most of PortOS works with no key at all.'}+ {' '}+ This page shows presence and where a value resolved from — never the value itself. Enter or rotate a secret on its existing settings tab.+ </p>+ </div>++ <div className="space-y-3">+ {credentials.map((credential) => {+ const configured = credential.configured === true;+ return (+ <div+ key={credential.id}+ className="bg-port-card border border-port-border rounded-lg p-4 space-y-2"+ >+ <div className="flex flex-wrap items-start justify-between gap-2">+ <div className="min-w-0">+ <h3 className="text-sm font-semibold text-white">{credential.label}</h3>+ <p className="text-sm text-gray-400 mt-1">{credential.unlocks}</p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ <span className={`inline-flex items-center min-h-[28px] px-2 rounded text-xs ${configured ? 'bg-emerald-500/15 text-emerald-300' : 'bg-port-border/60 text-gray-400'}`}>+ {configured ? 'Configured' : 'Not configured'}+ </span>+ <span className="inline-flex items-center min-h-[28px] px-2 rounded text-xs bg-port-bg text-gray-400">+ {SOURCE_LABEL[credential.source] || SOURCE_LABEL.none}+ </span>+ {credential.tier && credential.tier !== 'none' && (+ <span className="inline-flex items-center min-h-[28px] px-2 rounded text-xs bg-port-bg text-gray-500">+ {TIER_LABEL[credential.tier] || credential.tier}+ </span>+ )}+ </div>+ </div>++ {credential.unavailableFeatures?.length > 0 && (+ <p className="text-xs text-amber-300/90">+ Currently unavailable:+ {' '}+ {credential.unavailableFeatures.map((feature) => feature.label).join(', ')}+ </p>+ )}++ <div className="flex flex-wrap gap-2 pt-1">+ {credential.configurePath && (+ <Link+ to={credential.configurePath}+ className="inline-flex items-center justify-center min-h-[44px] px-3 text-sm bg-port-border hover:bg-port-border/70 text-white rounded transition-colors"+ >+ Open {credential.label} settings+ </Link>+ )}+ {credential.getUrl && (+ <a+ href={credential.getUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center justify-center gap-1 min-h-[44px] px-3 text-sm text-port-accent hover:underline"+ >+ Get a key+ <ExternalLink size={14} />+ </a>+ )}+ </div>+ </div>+ );+ })}+ {credentials.length === 0 && (+ <div className="bg-port-card border border-port-border rounded-lg p-4 text-sm text-gray-400">+ No credentials are registered for this version of PortOS.+ </div>+ )}+ </div>+ </div>+ );+}++export default CredentialsTab;diff --git a/client/src/components/settings/CredentialsTab.test.jsx b/client/src/components/settings/CredentialsTab.test.jsxnew file mode 100644index 0000000000..40ecfed210--- /dev/null+++ b/client/src/components/settings/CredentialsTab.test.jsx@@ -0,0 +1,65 @@+import { describe, expect, it, beforeEach, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';++const mock = vi.hoisted(() => ({+ getCredentialInventory: vi.fn(),+}));++vi.mock('../../services/api', () => mock);++import CredentialsTab from './CredentialsTab';++const PAYLOAD = {+ headline: 'Most of PortOS works with no key at all.',+ credentials: [+ {+ id: 'huggingface',+ label: 'Hugging Face',+ unlocks: 'Authenticated model downloads.',+ tier: 'free',+ getUrl: 'https://huggingface.co/settings/tokens',+ configurePath: '/media/image?settings=1',+ feature: null,+ configured: true,+ source: 'settings',+ unavailableFeatures: [],+ },+ {+ id: 'jira',+ label: 'JIRA',+ unlocks: 'Sprint boards.',+ tier: 'metered',+ getUrl: 'https://id.atlassian.com/manage-profile/security/api-tokens',+ configurePath: '/devtools/jira',+ feature: 'jira',+ configured: false,+ source: 'none',+ unavailableFeatures: [{ id: 'jira', label: 'JIRA' }],+ },+ ],+};++describe('CredentialsTab', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mock.getCredentialInventory.mockResolvedValue(PAYLOAD);+ });++ it('renders presence and source, never a secret value, and links out to the existing tab', async () => {+ render(+ <MemoryRouter>+ <CredentialsTab />+ </MemoryRouter>,+ );++ expect(await screen.findByText(/Most of PortOS works with no key at all/)).toBeTruthy();+ expect(screen.getByText('Hugging Face')).toBeTruthy();+ expect(screen.getByText('Configured')).toBeTruthy();+ expect(screen.getByText('Settings')).toBeTruthy();+ expect(screen.getByRole('link', { name: 'Open Hugging Face settings' })).toHaveAttribute('href', '/media/image?settings=1');+ expect(screen.getByText('Currently unavailable: JIRA')).toBeTruthy();+ expect(screen.queryByText(/hf_/)).toBeNull();+ expect(JSON.stringify(PAYLOAD)).not.toMatch(/hf_this/);+ });+});diff --git a/client/src/components/settings/SettingsTabsHeader.jsx b/client/src/components/settings/SettingsTabsHeader.jsxindex 3d410032e6..9354216c69 100644--- a/client/src/components/settings/SettingsTabsHeader.jsx+++ b/client/src/components/settings/SettingsTabsHeader.jsx@@ -14,6 +14,7 @@ export const TABS = [{ id: 'api-access', label: 'API Access', to: '/settings/api-access' },{ id: 'autofixer', label: 'Autofixer', to: '/settings/autofixer' },{ id: 'backup', label: 'Backup', to: '/settings/backup' },+ { id: 'credentials', label: 'Credentials', to: '/settings/credentials' },{ id: 'database', label: 'Database', to: '/settings/database' },{ id: 'features', label: 'Features', to: '/settings/features' },{ id: 'general', label: 'General', to: '/settings/general' },diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsxindex 96ccac918a..cc5a7c1764 100644--- a/client/src/pages/Settings.jsx+++ b/client/src/pages/Settings.jsx@@ -7,6 +7,7 @@ import AiAssignmentsTab from '../components/settings/AiAssignmentsTab';import { BackupTab } from '../components/settings/BackupTab';import { DatabaseTab } from '../components/settings/DatabaseTab';import InstanceFeaturesTab from '../components/settings/InstanceFeaturesTab';+import CredentialsTab from '../components/settings/CredentialsTab';import { TelegramTab } from '../components/settings/TelegramTab';import { GeneralTab } from '../components/settings/GeneralTab';import { MortalLoomTab } from '../components/settings/MortalLoomTab';@@ -43,6 +44,7 @@ export default function Settings() {case 'autofixer': return <AutofixerTab />;case 'backup': return <BackupTab />;case 'database': return <DatabaseTab />;+ case 'credentials': return <CredentialsTab />;case 'features': return <InstanceFeaturesTab />;case 'security': return <SecurityTab />;case 'sharing': return <SharingTab />;diff --git a/client/src/pages/Settings.tabs.test.jsx b/client/src/pages/Settings.tabs.test.jsxindex 01fe3a048b..c21fa8993d 100644--- a/client/src/pages/Settings.tabs.test.jsx+++ b/client/src/pages/Settings.tabs.test.jsx@@ -16,6 +16,9 @@ vi.mock('../components/settings/GeneralTab', () => ({vi.mock('../components/settings/InstanceFeaturesTab', () => ({default: () => <div data-testid="instance-features-tab" />,}));+vi.mock('../components/settings/CredentialsTab', () => ({+ default: () => <div data-testid="credentials-tab" />,+}));const Settings = (await import('./Settings')).default;@@ -51,3 +54,17 @@ describe('Settings — MortalLoom tab', () => {expect(tab).toMatchObject({ to: '/settings/mortalloom', feature: 'health' });});});++describe('Settings — Credentials tab', () => {+ it('is listed in the settings sub-nav', () => {+ const tab = TABS.find(t => t.id === 'credentials');+ expect(tab?.to).toBe('/settings/credentials');+ });++ it('routes /settings/credentials to the credential inventory', async () => {+ renderTab('/settings/credentials');+ await act(async () => {});+ expect(screen.getByTestId('credentials-tab')).toBeTruthy();+ expect(screen.queryByTestId('general-tab')).toBeNull();+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 9dc448f9fa..2ed0d3c7ff 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -63,7 +63,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiSchedules.js` | Automation schedules. || `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`), plus `rearmQuotaBurn` to put spent `run once` steps back into the rotation. || `apiRapidReader.js` | Rapid Reader's optional author-hosted Accelerando loader and machine-local shelf API. |-| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). |+| `apiSystem.js` | System info (CPU/memory/ports/alerts/active processing and local hardware capabilities) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`, `updateSubscriptionCosts` for the subscription-vs-API savings comparison, `updateUsageFleetBilling` to exclude an API-billed federated instance from Across Instances totals). Also `getCredentialInventory` (`GET /settings/credentials`) — presence and source of each PortOS credential, never a value. || `apiAuth.js` | Optional login password — status, login, set/clear password. || `apiLoops.js` | Scheduled loops. |diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 9171e18950..e7347c8dec 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -70,6 +70,7 @@ export const syncPortosFork = (opts = {}, requestOpts = {}) => request('/update/// Settingsexport const getSettings = (options) => request('/settings', options);export const getInstanceFeatures = (options) => request('/settings/features', options);+export const getCredentialInventory = (options) => request('/settings/credentials', options);export const updateInstanceFeature = (featureId, enabled, options = {}) => request(`/settings/features/${encodeURIComponent(featureId)}`, {method: 'PUT',body: JSON.stringify({ enabled }),diff --git a/server/lib/README.md b/server/lib/README.mdindex 825c66020b..f9f05618dd 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -169,6 +169,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. || `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). || `subscriptionSavings.js` | Subscription-vs-API savings math for the usage page — `resolveSavingsWindow` (clamps an open-ended report range to today / first activity day), `prorateMonthlyCost` (monthly plan price → this window's share, `DAYS_PER_MONTH`, capped by `MAX_MONTHLY_COST`), `savingsPercent` / `costMultiplier` (null, never 0, when the comparison is undefined), `attributeReportCostToFamilies` (groups report rows by their stamped `family`), `roundCents` (the one money rounder), and `buildSubscriptionSavings({ entries, range, unmatchedApiCost })` → per-family rows + totals. Pure. |+| `credentialRegistry.js` | Pure catalog of PortOS credentials (`CREDENTIALS`, `CREDENTIAL_IDS`, `CREDENTIAL_TIERS`) — one entry per key/token an install can use (`id`, `label`, `unlocks`, `tier`, `getUrl`, `envVars`, `settingsPath`, `configurePath`, optional `feature`). Sits beside `instanceFeatureRegistry.js` so the two lists stay greppable together. Runtime resolution (settings / repo `.env` / inherited `process.env` / CLI / instance config) lives in `services/credentialInventory.js`. The Settings > Credentials page never receives a value or masked prefix. || `instanceFeatureRegistry.js` | The registry of optional per-install features (`INSTANCE_FEATURES`, `INSTANCE_FEATURE_IDS`, `APP_FEATURE_IDS`) — pure data, so `validation.js` derives its feature schemas from it and `navManifest.js` can be checked against it without a service→lib inversion. Runtime resolution (stored override → auto-detection → `defaultEnabled`) lives in `services/instanceFeatures.js`. A feature id tagged on a nav entry hides that page from ⌘K and the sidebar when the feature is off. || `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. || `providerGateways.js` | `PROVIDER_GATEWAYS` — one row per hosted OpenAI-compatible gateway an OpenCode CLI/TUI wrapper can front-end (`orcarouter`, `openrouter`), plus `PROVIDER_GATEWAY_IDS`, `gatewayById`, `isGatewayNamespace(ns)` and `gatewayForProvider(config)` → row or null. Each row's `id` is simultaneously the OpenCode provider namespace, the `gatewayBacked` marker value, and the id of the sibling `api` record that owns the key — so the sibling lookup is `providers[gateway.id]` and an OrcaRouter key can never satisfy an OpenRouter wrapper. Replaces the `orcarouterBacked` boolean + literal `'orcarouter'` that had been hand-copied across ~15 server and client files (namespace resolution, the OpenCode config builder, both zod schemas, the model-fetcher table, the sibling-key attach, the prerequisite check, and the two "not a local runtime" carve-outs in `cliChildEnv.js`/`localProviderRuntime.js`). Reads the legacy per-gateway boolean FOREVER, so stored records are never rewritten. Distinct from a local runtime (`ollamaBacked`, `vllmBacked`, …): remote, always authenticating, and no thinking toggle. Deliberately mirrored in `aiToolkit/internal/gateways.js` (the vendored toolkit may not import out) and `client/src/utils/providers.js` (the browser cannot import server code) — `providerGateways.parity.test.js` fails when the first two drift. Dependency-light: imports nothing. |diff --git a/server/lib/credentialRegistry.js b/server/lib/credentialRegistry.jsnew file mode 100644index 0000000000..a915f66227--- /dev/null+++ b/server/lib/credentialRegistry.js@@ -0,0 +1,204 @@+// The registry of PortOS credentials — the single list Settings > Credentials+// renders. Pure data, no I/O, so a lib and a service can read it without a+// service→lib inversion. Runtime resolution — settings store, repo `.env`,+// inherited process.env, CLI/keychain, instance config — lives in+// `server/services/credentialInventory.js`.+//+// Ordered most-value-first. Adding a credential:+// 1. add a descriptor here;+// 2. point `configurePath` at the existing per-integration tab (this page+// never collects a secret);+// 3. tag `feature` when an instance-feature id from instanceFeatureRegistry+// stays dark without it.+// Presence and source only. Never the value, and not a masked prefix either.++export const CREDENTIAL_TIERS = Object.freeze(['free', 'metered', 'none']);++export const CREDENTIALS = Object.freeze([+ Object.freeze({+ id: 'huggingface',+ label: 'Hugging Face',+ unlocks: 'Authenticated model, LoRA, and 3D-asset downloads (FLUX, LTX, Trellis, and gated Hub repos).',+ tier: 'free',+ getUrl: 'https://huggingface.co/settings/tokens',+ envVars: Object.freeze(['HF_TOKEN', 'HUGGINGFACE_HUB_TOKEN', 'HUGGINGFACEHUB_API_TOKEN', 'HUGGINGFACE_TOKEN']),+ settingsPath: 'imageGen.hfToken',+ configurePath: '/media/image?settings=1',+ }),+ Object.freeze({+ id: 'github',+ label: 'GitHub',+ unlocks: 'CoS agent PRs, `gh` on spawned CLIs, and the GitHub Dev Tools page.',+ tier: 'free',+ getUrl: 'https://github.com/settings/tokens',+ envVars: Object.freeze(['GH_TOKEN', 'GITHUB_TOKEN']),+ settingsPath: null,+ configurePath: '/devtools/github',+ }),+ Object.freeze({+ id: 'anthropic',+ label: 'Anthropic / Claude',+ unlocks: 'Claude Code CLI/TUI coding agents and cloud Claude text.',+ tier: 'metered',+ getUrl: 'https://console.anthropic.com/settings/keys',+ envVars: Object.freeze(['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']),+ settingsPath: null,+ configurePath: '/ai',+ }),+ Object.freeze({+ id: 'openai',+ label: 'OpenAI / Codex',+ unlocks: 'Codex CLI/TUI coding agents and OpenAI API text.',+ tier: 'metered',+ getUrl: 'https://platform.openai.com/api-keys',+ envVars: Object.freeze(['OPENAI_API_KEY']),+ settingsPath: null,+ configurePath: '/ai',+ }),+ Object.freeze({+ id: 'google',+ label: 'Google / Gemini',+ unlocks: 'Antigravity / Gemini CLI coding agents and Google AI image/text.',+ tier: 'metered',+ getUrl: 'https://aistudio.google.com/apikey',+ envVars: Object.freeze(['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_GENAI_API_KEY']),+ settingsPath: null,+ configurePath: '/ai',+ }),+ Object.freeze({+ id: 'xai',+ label: 'xAI / Grok',+ unlocks: 'Grok CLI/TUI coding agents and grok image/video.',+ tier: 'metered',+ getUrl: 'https://console.x.ai/',+ envVars: Object.freeze(['XAI_API_KEY', 'GROK_API_KEY']),+ settingsPath: null,+ configurePath: '/ai',+ }),+ Object.freeze({+ id: 'civitai',+ label: 'CivitAI',+ unlocks: 'LoRA and checkpoint downloads from civitai.com.',+ tier: 'free',+ getUrl: 'https://civitai.com/user/account',+ envVars: Object.freeze(['CIVITAI_API_KEY']),+ settingsPath: 'civitai.apiKey',+ configurePath: '/models/loras',+ }),+ Object.freeze({+ id: 'telegram',+ label: 'Telegram',+ unlocks: 'Outbound Telegram notifications and the MCP bridge bot.',+ tier: 'free',+ getUrl: 'https://t.me/BotFather',+ envVars: Object.freeze(['TELEGRAM_BOT_TOKEN']),+ settingsPath: 'secrets.telegram.token',+ configurePath: '/settings/telegram',+ }),+ Object.freeze({+ id: 'jira',+ label: 'JIRA',+ unlocks: 'Sprint boards, ticket triage, and JIRA reports.',+ tier: 'metered',+ getUrl: 'https://id.atlassian.com/manage-profile/security/api-tokens',+ envVars: Object.freeze([]),+ settingsPath: null,+ configurePath: '/devtools/jira',+ feature: 'jira',+ }),+ Object.freeze({+ id: 'datadog',+ label: 'DataDog',+ unlocks: 'Error-monitoring dashboards for apps wired to a DataDog instance.',+ tier: 'metered',+ getUrl: 'https://app.datadoghq.com/organization-settings/api-keys',+ envVars: Object.freeze([]),+ settingsPath: null,+ configurePath: '/devtools/datadog',+ feature: 'datadog',+ }),+ Object.freeze({+ id: 'spotify',+ label: 'Spotify',+ unlocks: 'Listening-history ingest for Brain / Digital Twin taste.',+ tier: 'free',+ getUrl: 'https://developer.spotify.com/dashboard',+ envVars: Object.freeze([]),+ settingsPath: null,+ configurePath: '/brain/spotify',+ }),+ Object.freeze({+ id: 'youtube',+ label: 'YouTube',+ unlocks: 'Watch-history ingest from a signed-in managed browser.',+ tier: 'free',+ getUrl: 'https://www.youtube.com/',+ envVars: Object.freeze([]),+ settingsPath: 'youtube.enabled',+ configurePath: '/brain/youtube',+ }),+ Object.freeze({+ id: 'signal',+ label: 'Signal',+ unlocks: 'Local Signal Desktop chat ingest for Tribe and the life timeline.',+ tier: 'none',+ getUrl: 'https://signal.org/download/',+ envVars: Object.freeze(['SIGNAL_DIR', 'SIGNAL_CONFIG_PATH', 'SIGNAL_KEYCHAIN_PASSWORD']),+ settingsPath: null,+ configurePath: '/messages/signal',+ }),+ Object.freeze({+ id: 'stacker-news',+ label: 'Stacker News',+ unlocks: 'Territory stewardship, item ingest, and approved SN actions.',+ tier: 'free',+ getUrl: 'https://stacker.news/settings',+ envVars: Object.freeze([]),+ settingsPath: null,+ configurePath: '/stacker-news',+ }),+ Object.freeze({+ id: 'mortalloom',+ label: 'MortalLoom',+ unlocks: 'iCloud MortalLoom.json import into Health tracking.',+ tier: 'none',+ getUrl: null,+ envVars: Object.freeze([]),+ settingsPath: 'mortalloom.path',+ configurePath: '/settings/mortalloom',+ feature: 'health',+ }),+ Object.freeze({+ id: 'openclaw',+ label: 'OpenClaw',+ unlocks: 'Operator chat with a configured OpenClaw runtime.',+ tier: 'none',+ getUrl: null,+ envVars: Object.freeze(['OPENCLAW_AUTH_TOKEN', 'OPENCLAW_BASE_URL']),+ settingsPath: null,+ configurePath: '/openclaw',+ feature: 'openclaw',+ }),+ Object.freeze({+ id: 'cursor',+ label: 'Cursor',+ unlocks: 'cursor-agent CLI coding agents.',+ tier: 'metered',+ getUrl: 'https://cursor.com/dashboard',+ envVars: Object.freeze(['CURSOR_API_KEY']),+ settingsPath: null,+ configurePath: '/ai',+ }),+ Object.freeze({+ id: 'kimi',+ label: 'Kimi / Moonshot',+ unlocks: 'Kimi Code CLI/TUI coding agents.',+ tier: 'metered',+ getUrl: 'https://platform.moonshot.ai/console/api-keys',+ envVars: Object.freeze(['KIMI_API_KEY', 'MOONSHOT_API_KEY']),+ settingsPath: null,+ configurePath: '/ai',+ }),+]);++export const CREDENTIAL_IDS = Object.freeze(CREDENTIALS.map((credential) => credential.id));diff --git a/server/lib/credentialRegistry.test.js b/server/lib/credentialRegistry.test.jsnew file mode 100644index 0000000000..ebe35667da--- /dev/null+++ b/server/lib/credentialRegistry.test.js@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';+import { CREDENTIALS, CREDENTIAL_IDS, CREDENTIAL_TIERS } from './credentialRegistry.js';+import { INSTANCE_FEATURE_IDS } from './instanceFeatureRegistry.js';++describe('credentialRegistry', () => {+ it('exports unique ids in most-value-first order with a stable huggingface lead', () => {+ expect(CREDENTIAL_IDS[0]).toBe('huggingface');+ expect(new Set(CREDENTIAL_IDS).size).toBe(CREDENTIAL_IDS.length);+ });++ it('requires the documented descriptor fields and a known tier', () => {+ for (const entry of CREDENTIALS) {+ expect(entry.id).toMatch(/^[a-z][a-z0-9-]*$/);+ expect(entry.label).toBeTruthy();+ expect(entry.unlocks).toBeTruthy();+ expect(CREDENTIAL_TIERS).toContain(entry.tier);+ expect(Array.isArray(entry.envVars)).toBe(true);+ expect(entry.configurePath).toMatch(/^\//);+ if (entry.getUrl != null) expect(entry.getUrl).toMatch(/^https:\/\//);+ if (entry.feature) expect(INSTANCE_FEATURE_IDS).toContain(entry.feature);+ }+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex aa82e665cf..c67f40c9bd 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -361,6 +361,7 @@ export * from './migrationMarker.js';export * from './modelPricing.js';export * from './navManifest.js';export * from './instanceFeatureRegistry.js';+export * from './credentialRegistry.js';export * from './usageRange.js';export * from './subscriptionSavings.js';export * from './providerFamilies.js';diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex b6b34b7f0d..3992871e12 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -266,6 +266,7 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.devtools.api-explorer', path: '/api-reference/catalog', label: 'API Explorer', section: 'Dev Tools', aliases: ['api-explorer', 'api-reference', 'swagger-ui', 'rest-reference'], keywords: ['openapi', 'rest', 'endpoints', 'routes', 'agent tools', 'contracts', 'developer docs'] },{ id: 'nav.settings.autofixer', path: '/settings/autofixer', label: 'Autofixer', section: 'Settings', aliases: ['autofixer', 'settings-autofixer', 'auto-fixer'], keywords: ['crash', 'fix', 'pm2', 'repair', 'ai provider', 'restart'] },{ id: 'nav.settings.backup', path: '/settings/backup', label: 'Backup', section: 'Settings', aliases: ['backup', 'settings-backup'] },+ { id: 'nav.settings.credentials', path: '/settings/credentials', label: 'Credentials', section: 'Settings', aliases: ['settings-credentials', 'credentials', 'api-keys', 'tokens'], keywords: ['configured', 'unconfigured', 'env', 'huggingface', 'civitai', 'jira', 'datadog', 'telegram'] },{ id: 'nav.settings.database', path: '/settings/database', label: 'Database', section: 'Settings', aliases: ['settings-database', 'database'] },{ id: 'nav.settings.features', path: '/settings/features', label: 'Features', section: 'Settings', aliases: ['settings-features', 'instance-features', 'feature-usage'], keywords: ['enabled', 'disabled', 'instance', 'optional', 'participation', 'metrics', 'reminders'] },{ id: 'nav.settings.general', path: '/settings/general', label: 'General', section: 'Settings', aliases: ['settings', 'settings-general', 'general'] },diff --git a/server/routes/settings.js b/server/routes/settings.jsindex ac2cf67f4b..5be8abb24a 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -12,6 +12,7 @@ import {} from '../services/mediaJobQueue/index.js';import { assertMediaRoutingConfig } from '../services/federatedMedia/routingPolicy.js';import { assertConfiguredEidoverseInstalled, getInstanceFeatures, updateEidoverseWorldsRepo, updateEidoverseWorldsSource, updateInstanceFeature } from '../services/instanceFeatures.js';+import { getCredentialInventory } from '../services/credentialInventory.js';import { installEidoverse } from '../services/eidoverse.js';import { ensureEidoverseHost } from '../services/eidoverseHost.js';import { isGitHubRepoUrl } from '../lib/repoUrl.js';@@ -169,6 +170,13 @@ router.get('/features', asyncHandler(async (_req, res) => {res.json(await getInstanceFeatures());}));+// GET /api/settings/credentials+// Presence + source only. Never a value or masked prefix — the page links out+// to the existing per-integration tab to enter a secret.+router.get('/credentials', asyncHandler(async (_req, res) => {+ res.json(await getCredentialInventory());+}));+// POST /api/settings/features/eidoverse/install// Explicit consent boundary: no Eidoverse checkout or dependency install occurs// until the user presses Install in Settings > Features.diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex f596ecd5a2..ec2b093328 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -58,6 +58,9 @@ vi.mock('../services/eidoverse.js', () => ({vi.mock('../services/eidoverseHost.js', () => ({ensureEidoverseHost: vi.fn(async () => ({ running: true, protocol: 'https', port: 5563 })),}));+vi.mock('../services/credentialInventory.js', () => ({+ getCredentialInventory: vi.fn(async () => ({ headline: 'Most of PortOS works with no key at all.', credentials: [] })),+}));import settingsRoutes from './settings.js';import { updateSettingsWith } from '../services/settings.js';@@ -650,3 +653,29 @@ describe('Settings routes — videoGen slice (#3231 Phase 4)', () => {expect(res.body.videoGen).toEqual({ mode: 'local' });});});++describe('Settings routes — credential inventory', () => {+ it('returns presence and source without secret values', async () => {+ const { getCredentialInventory } = await import('../services/credentialInventory.js');+ getCredentialInventory.mockResolvedValueOnce({+ headline: 'Most of PortOS works with no key at all.',+ credentials: [{+ id: 'huggingface',+ label: 'Hugging Face',+ unlocks: 'Downloads',+ tier: 'free',+ getUrl: 'https://huggingface.co/settings/tokens',+ configurePath: '/media/image?settings=1',+ feature: null,+ configured: true,+ source: 'settings',+ unavailableFeatures: [],+ }],+ });+ const res = await request(buildApp()).get('/api/settings/credentials');+ expect(res.status).toBe(200);+ expect(res.body.headline).toMatch(/no key at all/i);+ expect(res.body.credentials[0]).toMatchObject({ id: 'huggingface', configured: true, source: 'settings' });+ expect(JSON.stringify(res.body)).not.toMatch(/hf_|sk-|ghp_/);+ });+});diff --git a/server/services/credentialInventory.js b/server/services/credentialInventory.jsnew file mode 100644index 0000000000..475b7af7d3--- /dev/null+++ b/server/services/credentialInventory.js@@ -0,0 +1,190 @@+// Runtime resolution for the credential registry in+// server/lib/credentialRegistry.js. One page answers "which of PortOS's+// features are dark on this install, and what credential would light them+// up?" Presence and source only — never the value, and not a masked prefix.+//+// Source vocabulary (most specific first):+// settings — settings.json (or a sibling store the existing tab writes)+// env-file — the install's repo `.env`+// env — inherited process.env (shell / OS / PM2)+// cli — a CLI login (e.g. `hf auth login`)+// config — an instance/account config file that is not settings.json+// none — not configured+// Settings win over env, matching hfToken.js / loras.js. When process.env and+// `.env` carry the same non-empty value, `.env` is the more specific origin.++import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { CREDENTIALS } from '../lib/credentialRegistry.js';+import { INSTANCE_FEATURES } from '../lib/instanceFeatureRegistry.js';+import { PATHS, readJSONFile } from '../lib/fileUtils.js';+import { parseEnvContents } from '../lib/vllmQwenProvision.js';+import { getSettings } from './settings.js';++export const CREDENTIAL_SOURCES = Object.freeze([+ 'settings', 'env-file', 'env', 'cli', 'config', 'none',+]);++const HEADLINE = 'Most of PortOS works with no key at all.';++const isPresent = (value) => {+ if (typeof value === 'boolean') return value === true;+ if (typeof value !== 'string') return false;+ return value.trim().length > 0;+};++const getPath = (obj, path) => {+ if (!path || obj == null || typeof obj !== 'object') return undefined;+ return path.split('.').reduce((acc, key) => (acc == null ? acc : acc[key]), obj);+};++const firstPresentEnvKey = (keys, bag) => {+ if (!Array.isArray(keys) || keys.length === 0) return null;+ return keys.find((key) => isPresent(bag?.[key])) || null;+};++const firstPresentEnvFileKey = (keys, envFile) => {+ if (!Array.isArray(keys) || keys.length === 0 || !envFile) return null;+ return keys.find((key) => isPresent(envFile.get(key))) || null;+};++const classifyEnvSource = (envVars, env, envFile) => {+ const processKey = firstPresentEnvKey(envVars, env);+ const fileKey = firstPresentEnvFileKey(envVars, envFile);+ if (processKey && fileKey && env[processKey] === envFile.get(fileKey)) {+ return { configured: true, source: 'env-file' };+ }+ if (processKey) return { configured: true, source: 'env' };+ if (fileKey) return { configured: true, source: 'env-file' };+ return { configured: false, source: 'none' };+};++export async function loadInstallEnvFile(envPath = join(PATHS.installRoot, '.env')) {+ try {+ return parseEnvContents(await readFile(envPath, 'utf8'));+ } catch {+ return new Map();+ }+}++const detectHuggingFaceCli = async () => {+ const { getHfTokenInfo } = await import('./hfToken.js');+ const { source } = await getHfTokenInfo();+ if (source === 'cli') return { configured: true, source: 'cli' };+ return null;+};++const detectJira = async () => {+ const { hasConfiguredInstances } = await import('./jira.js');+ return (await hasConfiguredInstances()) ? { configured: true, source: 'config' } : null;+};++const detectDatadog = async () => {+ const { hasConfiguredInstances } = await import('./datadog.js');+ return (await hasConfiguredInstances()) ? { configured: true, source: 'config' } : null;+};++const detectSpotify = async () => {+ const { getAuthStatus } = await import('./spotifyAuth.js');+ const status = await getAuthStatus();+ return (status.hasCredentials || status.hasTokens)+ ? { configured: true, source: 'config' }+ : null;+};++const detectStackerNews = async () => {+ const { listAccounts } = await import('./stackerNews.js');+ const accounts = await listAccounts();+ return accounts.some((account) => account.apiKeyConfigured)+ ? { configured: true, source: 'config' }+ : null;+};++const detectOpenclaw = async () => {+ const fileConfig = await readJSONFile(join(PATHS.data, 'openclaw', 'config.json'), {}, { logError: false });+ return (isPresent(fileConfig.authToken) || isPresent(fileConfig.baseUrl))+ ? { configured: true, source: 'config' }+ : null;+};++const DEFAULT_DETECTORS = Object.freeze({+ huggingface: detectHuggingFaceCli,+ jira: detectJira,+ datadog: detectDatadog,+ spotify: detectSpotify,+ 'stacker-news': detectStackerNews,+ openclaw: detectOpenclaw,+});++const resolveFromSettingsAndEnv = (entry, { settings, env, envFile }) => {+ if (entry.settingsPath && isPresent(getPath(settings, entry.settingsPath))) {+ return { configured: true, source: 'settings' };+ }+ return classifyEnvSource(entry.envVars, env, envFile);+};++const publicRow = (entry, resolution, featuresById) => {+ const feature = entry.feature ? featuresById.get(entry.feature) : null;+ const unavailableFeatures = (entry.feature && !resolution.configured && feature)+ ? [{ id: feature.id, label: feature.label }]+ : [];+ return {+ id: entry.id,+ label: entry.label,+ unlocks: entry.unlocks,+ tier: entry.tier,+ getUrl: entry.getUrl,+ configurePath: entry.configurePath,+ feature: entry.feature ?? null,+ configured: resolution.configured,+ source: resolution.source,+ unavailableFeatures,+ };+};++const assertNoSecretPayload = (row) => {+ // Defense in depth: a future detector that accidentally forwarded a token+ // must fail the response rather than render it. Presence flags only.+ for (const value of Object.values(row)) {+ if (typeof value === 'string' && /^(hf_|sk-|ghp_|gho_|github_pat_|xox[baprs]-)/.test(value)) {+ throw new Error(`Credential inventory leaked a secret-shaped value on ${row.id}`);+ }+ }+ return row;+};++export async function getCredentialInventory({+ settings,+ env = process.env,+ envFile,+ features = INSTANCE_FEATURES,+ detectors = {},+} = {}) {+ const resolvedSettings = settings ?? await getSettings();+ const resolvedEnvFile = envFile ?? await loadInstallEnvFile();+ const resolvedDetectors = { ...DEFAULT_DETECTORS, ...detectors };+ const featuresById = new Map((features || []).map((feature) => [feature.id, feature]));++ const credentials = [];+ for (const entry of CREDENTIALS) {+ let resolution = resolveFromSettingsAndEnv(entry, {+ settings: resolvedSettings,+ env,+ envFile: resolvedEnvFile,+ });+ if (!resolution.configured && typeof resolvedDetectors[entry.id] === 'function') {+ const detected = await resolvedDetectors[entry.id](entry, {+ settings: resolvedSettings,+ env,+ envFile: resolvedEnvFile,+ }).catch((error) => {+ console.error(`❌ Credential "${entry.id}" detection failed: ${error.message}`);+ return null;+ });+ if (detected?.configured) resolution = detected;+ }+ credentials.push(assertNoSecretPayload(publicRow(entry, resolution, featuresById)));+ }++ return { headline: HEADLINE, credentials };+}diff --git a/server/services/credentialInventory.test.js b/server/services/credentialInventory.test.jsnew file mode 100644index 0000000000..90e350282a--- /dev/null+++ b/server/services/credentialInventory.test.js@@ -0,0 +1,128 @@+import { describe, expect, it, vi, beforeEach } from 'vitest';++const mock = vi.hoisted(() => ({+ getSettings: vi.fn(async () => ({})),+ getHfTokenInfo: vi.fn(async () => ({ token: null, source: 'none' })),+ jiraConfigured: false,+ datadogConfigured: false,+ spotifyStatus: { hasCredentials: false, hasTokens: false },+ stackerAccounts: [],+ openclawConfig: {},+}));++vi.mock('./settings.js', () => ({+ getSettings: mock.getSettings,+}));++vi.mock('./hfToken.js', () => ({+ getHfTokenInfo: mock.getHfTokenInfo,+}));++vi.mock('./jira.js', () => ({+ hasConfiguredInstances: vi.fn(async () => mock.jiraConfigured),+}));++vi.mock('./datadog.js', () => ({+ hasConfiguredInstances: vi.fn(async () => mock.datadogConfigured),+}));++vi.mock('./spotifyAuth.js', () => ({+ getAuthStatus: vi.fn(async () => mock.spotifyStatus),+}));++vi.mock('./stackerNews.js', () => ({+ listAccounts: vi.fn(async () => mock.stackerAccounts),+}));++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ readJSONFile: vi.fn(async () => mock.openclawConfig),+ };+});++import { getCredentialInventory } from './credentialInventory.js';++const byId = (credentials, id) => credentials.find((row) => row.id === id);++const secretShaped = /(hf_|sk-|ghp_|gho_|github_pat_|xox[baprs]-)/;++describe('credentialInventory', () => {+ beforeEach(() => {+ mock.getSettings.mockResolvedValue({});+ mock.getHfTokenInfo.mockResolvedValue({ token: null, source: 'none' });+ mock.jiraConfigured = false;+ mock.datadogConfigured = false;+ mock.spotifyStatus = { hasCredentials: false, hasTokens: false };+ mock.stackerAccounts = [];+ mock.openclawConfig = {};+ });++ it('reports settings over env when both are set, without echoing the value', async () => {+ const { credentials, headline } = await getCredentialInventory({+ settings: { imageGen: { hfToken: 'hf_thisMustNeverLeaveTheServer' }, civitai: { apiKey: 'secret-civitai-key' } },+ env: { HF_TOKEN: 'hf_envMustNotWin', CIVITAI_API_KEY: 'env-civitai' },+ envFile: new Map(),+ detectors: {},+ });++ expect(headline).toMatch(/no key at all/i);+ expect(byId(credentials, 'huggingface')).toMatchObject({ configured: true, source: 'settings' });+ expect(byId(credentials, 'civitai')).toMatchObject({ configured: true, source: 'settings' });+ expect(JSON.stringify({ credentials })).not.toMatch(secretShaped);+ expect(JSON.stringify({ credentials })).not.toContain('hf_thisMustNeverLeaveTheServer');+ expect(JSON.stringify({ credentials })).not.toContain('secret-civitai-key');+ });++ it('distinguishes repo .env from inherited process.env', async () => {+ const envFile = new Map([['CIVITAI_API_KEY', 'from-dot-env'], ['ANTHROPIC_API_KEY', 'from-dot-env']]);+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: { ANTHROPIC_API_KEY: 'from-dot-env', OPENAI_API_KEY: 'shell-only' },+ envFile,+ detectors: {},+ });++ expect(byId(credentials, 'civitai')).toMatchObject({ configured: true, source: 'env-file' });+ expect(byId(credentials, 'anthropic')).toMatchObject({ configured: true, source: 'env-file' });+ expect(byId(credentials, 'openai')).toMatchObject({ configured: true, source: 'env' });+ expect(JSON.stringify({ credentials })).not.toContain('from-dot-env');+ expect(JSON.stringify({ credentials })).not.toContain('shell-only');+ });++ it('uses the huggingface CLI source when that is the only place a token exists', async () => {+ mock.getHfTokenInfo.mockResolvedValue({ token: 'hf_cliTokenMustNotLeak', source: 'cli' });+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: {},+ envFile: new Map(),+ });+ expect(byId(credentials, 'huggingface')).toMatchObject({ configured: true, source: 'cli' });+ expect(JSON.stringify({ credentials })).not.toContain('hf_cliTokenMustNotLeak');+ });++ it('names the instance feature that stays dark without a JIRA token', async () => {+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: {},+ envFile: new Map(),+ detectors: { jira: async () => null },+ });+ expect(byId(credentials, 'jira')).toMatchObject({+ configured: false,+ source: 'none',+ unavailableFeatures: [{ id: 'jira', label: 'JIRA' }],+ });+ });++ it('treats a configured JIRA instance file as config, not env', async () => {+ mock.jiraConfigured = true;+ const { credentials } = await getCredentialInventory({+ settings: {},+ env: {},+ envFile: new Map(),+ });+ expect(byId(credentials, 'jira')).toMatchObject({ configured: true, source: 'config', unavailableFeatures: [] });+ });+});