/** * `key vault` commands and the `--key-vault` upload option (beta). * * The OTA private key is encrypted locally (vault-envelope.ts) with a vault secret that stays * with the customer: the CAPGO_KEY_VAULT_SECRET environment variable, a --vault-secret-file, or * a hidden prompt. Capgo stores only the envelope. Any machine with an API key that can read the * envelope plus the vault secret can decrypt it in memory and sign uploads, so CI, agents and * MCP clients do not need the key file on disk. */ import { existsSync, lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs' import { basename, dirname, join } from 'node:path' import process, { stdin } from 'node:process' import { confirm, isCancel, log, password } from '@clack/prompts' import { buildCliRequestHeaders } from '../analytics/cli-headers' import { CliUserError } from '../shared/cli-user-error' import { baseKeyV2, createCapgoClient, findSavedKey, formatError, getAppId, getConfig } from '../utils' import { assertVaultSecret, generateVaultSecret, openOtaPrivateKey, OTA_KEY_VAULT_SECRET_ENV, rsaPrivateKeyFingerprint, rsaPublicKeyFingerprint, sealOtaPrivateKey, } from './vault-envelope' export interface KeyVaultBaseOptions { apikey?: string apiHost?: string vaultSecretFile?: string } export interface KeyVaultPushOptions extends KeyVaultBaseOptions { key?: string generateSecret?: boolean replace?: boolean force?: boolean } export interface KeyVaultPullOptions extends KeyVaultBaseOptions { out?: string force?: boolean } export interface KeyVaultDeleteOptions extends KeyVaultBaseOptions { yes?: boolean } export interface KeyVaultStatus { app_id: string configured: boolean revision?: number public_key?: string public_key_sha256?: string kdf_iterations?: number updated_at?: string envelope_access?: boolean envelope?: unknown } async function vaultApi(options: KeyVaultBaseOptions, method: 'GET' | 'PUT' | 'DELETE', appId: string, body?: unknown, query = ''): Promise { const apikey = options.apikey || findSavedKey(true) const client = await createCapgoClient(apikey, options.apiHost, true) const response = await fetch(`${client.apiHost}/app/${encodeURIComponent(appId)}/ota-key-vault${query}`, { method, headers: buildCliRequestHeaders({ 'authorization': client.apikey, 'content-type': 'application/json' }), body: body === undefined ? undefined : JSON.stringify(body), }) const text = await response.text() let parsed: unknown try { parsed = text ? JSON.parse(text) : {} } catch { parsed = { message: text.slice(0, 500) } } if (!response.ok) { const error = parsed as { error?: string, message?: string } throw new CliUserError(`Capgo API ${response.status}${error.error ? ` ${error.error}` : ''}: ${error.message ?? 'request failed'}`) } return parsed as T } async function resolveAppId(appIdArg: string | undefined): Promise { let config: Awaited>['config'] | undefined if (!appIdArg) { try { config = (await getConfig(true))?.config } catch { // Not in a Capacitor project. } } // Same precedence as bundle upload: CapacitorUpdater.appId overrides the native appId. const appId = getAppId(appIdArg, config) if (appId) return appId throw new CliUserError('App ID is required: pass it as an argument or run from a Capacitor project') } async function configuredPublicKey(): Promise { try { const value = (await getConfig(true))?.config?.plugins?.CapacitorUpdater?.publicKey return typeof value === 'string' && value.includes('RSA PUBLIC KEY') ? value : undefined } catch { return undefined } } /** Vault secret from --vault-secret-file, then CAPGO_KEY_VAULT_SECRET, then a hidden prompt. */ export async function readVaultSecret(options: { vaultSecretFile?: string }, prompt = true): Promise { if (options.vaultSecretFile) { if (!existsSync(options.vaultSecretFile)) throw new CliUserError(`Vault secret file not found: ${options.vaultSecretFile}`) return assertVaultSecret(readFileSync(options.vaultSecretFile, 'utf8')) } const fromEnv = process.env[OTA_KEY_VAULT_SECRET_ENV] if (fromEnv) return assertVaultSecret(fromEnv) if (!prompt || !stdin.isTTY) return undefined const value = await password({ message: 'OTA key vault secret (never sent to Capgo)' }) if (isCancel(value)) throw new CliUserError('Cancelled') return assertVaultSecret(value) } function requireSecret(secret: string | undefined): string { if (!secret) throw new CliUserError(`Set the ${OTA_KEY_VAULT_SECRET_ENV} environment variable or pass --vault-secret-file to use the OTA key vault`) return secret } /** * Downloads the envelope and decrypts it in memory. Used by `bundle upload --key-vault`, * `bundle zip --for-upload --key-vault`, the SDK and the local MCP server. */ export async function loadPrivateKeyFromVault(appId: string, options: KeyVaultBaseOptions, vaultSecret?: string, matchProjectKey = true): Promise { const secret = requireSecret(vaultSecret ?? await readVaultSecret(options, false)) const status = await vaultApi(options, 'GET', appId) if (!status.configured) throw new CliUserError(`No OTA private key is stored in the key vault for ${appId}. Store one with: npx @capgo/cli@latest key vault push ${appId}`) if (!status.envelope) throw new CliUserError(`This API key cannot read the OTA key vault of ${appId}: app.upload_bundle permission is required`) const privateKey = await openOtaPrivateKey({ appId, envelope: status.envelope, secret }) const configured = matchProjectKey ? await configuredPublicKey() : undefined if (configured && await rsaPublicKeyFingerprint(configured) !== await rsaPrivateKeyFingerprint(privateKey)) throw new CliUserError('The OTA private key in the vault does not match CapacitorUpdater.publicKey in your Capacitor config; devices would reject this bundle') return privateKey } /** `--key-vault` replaces the local key file, so it cannot be combined with the other key options. */ export function assertKeyVaultOptions(options: { keyV2?: unknown, keyDataV2?: string, key?: unknown, external?: string }) { if (options.keyV2 || options.keyDataV2) throw new CliUserError('--key-vault cannot be combined with --key-v2 or --key-data-v2') if (options.key === false) throw new CliUserError('--key-vault cannot be combined with --no-key') if (options.external) throw new CliUserError('--key-vault cannot be used with an external URL') } export async function pushKeyVault(appIdArg: string | undefined, options: KeyVaultPushOptions) { if (options.generateSecret && options.vaultSecretFile) throw new CliUserError('--generate-secret cannot be combined with --vault-secret-file') const appId = await resolveAppId(appIdArg) const keyPath = options.key || baseKeyV2 if (!existsSync(keyPath)) throw new CliUserError(`Cannot find the OTA private key at ${keyPath}. Create one with npx @capgo/cli@latest key create, or pass --key`) const privateKeyPem = readFileSync(keyPath, 'utf8') const configured = await configuredPublicKey() if (configured && await rsaPublicKeyFingerprint(configured) !== await rsaPrivateKeyFingerprint(privateKeyPem) && !options.force) throw new CliUserError(`${keyPath} does not match CapacitorUpdater.publicKey in your Capacitor config. Pass --force to store it anyway`) // An explicit --generate-secret always makes a new secret, even when CAPGO_KEY_VAULT_SECRET is set. const generated = !!options.generateSecret const secret = generated ? generateVaultSecret() : requireSecret(await readVaultSecret(options)) const current = await vaultApi(options, 'GET', appId) if (current.configured && !options.replace) throw new CliUserError(`An OTA private key is already stored for ${appId} (revision ${current.revision}, SHA-256 ${current.public_key_sha256}). Pass --replace to overwrite it`) const sealed = await sealOtaPrivateKey({ appId, privateKeyPem, secret }) const result = await vaultApi(options, 'PUT', appId, { envelope: sealed.envelope, public_key: sealed.publicKeyPem, expected_revision: current.configured ? current.revision : 0, }) log.success(`Stored the OTA private key for ${appId} in the Capgo key vault (revision ${result.revision}). It was encrypted on this machine; Capgo cannot read it.`) log.info(`Public key SHA-256: ${sealed.publicKeySha256}`) if (generated) { // Shown once, on purpose: Capgo has no copy and cannot recover it. log.warn('Save this vault secret in your password manager and CI secrets now. Capgo cannot recover it:') process.stdout.write(`${OTA_KEY_VAULT_SECRET_ENV}=${secret}\n`) } return result } /** * Writes the key owner-only without following links: an existing symlink (even dangling) is * refused, and the file is created exclusively next to the target, then renamed over it. */ export function writePrivateKeyFile(out: string, privateKey: string, force: boolean) { let existing: ReturnType | undefined try { existing = lstatSync(out) } catch { existing = undefined } if (existing?.isSymbolicLink()) throw new CliUserError(`${out} is a symbolic link; refusing to write the private key through it`) if (existing && !existing.isFile()) throw new CliUserError(`${out} is not a regular file`) if (existing && readFileSync(out, 'utf8').trim() !== privateKey.trim() && !force) throw new CliUserError(`${out} already exists with a different key. Pass --force to overwrite it`) const temp = join(dirname(out), `.${basename(out)}.${process.pid}.${Date.now()}.tmp`) try { writeFileSync(temp, privateKey, { mode: 0o600, flag: 'wx' }) renameSync(temp, out) } finally { rmSync(temp, { force: true }) } } export async function pullKeyVault(appIdArg: string | undefined, options: KeyVaultPullOptions) { const appId = await resolveAppId(appIdArg) const out = options.out || baseKeyV2 const secret = requireSecret(await readVaultSecret(options)) // An explicitly named app may not be this project's app: its key is not compared with this // project's public key. Signing (upload, zip) always compares. const privateKey = await loadPrivateKeyFromVault(appId, options, secret, !appIdArg) writePrivateKeyFile(out, privateKey, options.force === true) log.success(`Decrypted the OTA private key for ${appId} into ${out} (mode 600). Do not commit it.`) return { path: out } } export async function keyVaultStatus(appIdArg: string | undefined, options: KeyVaultBaseOptions) { const appId = await resolveAppId(appIdArg) const status = await vaultApi(options, 'GET', appId) if (!status.configured) { log.info(`No OTA private key is stored in the key vault for ${appId}.`) return status } log.info(`Stored: revision ${status.revision}, updated ${status.updated_at}`) log.info(`Public key SHA-256: ${status.public_key_sha256}`) const configured = await configuredPublicKey() if (configured) log.info(await rsaPublicKeyFingerprint(configured) === status.public_key_sha256 ? 'Matches CapacitorUpdater.publicKey in this project.' : 'Does NOT match CapacitorUpdater.publicKey in this project.') if (!status.envelope_access) log.warn('This API key cannot download the encrypted key (needs app.upload_bundle).') const { envelope: _envelope, ...printable } = status return printable } export async function deleteKeyVault(appIdArg: string | undefined, options: KeyVaultDeleteOptions) { const appId = await resolveAppId(appIdArg) if (!options.yes && !stdin.isTTY) throw new CliUserError('Refusing to delete without confirmation in non-interactive mode; pass --yes') // Delete exactly the revision read here: a key stored meanwhile by someone else is kept (409). const status = await vaultApi(options, 'GET', appId, undefined, '?include_envelope=false') if (!status.configured || !status.revision) { log.info(`No OTA private key is stored in the key vault for ${appId}.`) return { deleted: false } } if (!options.yes) { const confirmed = await confirm({ message: `Delete the OTA private key stored in the Capgo key vault for ${appId} (revision ${status.revision}, SHA-256 ${status.public_key_sha256})? Keep a backup: without it you cannot sign updates for installed apps.` }) if (isCancel(confirmed) || !confirmed) { log.info('Cancelled.') return null } } const result = await vaultApi<{ deleted: boolean }>(options, 'DELETE', appId, undefined, `?expected_revision=${status.revision}`) log.success(`Deleted the OTA private key stored in the Capgo key vault for ${appId} (revision ${status.revision}).`) return result } function runCommand(fn: (...args: A) => Promise) { return async (...args: A) => { try { await fn(...args) } catch (error) { log.error(formatError(error)) process.exitCode = 1 } } } export const pushKeyVaultCommand = runCommand(pushKeyVault) export const pullKeyVaultCommand = runCommand(pullKeyVault) export const keyVaultStatusCommand = runCommand(keyVaultStatus) export const deleteKeyVaultCommand = runCommand(deleteKeyVault)