diff --git a/README.md b/README.md index 3163967..92b114c 100644 --- a/README.md +++ b/README.md @@ -52,10 +52,10 @@ One subcontainer, `opencode-sub`, runs the server. The image's entrypoint is the The package declares two volumes. -| Volume | Mount point | Contents | -| --------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------ | -| `main` | `/root` (read-write) | The container's entire home: sessions, credentials, repositories, projects, and OpenCode's own config, state, and cache. | -| `startos` | not mounted | StartOS-side state: `store.json`, holding the generated login password and the configured providers' API keys. | +| Volume | Mount point | Contents | +| --------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | +| `main` | `/root` (read-write) | The container's entire home: sessions, credentials, repositories, projects, and OpenCode's own config, state, and cache. | +| `startos` | optional read-only `provider-trust/` subtree | StartOS-side state: `store.json`, holding the generated login password and the configured providers' API keys. | `main` is mounted over the image's home directory, so everything OpenCode writes under `/root` persists across restarts and updates: @@ -67,27 +67,28 @@ under `/root` persists across restarts and updates: `/tmp/opencode` (OpenCode's temporary directory) is **not** on a volume and is lost on restart; treat anything only in there as scratch. -The `startos` volume is deliberately not mounted into `opencode-sub`, so the -running server never sees the file itself — it receives the login password as +Only the optional public CA directory is mounted from `startos`. The running +server cannot read `store.json` — it receives the login password as `OPENCODE_PASSWORD` and each configured provider's API key as an `OPENCODE_KEY_` variable instead. ## File Models -The package owns two file models. +The package owns three file models. | File | Format | Keys | Seeded by | Rewritten by | | ------------------------------------- | ------ | ------------------------------- | ---------------------------------------- | ---------------------------- | | `startos/store.json` | JSON | `adminPassword`, `providerKeys` | the **Set Admin Password** action | the two actions, on each run | | `main/.config/opencode/opencode.json` | JSONC | `$schema`, `providers`, `model` | the **Configure Model Providers** action | the same action, on each run | +| `startos/provider-trust/ca.pem` | PEM | — | the **Configure Provider CA** action | the same action, on each run | `adminPassword` is stored in clear text because the server reads it verbatim from `OPENCODE_PASSWORD` and cannot be given a hash. There is no default: it is absent until the user runs the action, which is what the [task](#tasks) waits for. `providerKeys` maps a configured provider's id to its API key, and has no -default either. +default either. The PEM file is optional and holds one public CA certificate. -Both schemas are permissive (`z.looseObject`, every key optional), and the +Both JSON schemas are permissive (`z.looseObject`, every key optional), and the package writes each file only from an action — never at startup, and never to normalize or repair it. A hand edit therefore survives: @@ -188,6 +189,24 @@ warning, and status gating; what follows is what the metadata cannot express. - **Outputs.** Each provider with the model IDs it serves, and the default model when one is set. +### `configure-provider-ca` — Configure Provider CA + +- **When to run it.** When an OpenAI-compatible endpoint you use serves a + certificate signed by a private or self-signed CA — a vLLM or Ollama server + behind an internal certificate authority, for instance — and the web app cannot + reach it. Paste the **public** CA certificate only; never a private key. +- **What it changes.** `startos/provider-trust/ca.pem`, one public CA certificate. + The directory is mounted read-only into the container and the certificate is + handed to OpenCode as `NODE_EXTRA_CA_CERTS` on startup, so it applies to + outbound TLS connections. The file lives on a volume and is included in the + service backup. +- **Cost.** Seconds, and the service restarts so OpenCode re-reads the CA. Nothing + else is touched, and no session, repository, or project is affected. +- **Repeat safety.** Repeatable. Running it again replaces the stored certificate; + clearing the field removes trust. The form opens prefilled with the current + certificate, so saving unchanged keeps it. One CA at a time. +- **Outputs.** None. + ## Tasks One task, raised by `startos/init/watchCredentials.ts`. diff --git a/instructions.md b/instructions.md index ec184a1..2ead80f 100644 --- a/instructions.md +++ b/instructions.md @@ -85,7 +85,17 @@ already configured is filled in when the form opens, so leave it as it is unless you are replacing it. OpenAI-compatible endpoints you configured by hand are also listed, with their API key — or the `{env:…}` or `{file:…}` reference that supplies it — filled in. Providers connected in the web app are not affected. If -an ID is already in use outside this list, choose a different ID. +an ID is already in use outside this list, choose a different ID. Existing model +aliases keep their upstream IDs when you save again, and turning off every +**Default** toggle leaves no default model. + +### Private HTTPS providers + +Open **Configure Provider CA** and paste the public PEM certificate of the CA +that signed the provider endpoint. Saving a new CA restarts OpenCode. Reopen +the action to replace it, or clear the field to remove trust. The CA applies to +outbound OpenCode TLS connections and is included in the service backup. +Use the hostname or IP listed in the server certificate. ### Changing the password diff --git a/startos/actions/configureProviderCa.ts b/startos/actions/configureProviderCa.ts new file mode 100644 index 0000000..3a1835b --- /dev/null +++ b/startos/actions/configureProviderCa.ts @@ -0,0 +1,39 @@ +import { normalizeProviderCa, providerCa } from '../fileModels/providerCa' +import { i18n } from '../i18n' +import { sdk } from '../sdk' + +export const configureProviderCa = sdk.Action.withInput( + 'configure-provider-ca', + { + name: i18n('Configure Provider CA'), + description: i18n( + 'Trust one additional CA for outbound OpenCode HTTPS connections.', + ), + warning: null, + allowedStatuses: 'any', + group: null, + visibility: 'enabled', + }, + sdk.InputSpec.of({ + pem: sdk.Value.textarea({ + name: i18n('Public CA certificate (PEM)'), + description: i18n( + 'Paste one certificate. Clear the field to remove trust.', + ), + default: null, + required: false, + maxLength: 32768, + }), + }), + async () => ({ pem: (await providerCa.read().once()) || null }), + async ({ effects, input }) => { + const pem = normalizeProviderCa(input.pem ?? '') + await providerCa.update(effects, () => pem) + return { + version: '1', + title: i18n('Configure Provider CA'), + message: i18n('Trust settings saved.'), + result: null, + } + }, +) diff --git a/startos/actions/configureProviders.ts b/startos/actions/configureProviders.ts index 50713f9..b1a703f 100644 --- a/startos/actions/configureProviders.ts +++ b/startos/actions/configureProviders.ts @@ -187,6 +187,9 @@ export const configureProviders = sdk.Action.withInput( // execution async ({ effects, input }) => { + if (input.providers.filter((provider) => provider.isDefault).length > 1) { + throw new Error(i18n('Select only one default provider.')) + } const providerKeys = Object.fromEntries( input.providers .filter((provider) => provider.apiKey && !isReference(provider.apiKey)) @@ -237,10 +240,11 @@ export const configureProviders = sdk.Action.withInput( const models: Record = {} for (const modelId of provider.models) { + const existingModel = asRecord(previousModels[modelId]) models[modelId] = { - ...asRecord(previousModels[modelId]), - name: modelId, - modelID: modelId, + ...existingModel, + name: asString(existingModel.name) ?? modelId, + modelID: asString(existingModel.modelID) ?? modelId, } } diff --git a/startos/actions/index.ts b/startos/actions/index.ts index 599d403..c544393 100644 --- a/startos/actions/index.ts +++ b/startos/actions/index.ts @@ -1,3 +1,4 @@ +import { configureProviderCa } from './configureProviderCa' import { sdk } from '../sdk' import { configureProviders } from './configureProviders' import { setAdminPassword } from './setAdminPassword' @@ -5,3 +6,4 @@ import { setAdminPassword } from './setAdminPassword' export const actions = sdk.Actions.of() .addAction(setAdminPassword) .addAction(configureProviders) + .addAction(configureProviderCa) diff --git a/startos/fileModels/providerCa.ts b/startos/fileModels/providerCa.ts new file mode 100644 index 0000000..b4283b2 --- /dev/null +++ b/startos/fileModels/providerCa.ts @@ -0,0 +1,27 @@ +import { X509Certificate } from 'node:crypto' +import { FileHelper } from '@start9labs/start-sdk' +import { i18n } from '../i18n' +import { sdk } from '../sdk' + +export const providerCaDirectory = 'provider-trust' +export const providerCaMountpoint = '/etc/opencode-trust' +export const providerCaPath = providerCaMountpoint + '/ca.pem' +export const providerCa = FileHelper.string({ + base: sdk.volumes.startos, + subpath: providerCaDirectory + '/ca.pem', +}) + +export function normalizeProviderCa(input: string): string { + const pem = input.trim() + if (!pem) return '' + if ( + !/^-----BEGIN CERTIFICATE-----\r?\n[A-Za-z0-9+/=\r\n]+\r?\n-----END CERTIFICATE-----$/.test( + pem, + ) + ) { + throw new Error(i18n('Paste one public PEM CA certificate.')) + } + const cert = new X509Certificate(pem) + if (!cert.ca) throw new Error(i18n('This certificate is not a CA.')) + return cert.toString().trim() + '\n' +} diff --git a/startos/i18n/dictionaries/default.ts b/startos/i18n/dictionaries/default.ts index cbb6a8e..ecbe108 100644 --- a/startos/i18n/dictionaries/default.ts +++ b/startos/i18n/dictionaries/default.ts @@ -46,6 +46,14 @@ const dict = { 'Default Model': 33, 'Provider ID "${id}" belongs to a provider configured outside this action. Choose another ID.': 34, 'The OpenCode configuration contains invalid JSONC. Fix opencode.json before configuring providers.': 35, + 'Configure Provider CA': 36, + 'Trust one additional CA for outbound OpenCode HTTPS connections.': 37, + 'Public CA certificate (PEM)': 38, + 'Paste one certificate. Clear the field to remove trust.': 39, + 'Trust settings saved.': 40, + 'Select only one default provider.': 41, + 'Paste one public PEM CA certificate.': 42, + 'This certificate is not a CA.': 43, } as const /** diff --git a/startos/i18n/dictionaries/translations.ts b/startos/i18n/dictionaries/translations.ts index 6d5e4fa..fcb59dc 100644 --- a/startos/i18n/dictionaries/translations.ts +++ b/startos/i18n/dictionaries/translations.ts @@ -38,6 +38,14 @@ export default { 33: 'Modelo predeterminado', 34: 'El ID de proveedor "${id}" pertenece a un proveedor configurado fuera de esta acción. Elige otro ID.', 35: 'La configuración de OpenCode contiene JSONC no válido. Corrige opencode.json antes de configurar los proveedores.', + 36: 'Configurar CA del proveedor', + 37: 'Confía en una CA adicional para las conexiones HTTPS salientes de OpenCode.', + 38: 'Certificado público de CA (PEM)', + 39: 'Pega un certificado. Borra el campo para retirar la confianza.', + 40: 'Ajustes guardados.', + 41: 'Selecciona solo un proveedor predeterminado.', + 42: 'Pega un certificado de CA público en formato PEM.', + 43: 'Este certificado no es una CA.', }, de_DE: { 0: 'Weboberfläche', @@ -76,6 +84,14 @@ export default { 33: 'Standardmodell', 34: 'Die Anbieter-ID „${id}“ gehört zu einem außerhalb dieser Aktion konfigurierten Anbieter. Wählen Sie eine andere ID.', 35: 'Die OpenCode-Konfiguration enthält ungültiges JSONC. Korrigieren Sie opencode.json, bevor Sie Anbieter konfigurieren.', + 36: 'Anbieter-CA konfigurieren', + 37: 'Einer weiteren CA für ausgehende HTTPS-Verbindungen von OpenCode vertrauen.', + 38: 'Öffentliches CA-Zertifikat (PEM)', + 39: 'Ein Zertifikat einfügen. Zum Entfernen das Feld leeren.', + 40: 'Einstellungen gespeichert.', + 41: 'Wählen Sie nur einen Standardanbieter.', + 42: 'Fügen Sie ein öffentliches CA-Zertifikat (PEM) ein.', + 43: 'Dieses Zertifikat ist keine CA.', }, pl_PL: { 0: 'Interfejs webowy', @@ -114,6 +130,14 @@ export default { 33: 'Model domyślny', 34: 'Identyfikator dostawcy „${id}” należy do dostawcy skonfigurowanego poza tą akcją. Wybierz inny identyfikator.', 35: 'Konfiguracja OpenCode zawiera nieprawidłowy JSONC. Popraw opencode.json przed skonfigurowaniem dostawców.', + 36: 'Konfiguracja CA dostawcy', + 37: 'Zaufaj dodatkowemu CA dla wychodzących połączeń HTTPS OpenCode.', + 38: 'Publiczny certyfikat CA (PEM)', + 39: 'Wklej jeden certyfikat. Wyczyść pole, aby usunąć zaufanie.', + 40: 'Zapisano ustawienia.', + 41: 'Wybierz tylko jednego dostawcę domyślnego.', + 42: 'Wklej publiczny certyfikat CA w formacie PEM.', + 43: 'Ten certyfikat nie jest CA.', }, fr_FR: { 0: 'Interface web', @@ -152,5 +176,13 @@ export default { 33: 'Modèle par défaut', 34: 'L’identifiant de fournisseur « ${id} » appartient à un fournisseur configuré en dehors de cette action. Choisissez un autre identifiant.', 35: 'La configuration OpenCode contient du JSONC invalide. Corrigez opencode.json avant de configurer les fournisseurs.', + 36: 'Configurer l’autorité de certification', + 37: 'Faire confiance à une autorité supplémentaire pour les connexions HTTPS sortantes d’OpenCode.', + 38: 'Certificat public de l’autorité (PEM)', + 39: 'Collez un certificat. Videz le champ pour retirer cette autorité.', + 40: 'Paramètres enregistrés.', + 41: 'Sélectionnez un seul fournisseur par défaut.', + 42: 'Collez un certificat d’autorité publique au format PEM.', + 43: 'Ce certificat n’est pas une autorité de certification.', }, } satisfies Record diff --git a/startos/main.ts b/startos/main.ts index a078865..7615165 100644 --- a/startos/main.ts +++ b/startos/main.ts @@ -1,3 +1,9 @@ +import { + providerCa, + providerCaDirectory, + providerCaMountpoint, + providerCaPath, +} from './fileModels/providerCa' import { storeJson } from './fileModels/store.json' import { i18n } from './i18n' import { sdk } from './sdk' @@ -24,16 +30,30 @@ export const main = sdk.setupMain(async ({ effects }) => { .map(([id, key]) => [providerKeyEnvVar(id), key]), ) + let mounts = sdk.Mounts.of().mountVolume({ + volumeId: 'main', + subpath: null, + mountpoint: '/root', + readonly: false, + }) + const pem = await providerCa.read().const(effects) + const extraCaPath = pem ? providerCaPath : undefined + if (pem) { + // The `.const()` read above re-runs this setup — and so restarts the daemon — + // whenever the certificate changes, so the mount can sit at a fixed path. + mounts = mounts.mountVolume({ + volumeId: 'startos', + subpath: providerCaDirectory, + mountpoint: providerCaMountpoint, + readonly: true, + }) + } + return sdk.Daemons.of(effects).addDaemon('opencode', { subcontainer: sdk.SubContainer.of( effects, { imageId: 'opencode' }, - sdk.Mounts.of().mountVolume({ - volumeId: 'main', - subpath: null, - mountpoint: '/root', - readonly: false, - }), + mounts, 'opencode-sub', ), exec: { @@ -47,6 +67,7 @@ export const main = sdk.setupMain(async ({ effects }) => { env: { OPENCODE_PASSWORD: adminPassword, OPENCODE_DISABLE_AUTOUPDATE: '1', + ...(extraCaPath && { NODE_EXTRA_CA_CERTS: extraCaPath }), ...providerEnv, }, }, diff --git a/startos/manifest/index.ts b/startos/manifest/index.ts index 76f3ffa..fa7ca2f 100644 --- a/startos/manifest/index.ts +++ b/startos/manifest/index.ts @@ -10,7 +10,8 @@ export const manifest = setupManifest({ marketingUrl: 'https://opencode.ai', donationUrl: null, description: { short, long }, - // `startos` holds the login password and is never mounted into the container. + // `startos` holds secrets (the login password and provider API keys) and the + // optional public CA; only the CA subtree is mounted into the container, read-only. volumes: ['main', 'startos'], images: { opencode: { diff --git a/startos/versions/current.ts b/startos/versions/current.ts index 9d4bf28..d367a47 100644 --- a/startos/versions/current.ts +++ b/startos/versions/current.ts @@ -1,18 +1,18 @@ import { IMPOSSIBLE, VersionInfo } from '@start9labs/start-sdk' export const current = VersionInfo.of({ - version: '2.4.1:1', + version: '2.4.1:2', releaseNotes: { en_US: - 'Add a Configure Model Providers action, which connects an OpenAI-compatible provider — your own vLLM, LM Studio, or Ollama server, or a hosted API — without a shell.', + 'Add private provider CA trust and keep existing model aliases when configuring providers.', es_ES: - 'Añade una acción Configurar proveedores de modelos, que conecta un proveedor compatible con OpenAI —tu propio servidor vLLM, LM Studio u Ollama, o una API alojada— sin usar la terminal.', + 'Permite confiar en una CA privada y conserva los alias de modelos al configurar proveedores.', de_DE: - 'Fügt die Aktion „Modellanbieter konfigurieren" hinzu, die einen OpenAI-kompatiblen Anbieter verbindet – Ihren eigenen vLLM-, LM-Studio- oder Ollama-Server oder eine gehostete API – ganz ohne Shell.', + 'Unterstützt private Zertifizierungsstellen und behält vorhandene Modellaliase beim Konfigurieren der Anbieter bei.', pl_PL: - 'Dodaje akcję „Konfiguruj dostawców modeli", która podłącza dostawcę zgodnego z OpenAI — własny serwer vLLM, LM Studio lub Ollama albo hostowane API — bez użycia terminala.', + 'Dodaje obsługę prywatnego CA i zachowuje istniejące aliasy modeli podczas konfigurowania dostawców.', fr_FR: - "Ajoute l'action « Configurer les fournisseurs de modèles », qui connecte un fournisseur compatible OpenAI — votre propre serveur vLLM, LM Studio ou Ollama, ou une API hébergée — sans passer par le shell.", + 'Ajoute la prise en charge des AC privées et conserve les alias de modèles lors de la configuration des fournisseurs.', }, migrations: { up: async ({ effects }) => {},