| layout | default |
|---|---|
| title | Chapter 7: Configuration and Security |
| nav_order | 7 |
| parent | HAPI Tutorial |
Welcome to Chapter 7: Configuration and Security. In this part of HAPI Tutorial: Remote Control for Local AI Coding Sessions, you will build an intuitive mental model first, then move into concrete implementation details and practical production tradeoffs.
HAPI security depends on disciplined token management, environment separation, and controlled exposure.
| Domain | Examples |
|---|---|
| auth/token | CLI_API_TOKEN, access token settings |
| endpoint config | HAPI_API_URL, listen host/port, publicUrl |
| notifications | Telegram token/settings |
| optional voice | ElevenLabs key and agent settings |
- keep secrets outside version control
- rotate tokens on schedule and after incidents
- segregate dev/stage/prod hub deployments
- restrict externally reachable surfaces to required endpoints
- audit log review for auth failures and approval anomalies
- machine offboarding process with token revocation
- periodic configuration drift audits against baseline policy
You now have a security baseline for moving HAPI from personal setup to team deployment.
Next: Chapter 8: Production Operations
Most teams struggle here because the hard part is not writing more code, but deciding clear boundaries for core abstractions in this chapter so behavior stays predictable as complexity grows.
In practical terms, this chapter helps you avoid three common failures:
- coupling core logic too tightly to one implementation path
- missing the handoff boundaries between setup, execution, and validation
- shipping changes without clear rollback or observability strategy
After working through this chapter, you should be able to reason about Chapter 7: Configuration and Security as an operating subsystem inside HAPI Tutorial: Remote Control for Local AI Coding Sessions, with explicit contracts for inputs, state transitions, and outputs.
Use the implementation notes around execution and reliability details as your checklist when adapting these patterns to your own repository.
Under the hood, Chapter 7: Configuration and Security usually follows a repeatable control path:
- Context bootstrap: initialize runtime config and prerequisites for
core component. - Input normalization: shape incoming data so
execution layerreceives stable contracts. - Core execution: run the main logic branch and propagate intermediate state through
state model. - Policy and safety checks: enforce limits, auth scopes, and failure boundaries.
- Output composition: return canonical result payloads for downstream consumers.
- Operational telemetry: emit logs/metrics needed for debugging and performance tuning.
When debugging, walk this sequence in order and confirm each stage has explicit success/failure conditions.
Use the following upstream sources to verify implementation details while reading this chapter:
- HAPI Repository
Why it matters: authoritative reference on
HAPI Repository(github.com). - HAPI Releases
Why it matters: authoritative reference on
HAPI Releases(github.com). - HAPI Docs
Why it matters: authoritative reference on
HAPI Docs(hapi.run).
- Tutorial Index
- Previous Chapter: Chapter 6: PWA, Telegram, and Extensions
- Next Chapter: Chapter 8: Production Operations
- Main Catalog
- A-Z Tutorial Directory
The readSettings function in cli/src/persistence.ts handles a key part of this chapter's functionality:
}
export async function readSettings(): Promise<Settings> {
if (!existsSync(configuration.settingsFile)) {
return { ...defaultSettings }
}
try {
const content = await readFile(configuration.settingsFile, 'utf8')
return JSON.parse(content)
} catch {
return { ...defaultSettings }
}
}
export async function writeSettings(settings: Settings): Promise<void> {
if (!existsSync(configuration.happyHomeDir)) {
await mkdir(configuration.happyHomeDir, { recursive: true })
}
await writeFile(configuration.settingsFile, JSON.stringify(settings, null, 2))
}
/**
* Atomically update settings with multi-process safety via file locking
* @param updater Function that takes current settings and returns updated settings
* @returns The updated settings
*/
export async function updateSettings(
updater: (current: Settings) => Settings | Promise<Settings>
): Promise<Settings> {
// Timing constantsThis function is important because it defines how HAPI Tutorial: Remote Control for Local AI Coding Sessions implements the patterns covered in this chapter.
The writeSettings function in cli/src/persistence.ts handles a key part of this chapter's functionality:
}
export async function writeSettings(settings: Settings): Promise<void> {
if (!existsSync(configuration.happyHomeDir)) {
await mkdir(configuration.happyHomeDir, { recursive: true })
}
await writeFile(configuration.settingsFile, JSON.stringify(settings, null, 2))
}
/**
* Atomically update settings with multi-process safety via file locking
* @param updater Function that takes current settings and returns updated settings
* @returns The updated settings
*/
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 });
}
const lockFile = configuration.settingsFile + '.lock';
const tmpFile = configuration.settingsFile + '.tmp';
let fileHandle;
let attempts = 0;This function is important because it defines how HAPI Tutorial: Remote Control for Local AI Coding Sessions implements the patterns covered in this chapter.
The updateSettings function in cli/src/persistence.ts handles a key part of this chapter's functionality:
* @returns The updated settings
*/
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 });
}
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 lockThis function is important because it defines how HAPI Tutorial: Remote Control for Local AI Coding Sessions implements the patterns covered in this chapter.
The writeCredentialsDataKey function in cli/src/persistence.ts handles a key part of this chapter's functionality:
//
export async function writeCredentialsDataKey(credentials: { publicKey: Uint8Array, machineKey: Uint8Array, token: string }): Promise<void> {
if (!existsSync(configuration.happyHomeDir)) {
await mkdir(configuration.happyHomeDir, { recursive: true })
}
await writeFile(configuration.privateKeyFile, JSON.stringify({
encryption: { publicKey: Buffer.from(credentials.publicKey).toString('base64'), machineKey: Buffer.from(credentials.machineKey).toString('base64') },
token: credentials.token
}, null, 2));
}
export async function clearCredentials(): Promise<void> {
if (existsSync(configuration.privateKeyFile)) {
await unlink(configuration.privateKeyFile);
}
}
export async function clearMachineId(): Promise<void> {
await updateSettings(settings => ({
...settings,
machineId: undefined
}));
}
/**
* Read runner state from local file
*/
export async function readRunnerState(): Promise<RunnerLocallyPersistedState | null> {
try {
if (!existsSync(configuration.runnerStateFile)) {
return null;This function is important because it defines how HAPI Tutorial: Remote Control for Local AI Coding Sessions implements the patterns covered in this chapter.
flowchart TD
A[readSettings]
B[writeSettings]
C[updateSettings]
D[writeCredentialsDataKey]
E[clearCredentials]
A --> B
B --> C
C --> D
D --> E