Skip to content
Closed
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
27 changes: 26 additions & 1 deletion browser/data-browser/src/helpers/agentStorage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ import { Agent } from '@tomic/react';

/** In-memory stand-in for IndexedDB, so we can inspect exactly what got stored. */
const store = new Map<string, unknown>();
/** Extra latency on every write, for tests that race a slow sign-in. */
let writeDelayMs = 0;

vi.mock('idb-keyval', () => ({
get: async (key: string) => store.get(key),
set: async (key: string, value: unknown) => void store.set(key, value),
set: async (key: string, value: unknown) => {
if (writeDelayMs) await new Promise(r => setTimeout(r, writeDelayMs));
store.set(key, value);
},
del: async (key: string) => void store.delete(key),
keys: async () => [...store.keys()],
}));
Expand All @@ -17,11 +22,13 @@ const {
readPreviousIdentities,
saveAgentToIDB,
} = await import('./agentStorage');
const { waitForSessionDbKey } = await import('./localDbKey');

const AGENT_IDB_KEY = 'atomic.agent';
const AGENT_FALLBACK_KEY = 'atomic.agent.fallback';
const SESSION_KEY_PREFIX = 'atomic.clientdb.session-key.';
const WRAPPED_KEY_PREFIX = 'atomic.clientdb.wrapped-key.';
const WRAPPED_KEY_V2_PREFIX = 'atomic.clientdb.wrapped-key-v2.';

async function makeSecret(): Promise<string> {
const keys = await Agent.generateKeyPair();
Expand Down Expand Up @@ -49,6 +56,22 @@ describe('agent key storage', () => {
beforeEach(() => store.clear());
afterEach(() => store.clear());

it('announces a sign-in before its first await, so the database opener waits for it', async () => {
const secret = await makeSecret();
const order: string[] = [];
// A sign-in slower than the opener's own patience, as one that loads the
// wasm bundle on a cold page is.
writeDelayMs = 300;
// What callers do: set the agent (which starts the opener), then save.
const saving = saveAgentToIDB(secret).then(() => order.push('saved'));
const opening = waitForSessionDbKey('atomic:agent:test', 100).then(() =>
order.push('opened'),
);
await Promise.all([saving, opening]).finally(() => (writeDelayMs = 0));

expect(order).toEqual(['saved', 'opened']);
});

it('never stores a readable private key where Web Crypto is available', async () => {
await saveAgentToIDB(await makeSecret());

Expand Down Expand Up @@ -94,6 +117,7 @@ describe('agent key storage', () => {
store.set(AGENT_FALLBACK_KEY, { privateKey: 'x', subject: 'y' });
store.set(`${SESSION_KEY_PREFIX}fingerprint`, 'session-copy');
store.set(`${WRAPPED_KEY_PREFIX}fingerprint`, 'wrapped-copy');
store.set(`${WRAPPED_KEY_V2_PREFIX}fingerprint`, 'wrapped-copy-v2');

await saveAgentToIDB(undefined);

Expand All @@ -105,6 +129,7 @@ describe('agent key storage', () => {
// ...while the wrapped copy survives, so the owning agent's cache becomes
// readable again on their next sign-in rather than being wiped.
expect(store.has(`${WRAPPED_KEY_PREFIX}fingerprint`)).toBe(true);
expect(store.has(`${WRAPPED_KEY_V2_PREFIX}fingerprint`)).toBe(true);
});
});

Expand Down
44 changes: 38 additions & 6 deletions browser/data-browser/src/helpers/agentStorage.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import {
Agent,
decodeSecret,
SubtleCryptoProvider,
JSCryptoProvider,
legacySubjectFromSecret,
} from '@tomic/react';
import { del, get, set } from 'idb-keyval';
import { adoptAgentOnDevice } from './adoptAgent';
import { clearSessionDbKeys, ensureDbKeyOnSignIn } from './localDbKey';
import {
clearSessionDbKeys,
ensureDbKeyOnSignIn,
trackDbKeySignIn,
type SignInCredentials,
} from './localDbKey';

const AGENT_IDB_KEY = 'atomic.agent';

Expand Down Expand Up @@ -177,7 +183,15 @@ export async function saveAgentToIDB(
}

if (typeof keyPairOrSecret === 'string') {
await storeSecret(keyPairOrSecret);
const stored = storeSecret(keyPairOrSecret);
// Announced before anything is awaited: callers often set the agent first,
// and the database opener that event starts must know a sign-in is about
// to deliver this agent's key (see `waitForSessionDbKey`).
const signingIn = subjectOfSecret(keyPairOrSecret);

if (signingIn) trackDbKeySignIn(signingIn, stored);

await stored;

// The device now holds this agent; its node should sign as this agent too.
// Best-effort and last, so a node that isn't up yet can't block sign-in.
Expand Down Expand Up @@ -212,6 +226,18 @@ export async function saveAgentToIDB(
} satisfies StoredAgent);
}

/**
* The agent subject a secret signs in as (the same one `storeSecret` stores),
* or undefined when the secret cannot be read.
*/
function subjectOfSecret(secret: string): string | undefined {
try {
return decodeSecret(secret).subject;
} catch {
return undefined;
}
}

/** Persist the agent's key, preferring a non-extractable keypair. */
async function storeSecret(secret: string): Promise<void> {
// The secret is a base64-encoded JSON containing { privateKey, subject }.
Expand Down Expand Up @@ -245,7 +271,10 @@ async function storeSecret(secret: string): Promise<void> {
} satisfies StoredAgent);
await del(AGENT_FALLBACK_KEY);

await ensureLocalDbKey(resolvedSubject, decoded.privateKey);
await ensureLocalDbKey(resolvedSubject, {
privateKey: decoded.privateKey,
vaultProof,
});

return;
} catch {
Expand All @@ -269,7 +298,10 @@ async function storeSecret(secret: string): Promise<void> {
// Drop a keypair from a previous account, so it can't be loaded instead.
await del(AGENT_IDB_KEY);

await ensureLocalDbKey(newSubject, decoded.privateKey);
await ensureLocalDbKey(newSubject, {
privateKey: decoded.privateKey,
vaultProof,
});
}
}

Expand All @@ -280,10 +312,10 @@ async function storeSecret(secret: string): Promise<void> {
*/
async function ensureLocalDbKey(
subject: string,
privateKey: string,
credentials: SignInCredentials,
): Promise<void> {
try {
await ensureDbKeyOnSignIn(subject, privateKey);
await ensureDbKeyOnSignIn(subject, credentials);
} catch (e) {
console.warn('Failed to prepare local database key:', e);
}
Expand Down
10 changes: 4 additions & 6 deletions browser/data-browser/src/helpers/initClientDb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
getOrCreateSessionDbKey,
getSessionDbKey,
hasWrappedDbKey,
waitForSessionDbKey,
} from './localDbKey';
import { wasmJsUrl } from './wasmUrls';

Expand Down Expand Up @@ -109,7 +110,7 @@ async function dbNameForAgent(agentSubject: string): Promise<string> {
* The encryption key for an agent's database, preferring the active-session
* record. A wrapped record without a session record means a sign-in is
* unwrapping it right now (`ensureDbKeyOnSignIn` runs alongside the
* AgentChanged event) — wait for that instead of generating a fresh key that
* AgentChanged event, announced by `trackDbKeySignIn`) — wait for that instead of generating a fresh key that
* couldn't open the existing encrypted file.
*
* Returns null when there is a wrapped record but no session key, which means
Expand All @@ -126,12 +127,9 @@ async function resolveDbKey(agentSubject: string): Promise<Uint8Array | null> {
if (existing) return existing;

if (await hasWrappedDbKey(agentSubject)) {
for (let attempt = 0; attempt < 30; attempt++) {
await new Promise(resolve => setTimeout(resolve, 100));
const key = await getSessionDbKey(agentSubject);
const key = await waitForSessionDbKey(agentSubject);

if (key) return key;
}
if (key) return key;

// The sign-in never delivered the key (e.g. an agent restored from a
// non-extractable keypair, where no secret enters JS).
Expand Down
Loading