Repository navigation
Expand file tree
/
Copy pathoffline-cache.ts
More file actions
452 lines (410 loc) · 15.9 KB
/
Copy pathoffline-cache.ts
File metadata and controls
452 lines (410 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
"use client";
/**
* Client for the desktop shell's encrypted offline read cache (cave-f1k8n).
*
* The native side (`src-tauri/src/offline_cache.rs`) owns the crypto, the
* caps, and the purge rules. This module owns the two things that have to
* happen before a payload is allowed near the disk:
*
* 1. **Sanitization.** The cache is encrypted, but "encrypted" is not a
* licence to persist a bearer token or an attachment's bytes. Whatever
* survives {@link sanitizeForOfflineCache} is what gets stored, and the
* rules are deliberately conservative: a key that reads like a credential
* is dropped, and so is any value that looks like embedded file bytes.
* 2. **Read-only framing.** A cached read is history, never live state.
* Every hit comes back with `readOnly: true` from the native layer and is
* re-asserted here, so a surface can label it without inferring anything
* from timestamps.
*
* Outside the desktop shell every call is a no-op that resolves to `null` or
* `false` — the browser and mobile builds have no keychain to derive from, so
* the honest answer is "no cache" rather than an unencrypted fallback.
*
* This sits underneath the in-memory tier in `conversation-cache.ts`: that one
* removes the skeleton flash between thread switches and dies with the window,
* this one survives a restart with the daemon down.
*/
import { subscribeChatAccessInvalidation } from "./chat-access-invalidation.ts";
import { isTauri } from "./tauri-platform.ts";
/** Mirrors `OFFLINE_CACHE_SCHEMA_VERSION` in `offline_cache.rs`. */
export const OFFLINE_CACHE_SCHEMA_VERSION = 2;
/** Mirrors `MAX_ENTRY_BYTES` in `offline_cache.rs`. */
export const OFFLINE_CACHE_MAX_ENTRY_BYTES = 1024 * 1024;
/** Mirrors `MAX_NAME_LEN` in `offline_cache.rs`. */
const MAX_NAME_LENGTH = 128;
/** Mirrors `MAX_REVISION_LEN` in `offline_cache.rs`. */
const MAX_REVISION_LENGTH = 256;
/**
* Cache namespaces. A scope is cleared as a unit and is part of the key
* derivation, so adding one is a deliberate act rather than a free-form
* string at a call site.
*/
export type OfflineCacheScope = "conversation";
/** Mirrors `OfflineCacheFaultKind` in `offline_cache.rs`. */
export type OfflineCacheFaultKind =
| "truncated"
| "magic_mismatch"
| "header_malformed"
| "schema_mismatch"
| "instance_mismatch"
| "entry_mismatch"
| "length_mismatch"
| "undecryptable"
| "oversized"
| "payload_malformed"
| "io";
export type OfflineCacheFault = {
kind: OfflineCacheFaultKind;
detail: string;
};
type NativeOfflineCacheEntry = {
payload: string;
revision: string;
updatedAtUnixMs: number;
readOnly: boolean;
};
type NativeOfflineCacheReadResult = {
entry?: NativeOfflineCacheEntry;
fault?: OfflineCacheFault;
purged: boolean;
};
/**
* Occupancy and the recent classified faults. Mirrors `OfflineCacheStatus` in
* `offline_cache.rs`, which deliberately withholds the instance id: it is a
* stable per-install identifier and a diagnostic needs neither to say how full
* the cache is nor what has gone wrong in it.
*/
export type OfflineCacheStatus = {
schemaVersion: number;
entries: number;
bytes: number;
maxEntries: number;
maxEntryBytes: number;
maxTotalBytes: number;
faults: OfflineCacheFault[];
};
/**
* A cache hit. `readOnly` is always `true` and is present so a surface can
* say so out loud; nothing here can be written back through.
*/
export type OfflineCacheRead<T> = {
data: T;
revision: string;
updatedAtUnixMs: number;
readOnly: true;
};
export type OfflineCacheSanitizeResult = {
value: unknown;
/** Dot-separated paths that were removed. Key names only, never values. */
dropped: string[];
};
type Invoke = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
export type OfflineCacheDependencies = {
invoke?: Invoke;
supported?: () => boolean;
/**
* Where a write reports what it could not do: a native call that failed,
* and the fields the sanitizer removed. Both are otherwise silent — the
* write still resolves — so a caller that wants to know has to ask.
*/
warn?: (message: string) => void;
};
// Native writes and purges must finish in issue order. A purge also advances
// the read epoch synchronously, before loading the IPC bridge or waiting for
// an older write. Failed purges remain unreadable in this window until a fresh
// authorized write succeeds; they must not silently restore an offline copy.
let mutationTail: Promise<unknown> = Promise.resolve();
let cacheGeneration = 0;
const entryGenerations = new Map<string, number>();
const blockedEntries = new Set<string>();
let scopeBlocked = false;
const admittedEntries = new Set<string>();
function entryIdentity(scope: OfflineCacheScope, key: string): string {
return `${scope}:${key}`;
}
function cacheEpoch(identity: string): string {
return `${cacheGeneration}:${entryGenerations.get(identity) ?? 0}`;
}
function entryBlocked(identity: string): boolean {
return blockedEntries.has(identity) || (scopeBlocked && !admittedEntries.has(identity));
}
function mutateCache<T>(operation: () => Promise<T>): Promise<T> {
const pending = mutationTail.then(operation);
mutationTail = pending.catch(() => undefined);
return pending;
}
/**
* Key names that must never reach disk. Matched against the key with
* separators stripped, so `api_key`, `apiKey`, and `API-KEY` are one rule.
*/
const SECRET_KEY_PATTERN =
/^(token|accesstoken|refreshtoken|idtoken|bearertoken|apikey|apisecret|secret|clientsecret|password|passphrase|credential|credentials|authorization|authheader|cookie|setcookie|sessionkey|sessiontoken|privatekey|signingkey|signature|jwt|otp|pin)$/;
/**
* Key names whose values are file bytes rather than text. A conversation
* payload legitimately has `content`, so the byte-ish names are listed
* explicitly instead of guessing from the value alone.
*/
const ATTACHMENT_KEY_PATTERN =
/^(bytes|base64|blob|buffer|binary|filedata|rawdata|arraybuffer|dataurl|datauri|thumbnail|preview|imagedata)$/;
/** Anything at or beyond this length is a payload, not a caption. */
const MAX_INLINE_STRING_LENGTH = 8 * 1024;
const utf8 = new TextEncoder();
/**
* Every bound the native side enforces is a UTF-8 byte count (`str::len` in
* Rust); `String.length` is UTF-16 code units, which is smaller for anything
* outside Latin-1 and three times smaller for CJK. Measuring in the wrong
* unit does not make the cache accept oversized data — the native side
* refuses it — but it makes this module's own checks wrong in the permissive
* direction, so an over-budget write is discovered by a failed IPC round trip
* instead of here.
*/
function utf8Length(value: string): number {
return utf8.encode(value).length;
}
function normalizeKey(key: string): string {
return key.replace(/[-_.\s]/g, "").toLowerCase();
}
function looksLikeEmbeddedBytes(value: string): boolean {
if (/^data:[^,]*;base64,/i.test(value)) return true;
if (value.length < MAX_INLINE_STRING_LENGTH) return false;
// A long run of pure base64 alphabet is bytes someone stringified; prose,
// markdown, and JSON all contain characters outside it well before this
// length.
return /^[A-Za-z0-9+/=\r\n]+$/.test(value);
}
function joinPath(path: string, key: string): string {
return path ? `${path}.${key}` : key;
}
function sanitizeValue(value: unknown, path: string, dropped: string[]): unknown {
if (value === null) return null;
if (Array.isArray(value)) {
return value.map((item, index) => sanitizeValue(item, joinPath(path, String(index)), dropped));
}
if (typeof value === "string") {
if (looksLikeEmbeddedBytes(value)) {
dropped.push(path);
return undefined;
}
return value;
}
if (typeof value === "number" || typeof value === "boolean") return value;
if (typeof value === "object") {
// Typed arrays, Blobs, Dates, class instances: nothing structured enough
// to reason about, so nothing that belongs in a durable cache.
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
dropped.push(path);
return undefined;
}
const out: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
if (key === "__proto__" || key === "constructor" || key === "prototype") {
dropped.push(joinPath(path, key));
continue;
}
const normalized = normalizeKey(key);
if (SECRET_KEY_PATTERN.test(normalized) || ATTACHMENT_KEY_PATTERN.test(normalized)) {
dropped.push(joinPath(path, key));
continue;
}
const sanitized = sanitizeValue(child, joinPath(path, key), dropped);
if (sanitized !== undefined) out[key] = sanitized;
}
return out;
}
// undefined, functions, symbols, bigint: not JSON, so not cacheable.
if (value !== undefined) dropped.push(path);
return undefined;
}
/**
* Strip everything that must not be persisted, and report what went. The
* result is plain JSON data: no class instances, no typed arrays, no
* credential-shaped keys, and no embedded file bytes.
*/
export function sanitizeForOfflineCache(value: unknown): OfflineCacheSanitizeResult {
const dropped: string[] = [];
return { value: sanitizeValue(value, "", dropped), dropped };
}
function isValidName(value: string): boolean {
return (
value.length > 0 &&
utf8Length(value) <= MAX_NAME_LENGTH &&
// The native layer rejects Unicode controls; validate here to avoid a round-trip rejection.
!/\p{Cc}/u.test(value)
);
}
function defaultSupported(): boolean {
return isTauri();
}
async function resolveInvoke(dependencies: OfflineCacheDependencies): Promise<Invoke | null> {
if (dependencies.invoke) return dependencies.invoke;
if (typeof window === "undefined") return null;
try {
const { invoke } = await import("@tauri-apps/api/core");
return invoke as Invoke;
} catch {
return null;
}
}
/** True when a durable offline cache exists at all. */
export function isOfflineCacheSupported(dependencies: OfflineCacheDependencies = {}): boolean {
return (dependencies.supported ?? defaultSupported)();
}
function isReadResult(value: unknown): value is NativeOfflineCacheReadResult {
return typeof value === "object" && value !== null && "purged" in value;
}
/**
* Read a cached payload. Returns `null` for a miss, for an unsupported
* platform, and for a purged entry — all three mean "nothing to show" and
* none of them is an error the caller should surface.
*/
export async function readOfflineCache<T = unknown>(
scope: OfflineCacheScope,
key: string,
dependencies: OfflineCacheDependencies = {},
): Promise<OfflineCacheRead<T> | null> {
if (!isOfflineCacheSupported(dependencies) || !isValidName(key)) return null;
const identity = entryIdentity(scope, key);
const epoch = cacheEpoch(identity);
if (entryBlocked(identity)) return null;
await mutationTail;
const invoke = await resolveInvoke(dependencies);
if (!invoke || epoch !== cacheEpoch(identity) || entryBlocked(identity)) return null;
try {
const result = await invoke("offline_cache_read", { scope, key });
if (epoch !== cacheEpoch(identity) || entryBlocked(identity)) return null;
if (!isReadResult(result) || !result.entry) return null;
const { payload, revision, updatedAtUnixMs, readOnly } = result.entry;
if (readOnly !== true) return null;
return {
data: JSON.parse(payload) as T,
revision,
updatedAtUnixMs,
readOnly: true,
};
} catch {
// A cache read never fails a surface: the daemon path is the source of
// truth and a miss is always a legitimate answer.
return null;
}
}
/**
* Persist a payload for offline reading. Returns whether anything was stored:
* an unsupported platform, an unsanitizable value, and an over-budget payload
* are all `false` rather than throws, because none of them should interrupt
* the live path that produced the data.
*/
export async function writeOfflineCache(
scope: OfflineCacheScope,
key: string,
value: unknown,
revision: string,
dependencies: OfflineCacheDependencies = {},
): Promise<boolean> {
if (!isOfflineCacheSupported(dependencies) || !isValidName(key)) return false;
if (utf8Length(revision) > MAX_REVISION_LENGTH) return false;
const { value: sanitized, dropped } = sanitizeForOfflineCache(value);
if (sanitized === undefined) return false;
if (dropped.length > 0) {
// The sanitizer's rules are conservative on purpose, and two of them are
// heuristics: `looksLikeEmbeddedBytes` will drop any string of 8 KiB or
// more that happens to be entirely base64 alphabet. Without this the
// removal is invisible — the write still returns `true`, and the cached
// copy is quietly not what the caller passed. Paths are key names from
// the caller's own object graph and carry no values.
dependencies.warn?.(
`[cave] offline cache dropped ${dropped.length} field(s) before storing: ${dropped.join(", ")}`,
);
}
let payload: string;
try {
payload = JSON.stringify(sanitized);
} catch {
return false;
}
if (typeof payload !== "string" || utf8Length(payload) > OFFLINE_CACHE_MAX_ENTRY_BYTES) {
return false;
}
const identity = entryIdentity(scope, key);
const epoch = cacheEpoch(identity);
return mutateCache(async () => {
const invoke = await resolveInvoke(dependencies);
if (!invoke || epoch !== cacheEpoch(identity)) return false;
try {
await invoke("offline_cache_write", { scope, key, payload, revision });
if (epoch !== cacheEpoch(identity)) return false;
blockedEntries.delete(identity);
admittedEntries.add(identity);
return true;
} catch {
dependencies.warn?.("[cave] offline cache write is unavailable");
return false;
}
});
}
/** Drop one entry, e.g. a deleted chat's transcript (#5583). Absent is fine. */
export async function deleteOfflineCacheEntry(
scope: OfflineCacheScope,
key: string,
dependencies: OfflineCacheDependencies = {},
): Promise<boolean> {
if (!isOfflineCacheSupported(dependencies) || !isValidName(key)) return false;
const identity = entryIdentity(scope, key);
entryGenerations.set(identity, (entryGenerations.get(identity) ?? 0) + 1);
blockedEntries.add(identity);
admittedEntries.delete(identity);
return mutateCache(async () => {
const invoke = await resolveInvoke(dependencies);
if (!invoke) return false;
try {
await invoke("offline_cache_delete", { scope, key });
return true;
} catch {
return false;
}
});
}
/** Drop one scope, or the whole cache for this instance when scope is omitted. */
export async function clearOfflineCache(
scope?: OfflineCacheScope,
dependencies: OfflineCacheDependencies = {},
): Promise<boolean> {
if (!isOfflineCacheSupported(dependencies)) return false;
cacheGeneration += 1;
entryGenerations.clear();
blockedEntries.clear();
scopeBlocked = true;
admittedEntries.clear();
return mutateCache(async () => {
const invoke = await resolveInvoke(dependencies);
if (!invoke) return false;
try {
await invoke("offline_cache_clear", { scope: scope ?? null });
return true;
} catch {
return false;
}
});
}
/**
* Cache occupancy and the recent classified faults, for diagnostics. Returns
* `null` where there is no cache rather than a zeroed status, so a caller
* cannot mistake "unsupported" for "empty".
*/
export async function readOfflineCacheStatus(
dependencies: OfflineCacheDependencies = {},
): Promise<OfflineCacheStatus | null> {
if (!isOfflineCacheSupported(dependencies)) return null;
const invoke = await resolveInvoke(dependencies);
if (!invoke) return null;
try {
const status = await invoke("offline_cache_status");
if (typeof status !== "object" || status === null) return null;
return status as OfflineCacheStatus;
} catch {
return null;
}
}
subscribeChatAccessInvalidation((change) => {
if (change.sessionId === undefined) void clearOfflineCache("conversation");
else void deleteOfflineCacheEntry("conversation", change.sessionId);
});