/** * keystore.ts — encryption-at-rest key management (SEC-1/2, Wave 1 task 1b). * * Provider chain (per spec §4.1 / OQ-1): * (a) OS credential store — Windows Credential Manager / macOS Keychain / * Linux libsecret, via `@napi-rs/keyring` (prebuilt N-API binding, * verified to install cleanly with prebuilds for win32-x64-msvc, * darwin-x64/arm64, and linux-x64-gnu — the repo's 3 CI targets). * (b) key-file fallback (`/db.key`, mode 0600) with a WARN log — * used when the credential store throws (e.g. headless Linux with no * secret-service/dbus session). Spec OQ-1 explicitly allows this * fallback for v0.4. * * Credential-store identity is SCOPED by configDir (FEAT-466; extended to the * sync device token by FEAT-472): the service name is * `astramem-local:`, not the bare `astramem-local` used * pre-FEAT-466. This closes a 2026-07-10 incident where a sandboxed `init` * run (pointed at a throwaway configDir) overwrote the PRODUCTION daemon's * bearer, because the OS credential store is keyed globally by * service+account, not by configDir — two independent installs collided on * the exact same entry. Reads fall back read-only to the legacy unscoped * identity (service `'astramem-local'`, account `'db-key'`/`'bearer'`/ * `'sync-device-token'`) so pre-FEAT-466/pre-FEAT-472 installs keep working * after upgrade with no re-init/re-pair or migration step; new writes always * go to the scoped identity. * * The key is a 32-byte cryptographically random value, hex-encoded (64 chars), * used as the SQLCipher passphrase via `PRAGMA key=''` — the exact * PRAGMA form validated end-to-end (open/reopen/wrong-key) by the 1a spike * (tests/security/cipher-spike.test.ts). * * getOrCreateKey() is idempotent: a second call against the same configDir * (and, for the credential-store path, the same machine/user) returns the * same key rather than minting a new one. * * ASTRA_MEMORY_TEST_FORCE_KEYFILE=1 (FEAT-415, extended by FEAT-466 to also * cover the bearer): test-only bypass that skips the credential-store * attempt entirely and goes straight to a file fallback under configDir * (`db.key` / `bearer.key`). Exists because the encrypted-restart smoke * suite spawns the daemon as a separate child process — the in-process * __setEntryCtorForTests stub below has no effect across a process * boundary — and because a sandboxed/test `init` must have a way to NEVER * touch the real OS credential store even though scoping alone (above) * cannot fully prevent that when the test runs on the same machine/user as * the real daemon. Never set by real serving; no config.yaml/CLI surface * exposes it. */ import type { Entry } from '@napi-rs/keyring'; export type KeySource = 'credential-store' | 'key-file'; export type KeyIdentity = 'scoped' | 'legacy'; export interface KeyResult { key: string; source: KeySource; /** Only meaningful when source === 'credential-store'. */ identity?: KeyIdentity; } /** * Normalizes configDir before hashing (review defense-in-depth): resolves * to an absolute path (also strips a trailing separator) and, on Windows, * case-folds — so `C:\Users\x`, `c:\users\x`, `C:/Users/x`, and a * trailing-backslash variant all hash to the SAME scoped identity instead * of four different ones. Every real call site in this repo already * derives configDir from the single `defaultConfigDir()` function, so this * has no effect on current behavior; it only guards a future call site * that constructs configDir some other way. * * `platform` is injectable (FEAT-470 quickwin, FEAT-466 re-review LOW) so * the non-win32 (case-preserving) branch has an executable test on every * CI platform, not just whichever OS happens to run the suite — it defaults * to `process.platform` for every real call site, so this has no effect on * actual behavior. */ export declare function normalizeConfigDir(configDir: string, platform?: NodeJS.Platform): string; /** Test-only hook: override (or restore) the credential-store Entry constructor. */ export declare function __setEntryCtorForTests(ctor: typeof Entry | undefined): void; /** Test-only hook: clears the process-lifetime key cache. Real callers never * need this — a fresh process starts with an empty cache — but a test * process that calls getOrCreateKey() against the SAME configDir twice, * expecting the SECOND call to re-derive against mutated stub state (rather * than reuse the first call's cached result), needs to clear it between * arrangements. */ export declare function __resetKeyCacheForTests(): void; /** * Returns the encryption key for this machine/user, creating one on first * use. Tries the OS credential store first; falls back to a 0600 key file * under `configDir` (with a WARN log) when the credential store throws. * Memoized per (normalized) configDir for the lifetime of this process — see * `keyCache`'s doc comment above for why repeat calls must be free, not just * bounded. * * NOTE: deviates slightly from the originally-sketched `(configDir) => string` * signature — returns `{ key, source }` instead of a bare string so callers * (doctor, /health) can report key location (SEC-8/AC-5) without a second, * duplicate resolution pass. `.key` is what openDb()/migrate-encrypt need. */ export declare function getOrCreateKey(configDir: string): KeyResult; export declare function keyFilePath(configDir: string): string; export interface BearerStoreResult { stored: boolean; source: 'credential-store' | 'secrets-env-fallback' | 'key-file'; /** Only meaningful when source === 'credential-store'. */ identity?: KeyIdentity; } export declare function bearerFilePath(configDir: string): string; export interface StoreBearerOpts { /** * Review fix-round (rollback hazard): also best-effort write `token` into * the LEGACY unscoped identity, not just the scoped one. This is a * deliberate, narrowly-scoped exception to the "legacy is read-only" * rule (AC-2) — rotation is exactly the moment a stale legacy entry * becomes dangerous: a `reinstall --rollback` to a pre-FEAT-466 binary * reads the legacy identity directly (it has no scoping concept at all), * so if rotation only refreshed the scoped identity, the rolled-back * binary would resolve a stale bearer instead of the one just issued. * Only `token.ts`'s `rotateToken()` sets this — `init.ts`'s first-time * provisioning deliberately does NOT, since writing the legacy identity * from a sandboxed/test `init` is the exact mechanism that caused the * original 2026-07-10 incident this FEAT closes. Never touched when the * ASTRA_MEMORY_TEST_FORCE_KEYFILE bypass is active (that path never * touches the OS store at all, scoped or legacy). */ writeThroughLegacy?: boolean; } /** * Store `token` in the OS credential store, under the identity scoped to * `configDir` (FEAT-466). On failure (no credential store / no * secret-service session), WARNs and returns a fallback marker so the * caller persists the bearer into secrets.env instead (SEC-10). * * ASTRA_MEMORY_TEST_FORCE_KEYFILE=1 skips the OS credential store entirely * (AC-3) — a sandboxed/test caller that sets this never touches the real * store, writing to `/bearer.key` instead. */ export declare function storeBearer(token: string, configDir: string, opts?: StoreBearerOpts): BearerStoreResult; /** * Read the bearer token from the OS credential store, if present: the * identity scoped to `configDir` first, then a read-only fallback to the * legacy unscoped identity (AC-2). Returns null on any error (store * unavailable, or no entry under either identity) — same "throw and * getPassword()->null are both just 'no key yet'" tolerance as * getOrCreateCredentialStoreKey above. Callers fall back to secrets.env. * * Honors the same ASTRA_MEMORY_TEST_FORCE_KEYFILE=1 bypass as storeBearer — * reads from `/bearer.key` instead of the OS store (AC-4: this is * what makes the bypass's "OS store untouched" guarantee provable, since a * before/after OS-store read never even attempts the scoped/legacy lookup). */ export declare function readBearer(configDir: string): string | null; /** * Doctor-facing variant of readBearer(): reports which identity (scoped vs * legacy vs the test-only key-file bypass) the bearer was actually read * from, or 'none' when no bearer is stored under any of them (AC-5). */ export declare function getBearerIdentity(configDir: string): KeyIdentity | 'key-file' | 'none'; export declare function syncTokenFilePath(configDir: string): string; /** * Store the cloud sync device token (ADR-003 auth) in the OS credential * store, under the identity scoped to `configDir` (FEAT-472, mirroring * storeBearer). ASTRA_MEMORY_TEST_FORCE_KEYFILE=1 skips the OS credential * store entirely, writing to `/sync-token.key` instead. */ export declare function storeSyncToken(token: string, configDir: string): BearerStoreResult; /** * Read the cloud sync device token: the identity scoped to `configDir` * first, then a read-only fallback to the legacy unscoped identity (pre- * FEAT-472 installs keep working with no re-pair). Null when absent under * either identity or when the store is unavailable. */ export declare function readSyncToken(configDir: string): string | null; /** * Doctor-facing variant of readSyncToken(): reports which identity (scoped * vs legacy vs the test-only key-file bypass) the sync device token was * actually read from, or 'none' when nothing is stored under any of them. */ export declare function getSyncTokenIdentity(configDir: string): KeyIdentity | 'key-file' | 'none';