How managed-provider-auth.ts Handles Provider API Key Authentication in OpenWork
managed-provider-auth.ts is the server-side module that securely delivers cloud-provider credentials from the server's secret store directly to the OpenWork engine, using SHA-256 fingerprinting to ensure idempotent writes and prevent unnecessary engine restarts.
The OpenWork platform isolates sensitive API keys from client browsers by delegating authentication to a secure server-side orchestrator. Located at apps/server/src/managed-provider-auth.ts, this component implements a robust synchronization protocol that maps stored environment variables to provider configurations and pushes credentials to the engine via REST API endpoints. The implementation guarantees that credentials never traverse the client layer while maintaining strict deduplication to avoid service disruptions.
The 8-Step Authentication Workflow
The syncManagedProviderAuth function executes a deterministic pipeline that transforms server-side secrets into engine-ready authentication tokens. Each step is designed to minimize exposure and maximize reliability.
Workspace Resolution and Engine Discovery
The process begins by locating the target engine instance. The module calls findManagedEngineWorkspace to identify the managed-engine workspace, falling back to the first available workspace if necessary. It then invokes resolveWorkspaceOpencodeConnection to construct the base URL for subsequent API calls.
Loading the Runtime Provider Map
Once the engine endpoint is established, the system reads the global runtime configuration via readGlobalRuntimeOpencodeConfig. This extracts the runtimeProviderMap, which contains only providers marked as managed—those whose credentials are explicitly stored on the server rather than supplied by the client.
Gathering Stored Environment Secrets
The module interfaces with an injected EnvReader to retrieve all secret key-value pairs. The call to input.env.list() returns an array of environment variables, filtering out any non-string or empty values to ensure only valid credentials proceed to the matching phase.
Credential Name Resolution
For each managed provider, the system examines the entry.env array—the list of environment variable names that the provider recognizes. Using readEnvNames(entry), it selects the first name that exists in the secret store. If no matching environment variable is found, the provider is skipped rather than causing a hard failure, allowing the sync to continue gracefully.
SHA-256 Fingerprinting and Deduplication
Before transmitting any credential, the module computes a SHA-256 fingerprint of the value using the fingerprint utility. This hash is compared against the deliveredFingerprints cache, which tracks previously delivered credentials by provider key. If the fingerprint matches a cached entry, the provider is marked unchanged and no network request is issued. This mechanism was specifically implemented to prevent redundant writes that previously caused a production incident involving unnecessary engine restarts.
Delivering Credentials via PUT /auth/:providerId
When a new or modified credential is detected, the module constructs a fetch request (using an injectable fetchImpl) to PUT ${baseUrl}/auth/${encodeURIComponent(providerId)}. The JSON payload follows the structure {type: "api", key: <credential>}. Successful responses update the fingerprint cache and are recorded in the delivered array, while failures are logged and added to the failed array for operational visibility.
Cleaning Up Stale Credentials
After processing all active providers, the module iterates over the deliveredFingerprints cache. Any entry whose provider is no longer present in the managed set triggers a DELETE /auth/:providerId request. This cleanup only removes credentials that were previously delivered by this process, safeguarding desktop-auth flows and preventing accidental revocation of user-managed keys.
Returning the Sync Results
The function culminates in a ManagedProviderAuthResult object containing five categorized arrays: delivered, unchanged, removed, skipped, and failed. This structured result enables callers to surface detailed status information in logs or administrative UI components.
Why Server-Side Delivery Matters
Security isolation ensures that raw API keys never traverse browser environments or client-side code. By confining credential retrieval to the server layer, OpenWork eliminates the risk of key exposure through XSS or client-side leaks.
Idempotent synchronization via fingerprinting guarantees that the engine receives write operations only when credentials actually change. This prevents the cascade of unnecessary process restarts that previously destabilized production workloads.
Graceful degradation allows the system to continue operating even when individual providers lack configured credentials. Rather than throwing exceptions, the module skips incomplete configurations and reports them in the results object.
Implementation Example
Below is a typical server-side integration pattern that demonstrates credential delivery and cache management:
import {
syncManagedProviderAuth,
resetManagedProviderAuthCache
} from "./managed-provider-auth.js";
import { ServerConfig } from "./types.js";
// EnvReader implementation backed by the server's secret store
const envReader = {
async list() {
return [
{
key: "OPENAI_API_KEY",
value: process.env.OPENAI_API_KEY ?? ""
},
{
key: "ANTHROPIC_API_KEY",
value: process.env.ANTHROPIC_API_KEY ?? ""
},
];
},
};
const logger = {
warn: console.warn,
error: console.error,
};
async function deliverProviderAuth(config: ServerConfig) {
// Reset cache after engine restarts to ensure fresh delivery
resetManagedProviderAuthCache();
const result = await syncManagedProviderAuth({
config,
env: envReader,
logger,
});
console.log("Provider auth sync result:", result);
// result.delivered: newly sent credentials
// result.unchanged: credentials already in sync
// result.failed: transmission errors
}
Related Source Files
The authentication system spans several modules that collectively manage the path from secret storage to engine consumption:
opencode-connection.ts— Determines the engine base URL and authentication headers for establishing the connection.runtime-opencode-config-store.ts— Persists and retrieves the OpenCode runtime configuration that defines which providers require managed authentication.workspaces.ts— Provides workspace discovery utilities includingfindManagedEngineWorkspace.types.ts— Contains TypeScript definitions forServerConfig,ManagedProviderAuthResult, and theEnvReaderinterface.
Summary
- managed-provider-auth.ts acts as the secure bridge between server-side secret stores and the OpenWork engine.
- The fingerprint cache prevents redundant API calls by tracking SHA-256 hashes of previously delivered credentials.
- Credentials are transmitted via PUT /auth/:providerId and cleaned up via DELETE /auth/:providerId when removed from configuration.
- The EnvReader abstraction allows integration with diverse secret management systems while keeping keys server-bound.
- Graceful skipping of incomplete configurations ensures system stability when providers lack environment variables.
Frequently Asked Questions
How does the fingerprint cache prevent unnecessary engine restarts?
The module computes a SHA-256 hash of each credential value and stores it in the deliveredFingerprints map. Before sending any credential, it compares the current fingerprint against the cached version. If they match, the provider is marked as unchanged and no HTTP request is sent to the engine. This idempotency prevents the engine from receiving duplicate authentication updates that would otherwise trigger resource-intensive restart cycles.
What happens when a managed provider lacks a corresponding environment variable?
During the credential name resolution phase, the module iterates through the provider's expected environment variable names (entry.env). If none of these names exist in the secret store returned by input.env.list(), the provider is added to the skipped array in the results object. The sync continues processing other providers without throwing exceptions, ensuring that missing configuration for one service does not block authentication for others.
Can I customize the HTTP client used for credential delivery?
Yes. The syncManagedProviderAuth function accepts an optional fetchImpl parameter that defaults to the global fetch. You can inject any fetch-compatible implementation to add custom headers, implement retry logic, or route traffic through corporate proxies. The implementation must support the standard fetch signature to handle the PUT and DELETE requests to /auth/:providerId.
When should resetManagedProviderAuthCache() be called?
Call resetManagedProviderAuthCache() whenever the OpenWork engine process restarts or when you explicitly need to force a full re-synchronization of all credentials. Clearing the cache ensures that the next invocation of syncManagedProviderAuth treats all credentials as new deliveries, re-establishing the fingerprint baseline and verifying current engine state. This is particularly important during deployments or disaster recovery scenarios.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →