mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-27 05:41:23 +00:00
feat(settings): onboard hub provider credentials for dictation and voice (#1392)
* feat(settings): onboard hub transcription provider credentials in UI Env-only keys made dictation invisible; Settings can now add/edit/clear hub-side credentials (masked), with env still winning as override. Refs tiann/hapi#1384. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(settings): onboard voice-assistant backends alongside dictation Same Settings credential surface now covers ElevenLabs, Gemini Live, and Qwen Realtime (alias env pairs), not only transcription providers. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): address PR #1392 Major credential onboard findings Alias env locks, non-destructive Save (omit empty fields), and owner-only settings.json permissions for hub-stored provider secrets. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): harden credential onboard for second-pass Majors Owner-namespace gate, stage-then-sync env after persist, and per-field OpenAI-compatible editability under mixed env locks. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): serialize settings RMW and clear partial compatible creds Per-file settings lock for concurrent credential PUTs, and Clear shown for partial OpenAI-compatible entries (key/url/model alone). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): serialize all settings writers via updateSettings Route credentials, relay auth, generators, server settings, and CLI token persistence through a locked RMW helper; reset Clear form state. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): share cross-process settings lock with CLI Extract withSettingsFileLock for hub+CLI, keep owner-only 0o600 rewrites, and race hub credential updates against CLI-style writers. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): keep UI secrets out of process.env; PID-own settings locks Settings-backed provider credentials now live in an in-memory overlay (getProviderEnvironment) so tunnel/ACP/Codex children do not inherit them. Settings file locks record pid+token and only reclaim dead or legacy locks. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): never reclaim ownerless settings lock sidecars wx creates the lock path before the owner JSON is visible; unlinking null owners let a waiter steal a live acquisition and collide on settings.json.tmp (CI ENOENT). Only reclaim parsed owners with dead PIDs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): reclaim dead locks via rename; clean up failed publishes Stale reclaim renames the sidecar to a unique break path and re-verifies the expected dead owner before deleting it, so a loser cannot unlink a successor's live lock. Failed owner writes unlink the wx sidecar. Reclaim uses a sync owner read so contenders do not all observe one dead owner across an await and race the exclusive create. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): reclaim dead locks under exclusive reaper sidecar Stale reclaim now takes a fixed settings.json.lock.reap lock, re-validates pid+token, then unlinks — so a delayed contender cannot move a successor's live lock aside. Also document providerCredentials in settings.schema.json. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): fail closed on corrupt CLI settings; backoff busy reaper CLI updateSettings now uses a strict read that rejects invalid JSON instead of treating errors as {}, which could wipe providerCredentials. Settings lock reclaim sleeps when another process holds .reap so retries are not burned synchronously. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): publish locks via candidate+link; fix CLI vitest hoist Acquire settings locks by writing a complete candidate then linkSync to the fixed path so a crash cannot leave an empty live sidecar. Fix the CLI persistence regression test to create its temp dir inside vi.hoisted. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): replace bespoke lock with proper-lockfile; hide tenant creds UI Codex kept finding crash windows in hand-rolled lock sidecars. Switch the shared settings lock to proper-lockfile's mkdir + mtime lease. Hide the owner-only credentials editor from non-default namespaces on the voice page. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(settings): adapt sessionSummaryContract to outcome updateSettings Rebase onto main brought #1376 unique tmp + outcome-shaped writers; wire sessionSummaryContract and the write-failure credential test to match. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: retrigger CI after rebase onto upstream/main Empty commit — Meta reported no checks on da0c6c258 after tip-forward rebase. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { writeFileSync, readFileSync, rmSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const { dir } = vi.hoisted(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const { mkdtempSync } = require('node:fs') as typeof import('node:fs')
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const { tmpdir } = require('node:os') as typeof import('node:os')
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const { join: pathJoin } = require('node:path') as typeof import('node:path')
|
||||
return { dir: mkdtempSync(pathJoin(tmpdir(), 'hapi-cli-settings-')) }
|
||||
})
|
||||
|
||||
vi.mock('@/configuration', () => ({
|
||||
configuration: {
|
||||
happyHomeDir: dir,
|
||||
settingsFile: join(dir, 'settings.json'),
|
||||
privateKeyFile: join(dir, 'access.key'),
|
||||
runnerStateFile: join(dir, 'runner.state.json'),
|
||||
runnerLockFile: join(dir, 'runner.state.json.lock'),
|
||||
logsDir: join(dir, 'logs'),
|
||||
},
|
||||
}))
|
||||
|
||||
import { updateSettings } from './persistence'
|
||||
|
||||
describe('updateSettings', () => {
|
||||
afterEach(() => {
|
||||
try {
|
||||
rmSync(join(dir, 'settings.json'), { force: true })
|
||||
rmSync(join(dir, 'settings.json.lock'), { force: true })
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects corrupt settings.json and leaves the original bytes intact', async () => {
|
||||
const settingsFile = join(dir, 'settings.json')
|
||||
writeFileSync(settingsFile, '{not-json')
|
||||
|
||||
await expect(
|
||||
updateSettings((current) => ({ ...current, apiUrl: 'http://should-not-write' }))
|
||||
).rejects.toThrow()
|
||||
|
||||
expect(readFileSync(settingsFile, 'utf8')).toBe('{not-json')
|
||||
})
|
||||
})
|
||||
+36
-60
@@ -5,8 +5,9 @@
|
||||
*/
|
||||
|
||||
import { FileHandle } from 'node:fs/promises'
|
||||
import { readFile, writeFile, mkdir, open, unlink, rename, stat } from 'node:fs/promises'
|
||||
import { readFile, writeFile, mkdir, open, unlink, rename, chmod } from 'node:fs/promises'
|
||||
import { existsSync, writeFileSync, readFileSync, unlinkSync } from 'node:fs'
|
||||
import { withSettingsFileLock } from '@hapi/protocol/settingsFileLock'
|
||||
import { configuration } from '@/configuration'
|
||||
import { isProcessAlive } from '@/utils/process';
|
||||
|
||||
@@ -78,12 +79,32 @@ export async function readSettings(): Promise<Settings> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Strict read for locked updates — never treat corrupt/unreadable files as empty. */
|
||||
async function readSettingsForUpdate(): Promise<Settings> {
|
||||
if (!existsSync(configuration.settingsFile)) {
|
||||
return { ...defaultSettings }
|
||||
}
|
||||
const content = await readFile(configuration.settingsFile, 'utf8')
|
||||
const parsed: unknown = JSON.parse(content)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error(`Invalid settings file: ${configuration.settingsFile}`)
|
||||
}
|
||||
return parsed as Settings
|
||||
}
|
||||
|
||||
export async function writeSettings(settings: Settings): Promise<void> {
|
||||
if (!existsSync(configuration.happyHomeDir)) {
|
||||
await mkdir(configuration.happyHomeDir, { recursive: true })
|
||||
await mkdir(configuration.happyHomeDir, { recursive: true, mode: 0o700 })
|
||||
}
|
||||
await chmod(configuration.happyHomeDir, 0o700).catch(() => {})
|
||||
|
||||
await writeFile(configuration.settingsFile, JSON.stringify(settings, null, 2))
|
||||
await withSettingsFileLock(configuration.settingsFile, async () => {
|
||||
const tmpFile = configuration.settingsFile + '.tmp'
|
||||
await writeFile(tmpFile, JSON.stringify(settings, null, 2), { mode: 0o600 })
|
||||
await chmod(tmpFile, 0o600).catch(() => {})
|
||||
await rename(tmpFile, configuration.settingsFile)
|
||||
await chmod(configuration.settingsFile, 0o600).catch(() => {})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -94,66 +115,21 @@ export async function writeSettings(settings: Settings): Promise<void> {
|
||||
export async function updateSettings(
|
||||
updater: (current: Settings) => Settings | Promise<Settings>
|
||||
): Promise<Settings> {
|
||||
// Timing constants
|
||||
const LOCK_RETRY_INTERVAL_MS = 100; // How long to wait between lock attempts
|
||||
const MAX_LOCK_ATTEMPTS = 50; // Maximum number of attempts (5 seconds total)
|
||||
const STALE_LOCK_TIMEOUT_MS = 10000; // Consider lock stale after 10 seconds
|
||||
|
||||
if (!existsSync(configuration.happyHomeDir)) {
|
||||
await mkdir(configuration.happyHomeDir, { recursive: true });
|
||||
await mkdir(configuration.happyHomeDir, { recursive: true, mode: 0o700 })
|
||||
}
|
||||
await chmod(configuration.happyHomeDir, 0o700).catch(() => {})
|
||||
|
||||
const lockFile = configuration.settingsFile + '.lock';
|
||||
const tmpFile = configuration.settingsFile + '.tmp';
|
||||
let fileHandle;
|
||||
let attempts = 0;
|
||||
|
||||
// Acquire exclusive lock with retries
|
||||
while (attempts < MAX_LOCK_ATTEMPTS) {
|
||||
try {
|
||||
// 'wx' = create exclusively, fail if exists (cross-platform compatible)
|
||||
fileHandle = await open(lockFile, 'wx');
|
||||
break;
|
||||
} catch (err: any) {
|
||||
if (err.code === 'EEXIST') {
|
||||
// Lock file exists, wait and retry
|
||||
attempts++;
|
||||
await new Promise(resolve => setTimeout(resolve, LOCK_RETRY_INTERVAL_MS));
|
||||
|
||||
// Check for stale lock
|
||||
try {
|
||||
const stats = await stat(lockFile);
|
||||
if (Date.now() - stats.mtimeMs > STALE_LOCK_TIMEOUT_MS) {
|
||||
await unlink(lockFile).catch(() => { });
|
||||
}
|
||||
} catch { }
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!fileHandle) {
|
||||
throw new Error(`Failed to acquire settings lock after ${MAX_LOCK_ATTEMPTS * LOCK_RETRY_INTERVAL_MS / 1000} seconds`);
|
||||
}
|
||||
|
||||
try {
|
||||
// Read current settings with defaults
|
||||
const current = await readSettings() || { ...defaultSettings };
|
||||
|
||||
// Apply update
|
||||
const updated = await updater(current);
|
||||
|
||||
// Write atomically using rename
|
||||
await writeFile(tmpFile, JSON.stringify(updated, null, 2));
|
||||
await rename(tmpFile, configuration.settingsFile); // Atomic on POSIX
|
||||
|
||||
return updated;
|
||||
} finally {
|
||||
// Release lock
|
||||
await fileHandle.close();
|
||||
await unlink(lockFile).catch(() => { }); // Remove lock file
|
||||
}
|
||||
return withSettingsFileLock(configuration.settingsFile, async () => {
|
||||
const current = await readSettingsForUpdate()
|
||||
const updated = await updater(current)
|
||||
const tmpFile = configuration.settingsFile + '.tmp'
|
||||
await writeFile(tmpFile, JSON.stringify(updated, null, 2), { mode: 0o600 })
|
||||
await chmod(tmpFile, 0o600).catch(() => {})
|
||||
await rename(tmpFile, configuration.settingsFile)
|
||||
await chmod(configuration.settingsFile, 0o600).catch(() => {})
|
||||
return updated
|
||||
})
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
Reference in New Issue
Block a user