Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/daintree-integration-spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,7 @@ While the person is away, Daintree can ask the relay to tell their phone that an
- Epoch keys come from the `KeyStore` (safeStorage), and old epochs are kept, so content sealed before a rotation stays readable. Opening uses `openQuestionContent`, `openAnswerContent` and `openAnswers`.
- Rows written before sealing existed are sealed by `sealStoredContent({ store, identity })`, which `DecisionsBridge.start()` runs first; it then calls the optional `LocalStore.compact()`, and keeps retrying on later starts until a compaction succeeds. Daintree's store must implement `compact()` (`VACUUM` and `PRAGMA wal_checkpoint(TRUNCATE)`, throwing when the checkpoint reports `busy`) and should open with `PRAGMA secure_delete = ON`, as `SqliteLocalStore` does, so freed pages and the WAL never retain old plaintext. `SqliteLocalStore` keeps a pre-sealing `content_json` column only to hand legacy rows to that pass (`legacy_content_json`), which clears it.
- A 0.8.0 bridge kept the earlier round's deadline when it applied a reopen; 0.9.0 repairs those rows from the stored reopens it can verify, and only through the optional `LocalStore.processedEventsOfType(eventType)`. Daintree's store must implement it before shipping 0.9.0 over a 0.8.0 database: every row of `decisions_inbound_events` of that type with `processed_at IS NOT NULL` (rejected events included), ordered by ascending `seq`, each as a full `InboundEvent` with its original `json`, as `SqliteLocalStore` does. Without it nothing is repaired, so such a question can miss its expiry (asked with no deadline and reopened with one, it never expires) or be closed at the earlier round's deadline, and the bridge looks once, as it starts or first applies events: while any reopened question is open it reports a `not_supported` `BridgeError` on `on("error")`, before `start()` returns. Register the listener before the first `start()`, `catchUp()` or `sync()`, and surface the error. Keep the inbound events: once the method is implemented, a new bridge over the same store repairs the rows in the background, though an expiry refused before then stays refused and a question closed before then stays closed.
- **A store a newer library wrote is refused.** The store's `meta` keeps the format of what it holds under `STORE_FORMAT_KEY` (`store_format`), which a library release moves on (`STORE_FORMAT`) only when it starts storing something an older one may misread, such as a new answer entry kind. `daintreeLocalStore.ts` checks it when it opens, before anything reads or writes the store: in one transaction, it reads the value, passes it to `checkStoreFormat` (which throws `StoreFormatError` for a newer or unreadable format), and writes `STORE_FORMAT` when the stored format is older or missing. It refuses its own schema when that is newer than its migrations, too, as `SqliteLocalStore` does. Daintree shows the error's message and leaves the store alone; upgrading Daintree opens it. `DecisionsBridge.start()` checks the format again (`admitStoreFormat`, through `getMeta` and `setMeta`) and rejects with the same error before it starts anything; `bridge.idle()` also waits for that check before the store is closed. A store this check passed can still hold an entry the library cannot type: delivery never types it but holds its question for the person (`needs-attention`, with `answer_unknown_kind` or `answer_unknown_source`), and `get_decision` never reports it as the person's answer.
- If the user opts into decision-model learning, pass `learner: asBridgeLearner(history)` (from `@daintreehq/decisions-model`) to the bridge. Human answers and overrides (never proxy answers or confirmations of them) are offered to it, and the history store records them only while learning is on and the project is not opted out, with the secrets filter applied. It is the only place question or answer plaintext is written. A failing learner is audited (`learning.failed`) and never blocks delivery.
- The other plaintext on disk is opt-in by the user: an export written with `plaintext` (exports are encrypted by default), and the audit log's message text when `debugContent` is on.

Expand Down
2 changes: 2 additions & 0 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ Question and answer ciphertext is kept until you delete it (it is your decision

The relay stores ciphertext only; a backup of it is useless without your keys. Back up your keys (`decisions recovery export`), not the relay. See [key-recovery.md](key-recovery.md). To rebuild a relay: deploy again, claim with the same desktop keys, and re-pair phones; history on the old relay is discarded unless you export it first (`decisions export`).

A client refuses a state directory that a newer client has stored something in that it could misread (its local store holds a newer schema or data format). It says so in an error before it reads, migrates, seals or changes any record there; upgrade the client to use the directory. Stop running listeners before upgrading: a client already running when a newer one opens its state directory does not check again, though it never types an answer entry it does not understand.

## Deleting data

- One question: `DELETE /api/v1/questions/{id}` (owner), which also removes its events and schedules removal of its attachments.
Expand Down
17 changes: 16 additions & 1 deletion packages/cli/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
defaultHome,
loadIdentity,
sealStoredContent,
StoreFormatError,
type Identity,
type KeyStore,
type LocalStore,
Expand Down Expand Up @@ -130,7 +131,7 @@ export async function openRuntime(ctx: Ctx, g: GlobalOptions = {}): Promise<Runt
throw new CliError((e as Error).message);
}
await mkdir(ctx.home, { recursive: true, mode: 0o700 });
const store = new SqliteLocalStore(join(ctx.home, 'decisions.db'));
const store = openStore(ctx.home);
try {
// A store written before content was sealed is sealed (and compacted) on first open, whatever the command.
await sealStoredContent({ store, identity });
Expand All @@ -142,6 +143,20 @@ export async function openRuntime(ctx: Ctx, g: GlobalOptions = {}): Promise<Runt
return { ctx, keyStore, identity, client, store, auditPath: join(ctx.home, 'audit.jsonl') };
}

/**
* The state directory's store. A newer client's store (its schema or data format is newer than this client's) is
* refused before anything reads or writes it, so this client never misreads what a newer one left there.
*/
function openStore(home: string): SqliteLocalStore {
const path = join(home, 'decisions.db');
try {
return new SqliteLocalStore(path);
} catch (e) {
if (e instanceof StoreFormatError) throw new CliError(`cannot use ${path}: ${e.message}`);
throw e;
}
}

export async function readSecretFile(path: string, create: () => string): Promise<string> {
try {
return (await readFile(path, 'utf8')).trim();
Expand Down
27 changes: 27 additions & 0 deletions packages/cli/tests/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -868,6 +868,33 @@ describe('export / import / recovery / delete-data', () => {
if (existsSync(p)) expect(readFileSync(p).includes(Buffer.from('OLDPLAIN'))).toBe(false);
}
});
it('a command refuses a state directory a newer client wrote, before touching it', async () => {
const { ctx } = await ready();
await ask(ctx, {}, { question: 'Fresh question' });
const dbFile = join(ctx.home, 'decisions.db');
const raw = new DatabaseSync(dbFile);
// A newer client's data format, and a row this client would otherwise seal on open.
raw.prepare("UPDATE meta SET value = '2' WHERE key = 'store_format'").run();
raw
.prepare('UPDATE questions SET content_json = ?, content_sealed = NULL')
.run(JSON.stringify({ content_version: 1, question: 'NEWERPLAIN question' }));
raw.close();
const err = await status(ctx, {}).catch((e: unknown) => e);
expect(err).toBeInstanceOf(CliError);
expect((err as CliError).exitCode).toBe(1);
expect((err as CliError).message).toContain(`cannot use ${dbFile}`);
expect((err as CliError).message).toMatch(
/data format 2, and this client reads formats up to 1.*Upgrade this client/,
);
const after = new DatabaseSync(dbFile);
expect(after.prepare("SELECT value FROM meta WHERE key = 'store_format'").get()).toMatchObject({
value: '2',
});
expect(after.prepare('SELECT content_json FROM questions').get()).toMatchObject({
content_json: expect.stringContaining('NEWERPLAIN'),
});
after.close();
});
it('recovery kit export, verify and restore', async () => {
const env = { DECISIONS_RECOVERY_PASSPHRASE: 'a long recovery passphrase' };
const a = await ready({ env });
Expand Down
24 changes: 24 additions & 0 deletions packages/client/src/answers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,30 @@ export function parseAnswers(json: string): AnswerEntry[] {
}
export const serializeAnswers = (a: AnswerEntry[]): string => JSON.stringify(a);

const KNOWN_KINDS: ReadonlySet<string> = new Set<AnswerEntry['kind']>([
'answer',
'expired',
'declined',
'unpublished',
]);

/**
* Why this client cannot type `e`, or null when it can. A newer client may store an entry of a kind this one does not
* know (`answer_unknown_kind`), or one from a source this client does not expect for its kind
* (`answer_unknown_source`): an answer from anyone but the person or the proxy, or a decline from anyone but the
* person. Typed, either would read as the person's answer or decision. Delivery holds such an entry and reports its
* question instead. An expiry's notice says who closed the question itself, so its stored source is not checked.
*/
export function unsupportedEntry(
e: Pick<AnswerEntry, 'kind' | 'source'>,
): 'answer_unknown_kind' | 'answer_unknown_source' | null {
if (!KNOWN_KINDS.has(e.kind)) return 'answer_unknown_kind';
if (e.kind === 'answer' && e.source !== 'human' && e.source !== 'proxy')
return 'answer_unknown_source';
if (e.kind === 'declined' && e.source !== 'human') return 'answer_unknown_source';
return null;
}

/** An expiry notice of an advisory round, typed as the advisory notice (`advisory_disposition`). */
export const isAdvisoryNotice = (e: Pick<AnswerEntry, 'kind' | 'advisory_disposition'>): boolean =>
e.kind === 'expired' && e.advisory_disposition !== undefined;
Expand Down
4 changes: 3 additions & 1 deletion packages/client/src/at-rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
legacyContent,
parseAnswers,
serializeAnswers,
unsupportedEntry,
type AnswerContent,
type AnswerEntry,
type OpenAnswerEntry,
Expand Down Expand Up @@ -396,7 +397,8 @@ export async function sealStoredContent(
// flag) is kept rather than overwritten by the stale snapshot.
const seals = new Map<string, string | null>();
for (const e of parseAnswers(snapshot.answers_json)) {
if (!hasLegacyContent(e)) continue;
// An entry this client does not understand (a newer client's) is left exactly as it is.
if (!hasLegacyContent(e) || unsupportedEntry(e)) continue;
seals.set(
e.entry_id,
e.sealed ??
Expand Down
47 changes: 40 additions & 7 deletions packages/client/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
parseAnswers,
sameDigests,
unpublishedPlanDue,
unsupportedEntry,
type AdvisoryDisposition,
type OpenAnswerEntry,
} from './answers.js';
Expand All @@ -74,6 +75,7 @@ import {
} from './identity.js';
import type { DecisionLearner, ProxyEngine, ProxyOutcome } from './proxy.js';
import { Mutex, TransientError } from './mutex.js';
import { admitStoreFormat } from './store-format.js';
import { RelayClient, type CallOptions } from './relay.js';
import {
DECLARE_EVERY_MS,
Expand Down Expand Up @@ -556,6 +558,10 @@ export class DecisionsBridge {
state: BridgeState = 'created';
/** Bumped by every start, stop and revocation: a start still recovering when one comes starts nothing more. */
private lifecycle = 0;
/** The store's admissions `start` waits for, so `idle` waits for their reads too. */
private readonly admissions = new Set<Promise<void>>();
/** The start admitting the store for this lifecycle: a call made meanwhile is its second call. */
private starting: { lifecycle: number; admission: Promise<void> } | null = null;
private timer: ReturnType<typeof setInterval> | null = null;
private pumping: Promise<void> | null = null;
/**
Expand Down Expand Up @@ -803,7 +809,8 @@ export class DecisionsBridge {
/**
* Reconcile interrupted injections, connect the socket, start the retry timer. Without a socket
* (`socket: false`) the host reads events itself (`catchUp`, `sync`), or passes `poll` to have the bridge
* sync over HTTP continuously, starting now, until it stops or is revoked.
* sync over HTTP continuously, starting now, until it stops or is revoked. Rejects with `StoreFormatError`, having
* started nothing, when a newer client wrote the store (`admitStoreFormat`).
*
* A stopped bridge can be started again, and delivers again once a write still in flight from before the stop has
* settled. A revoked one cannot: `start` throws `forbidden`.
Expand All @@ -819,6 +826,26 @@ export class DecisionsBridge {
throw new BridgeError('forbidden', 'this device was revoked from the relay');
// A second call returns once a store that cannot be repaired has been reported, as the first does.
if (this.state === 'running') return this.inbox.checkHistory();
// A call made while the first admits the store is a second call: the first, which chose the transport, starts.
const first = this.starting;
if (first && first.lifecycle === this.lifecycle) {
await first.admission;
return this.running() ? this.inbox.checkHistory() : undefined;
}
// Nothing reads or writes the store before it is admitted. A stop or a revocation while it was being read wins:
// each moves the lifecycle on, and a start made after it admits the store again.
const admitting = this.lifecycle;
const admission = admitStoreFormat(this.ctx.store);
const starting = { lifecycle: admitting, admission };
this.starting = starting;
this.admissions.add(admission);
try {
await admission;
} finally {
this.admissions.delete(admission);
if (this.starting === starting) this.starting = null;
}
if (admitting !== this.lifecycle) return this.running() ? this.inbox.checkHistory() : undefined;
const run = ++this.lifecycle;
this.httpAbort = new AbortController();
this.state = 'running';
Expand Down Expand Up @@ -897,7 +924,8 @@ export class DecisionsBridge {
/**
* Stop everything this bridge started. An HTTP sync in flight has its requests aborted, and `stop` waits for it to
* settle, so the host can close the store afterwards; a request that is not the sync's own (a key lookup while
* verifying an event) is cut short only by `RelayClient.close()`.
* verifying an event) is cut short only by `RelayClient.close()`. A start still admitting the store is waited for by
* `idle()`.
*/
async stop(): Promise<void> {
this.lifecycle++;
Expand Down Expand Up @@ -938,6 +966,7 @@ export class DecisionsBridge {
() => undefined,
);
await Promise.all([
...[...this.admissions].map(quiet),
quiet(this.pumping),
quiet(this.syncing),
quiet(this.paging?.pass),
Expand Down Expand Up @@ -1445,7 +1474,9 @@ export class DecisionsBridge {
let confirmation: OpenAnswerEntry | undefined;
for (const e of entries) {
if (e.kind !== 'answer') continue;
if (e.action === 'confirm-proxy') confirmation = current ? e : undefined;
// Only the person confirms a proxy answer: a confirmation from anyone else (a newer client's) confirms nothing.
if (e.action === 'confirm-proxy')
confirmation = current && e.source === 'human' ? e : undefined;
else {
current = e;
confirmation = undefined;
Expand All @@ -1456,7 +1487,7 @@ export class DecisionsBridge {
// Only a reopen changes a cancelled question, and it moves the revision on: a decline at this revision is the
// cancellation in force.
const declined = entries.some(
(e) => e.kind === 'declined' && e.revision === row.question_revision,
(e) => e.kind === 'declined' && e.revision === row.question_revision && !unsupportedEntry(e),
);
// Every answer, correction or confirmation moves the revision on and is kept with its revision; a reopen moves it
// without one. So a revision the answers do not account for means the question was reopened into a round that
Expand Down Expand Up @@ -1496,12 +1527,14 @@ export class DecisionsBridge {
plannedFallback,
errorCode: row.local_status === 'publish-failed' ? row.error_code : null,
workflowGateId: row.origin.workflow_gate_id,
// An answer from a source this client does not know (a newer client's) is reported as no one's, never the
// person's.
provenance: inForce
? confirmed
? 'human'
: inForce.source === 'proxy'
? 'proxy'
: 'human'
: inForce.source === 'proxy' || inForce.source === 'human'
? inForce.source
: null
: null,
answeredOn: inForce ? answeredOn(confirmation ?? inForce) : null,
closedReason:
Expand Down
Loading
Loading