@abraca/dabra 2.89.0 → 2.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +5 -11
  2. package/src/AbracadabraBaseProvider.ts +0 -963
  3. package/src/AbracadabraClient.ts +0 -1960
  4. package/src/AbracadabraProvider.ts +0 -915
  5. package/src/AbracadabraWS.ts +0 -695
  6. package/src/BackgroundSyncManager.ts +0 -856
  7. package/src/BackgroundSyncPersistence.ts +0 -140
  8. package/src/ChatClient.ts +0 -314
  9. package/src/CloseEvents.ts +0 -49
  10. package/src/ContentManager.ts +0 -246
  11. package/src/CoverReconcile.ts +0 -168
  12. package/src/CryptoIdentityKeystore.ts +0 -754
  13. package/src/DeviceRegistrationService.ts +0 -257
  14. package/src/DocConverters.ts +0 -1859
  15. package/src/DocKeyManager.ts +0 -163
  16. package/src/DocTypes.ts +0 -628
  17. package/src/DocUtils.ts +0 -251
  18. package/src/DocumentCache.ts +0 -210
  19. package/src/DocumentManager.ts +0 -410
  20. package/src/E2EAbracadabraProvider.ts +0 -426
  21. package/src/E2EOfflineStore.ts +0 -55
  22. package/src/EncryptedChatClient.ts +0 -173
  23. package/src/EncryptedY.ts +0 -145
  24. package/src/EventEmitter.ts +0 -59
  25. package/src/FileBlobStore.ts +0 -569
  26. package/src/IdentityDoc.ts +0 -711
  27. package/src/IncomingMessage.ts +0 -63
  28. package/src/MessageReceiver.ts +0 -151
  29. package/src/MessageSender.ts +0 -22
  30. package/src/MetaManager.ts +0 -194
  31. package/src/MnemonicKeyDerivation.ts +0 -171
  32. package/src/NodeConnect.ts +0 -63
  33. package/src/NodeIdentity.ts +0 -378
  34. package/src/NotificationsClient.ts +0 -207
  35. package/src/OfflineStore.ts +0 -294
  36. package/src/OutgoingMessage.ts +0 -25
  37. package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
  38. package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
  39. package/src/OutgoingMessages/CloseMessage.ts +0 -17
  40. package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
  41. package/src/OutgoingMessages/StatelessMessage.ts +0 -18
  42. package/src/OutgoingMessages/SubdocMessage.ts +0 -35
  43. package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
  44. package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
  45. package/src/OutgoingMessages/UpdateMessage.ts +0 -20
  46. package/src/QueryClient.ts +0 -209
  47. package/src/RpcClient.ts +0 -659
  48. package/src/SchemaTypes.ts +0 -179
  49. package/src/SearchIndex.ts +0 -250
  50. package/src/ServerRegistry.ts +0 -220
  51. package/src/ServerReset.ts +0 -222
  52. package/src/TokenManager.ts +0 -337
  53. package/src/TreeManager.ts +0 -894
  54. package/src/TreeTimestamps.ts +0 -101
  55. package/src/auth.ts +0 -62
  56. package/src/awarenessStatesToArray.ts +0 -10
  57. package/src/index.ts +0 -219
  58. package/src/messageRecord.ts +0 -121
  59. package/src/sync/BroadcastChannelSync.ts +0 -235
  60. package/src/types.ts +0 -790
  61. package/src/webrtc/AbracadabraWebRTC.ts +0 -683
  62. package/src/webrtc/DataChannelRouter.ts +0 -179
  63. package/src/webrtc/DevicePairingChannel.ts +0 -496
  64. package/src/webrtc/E2EEChannel.ts +0 -195
  65. package/src/webrtc/FileTransferChannel.ts +0 -367
  66. package/src/webrtc/ManualSignaling.ts +0 -204
  67. package/src/webrtc/PeerConnection.ts +0 -133
  68. package/src/webrtc/SignalingSocket.ts +0 -378
  69. package/src/webrtc/YjsDataChannel.ts +0 -203
  70. package/src/webrtc/index.ts +0 -26
  71. package/src/webrtc/types.ts +0 -177
@@ -1,1960 +0,0 @@
1
- import type {
2
- UserProfile,
3
- DocumentMeta,
4
- UploadMeta,
5
- UploadInfo,
6
- ThumbnailOptions,
7
- StreamTokenInfo,
8
- PublicKeyInfo,
9
- PermissionEntry,
10
- EffectivePermissionsResponse,
11
- HealthStatus,
12
- ReadyzStatus,
13
- ServerInfo,
14
- InviteRow,
15
- SnapshotMeta,
16
- SnapshotData,
17
- SnapshotCreateResult,
18
- SnapshotRestoreResult,
19
- SnapshotForkResult,
20
- DocBacklink,
21
- DocSearchHit,
22
- AuditLogEntry,
23
- AuditQueryOpts,
24
- AuditVerifyResult,
25
- AdminConfigField,
26
- EnvSnapshotResponse,
27
- } from "./types.ts";
28
- import { Kind, SERVER_ROOT_ID } from "./types.ts";
29
- import type { DocEncryptionInfo } from "./types.ts";
30
- import type { DocumentCache } from "./DocumentCache.ts";
31
- import type { ServerResetOutcome } from "./ServerReset.ts";
32
- import { dropCachesIfServerReplaced } from "./ServerReset.ts";
33
- import { deriveDmDocId } from "./IdentityDoc.ts";
34
-
35
- function fromBase64(b64: string): Uint8Array {
36
- return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
37
- }
38
-
39
- /**
40
- * Decode a base64url-encoded string (e.g. a JWT header/payload segment) to
41
- * UTF-8 text. `atob` only accepts standard base64, so we translate the
42
- * url-safe alphabet (`-`/`_`) and re-pad before decoding — otherwise a
43
- * perfectly valid token whose payload happens to contain `-` or `_` throws
44
- * and gets misclassified as invalid/expired.
45
- */
46
- function decodeBase64UrlToString(b64url: string): string {
47
- let b64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
48
- const pad = b64.length % 4;
49
- if (pad) b64 += "=".repeat(4 - pad);
50
- const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
51
- return new TextDecoder().decode(bytes);
52
- }
53
-
54
- /**
55
- * Reason classifications surfaced to `onAuthFailed`. Consumers can decide
56
- * whether to silently re-register the keypair (`user_not_found`) or
57
- * surface a hard block (`account_revoked`, `forbidden`).
58
- */
59
- export type AuthFailureReason =
60
- | "user_not_found"
61
- | "account_revoked"
62
- | "forbidden"
63
- | "unauthorized";
64
-
65
- export interface AuthFailureContext {
66
- /** HTTP status code from the failed request. */
67
- status: number;
68
- /** Server-provided error message verbatim. */
69
- message: string;
70
- /** Best-guess classification from the message text. */
71
- reason: AuthFailureReason;
72
- /** Method + path of the failed request, useful for debugging. */
73
- method: string;
74
- path: string;
75
- }
76
-
77
- export interface AbracadabraClientConfig {
78
- /** Server base URL (http or https). WebSocket URL is derived automatically. */
79
- url: string;
80
- /** Initial JWT token. If omitted and persistAuth is true, loads from storage. */
81
- token?: string;
82
- /** Persist JWT to localStorage for stay-logged-in. Default: true in browser. */
83
- persistAuth?: boolean;
84
- /** localStorage key for token persistence. Default: "abracadabra:auth". */
85
- storageKey?: string;
86
- /** Custom fetch implementation (useful for Node.js or testing). */
87
- fetch?: typeof globalThis.fetch;
88
- /**
89
- * Optional metadata cache. When provided, read methods (getDoc, listChildren,
90
- * getMe, listPermissions, listUploads) check the cache before hitting the
91
- * network. Write methods (deleteDoc, upload, deleteUpload) invalidate affected
92
- * cache entries automatically.
93
- */
94
- cache?: DocumentCache;
95
- /**
96
- * Called whenever a REST call returns 401/403 with a recoverable reason
97
- * (typically "user not found" — server's DB was wiped or repointed).
98
- * Consumers wire this to their reauth path (in cou-sh: `_reauthFn`)
99
- * so silently-failing background fetches still trigger key re-registration
100
- * without waiting for the next WS action to surface the problem.
101
- *
102
- * The callback runs OUT-OF-BAND of the failing request — the original
103
- * Promise still rejects so callers handle their own error path.
104
- * Long-running auth handlers should debounce or short-circuit duplicate
105
- * concurrent invocations.
106
- */
107
- onAuthFailed?: (ctx: AuthFailureContext) => void;
108
- }
109
-
110
- export class AbracadabraClient {
111
- private _token: string | null;
112
- private readonly baseUrl: string;
113
- private readonly persistAuth: boolean;
114
- private readonly storageKey: string;
115
- private readonly _fetch: typeof globalThis.fetch;
116
- readonly cache: DocumentCache | null;
117
- private readonly _onAuthFailed: ((ctx: AuthFailureContext) => void) | null;
118
- /** Single-flight for root listings (`/docs?root=true`) — the per-row
119
- * permission cascade makes this a multi-second / hundreds-of-KB call on
120
- * a busy server, and a connect burst fires several identical ones.
121
- * Keyed by the kind filter; cleared when the request settles. */
122
- private readonly rootListInflight = new Map<
123
- string,
124
- Promise<DocumentMeta[]>
125
- >();
126
- /** Cached media-stream grants (`getStreamUrl`), keyed `docId/uploadId`.
127
- * Re-minted just before expiry and dropped whenever the session token
128
- * changes — a stream token inherits the identity that minted it. */
129
- private readonly streamTokens = new Map<
130
- string,
131
- { url: string; expiresAt: number }
132
- >();
133
- /** In-flight mints, keyed like `streamTokens` — collapses the burst a page
134
- * of media blocks produces into one request per upload. */
135
- private readonly streamTokenInflight = new Map<string, Promise<string>>();
136
-
137
- constructor(config: AbracadabraClientConfig) {
138
- this.baseUrl = config.url.replace(/\/+$/, "");
139
- this.persistAuth = config.persistAuth ?? typeof localStorage !== "undefined";
140
- this.storageKey = config.storageKey ?? "abracadabra:auth";
141
- this._fetch = config.fetch ?? globalThis.fetch.bind(globalThis);
142
- this.cache = config.cache ?? null;
143
- this._onAuthFailed = config.onAuthFailed ?? null;
144
-
145
- // Load token: explicit > persisted > null
146
- this._token = config.token ?? this.loadPersistedToken() ?? null;
147
- }
148
-
149
- // ── Token management ─────────────────────────────────────────────────────
150
-
151
- get token(): string | null {
152
- return this._token;
153
- }
154
-
155
- set token(value: string | null) {
156
- this._token = value;
157
- // Stream grants carry the old identity (and die with it on
158
- // logout-all) — never serve one across a session change.
159
- this.streamTokens.clear();
160
- this.streamTokenInflight.clear();
161
- if (this.persistAuth) {
162
- if (value) {
163
- this.persistToken(value);
164
- } else {
165
- this.clearPersistedToken();
166
- }
167
- }
168
- }
169
-
170
- get isAuthenticated(): boolean {
171
- return this._token !== null;
172
- }
173
-
174
- /** Check if the current JWT token is present and not expired. */
175
- isTokenValid(): boolean {
176
- if (!this._token) return false;
177
- try {
178
- const [, payload] = this._token.split(".");
179
- // JWT payloads are base64url — `atob` only handles standard base64,
180
- // so a payload containing `-` or `_` would throw and a valid token
181
- // would be misread as expired, forcing a spurious re-auth.
182
- const { exp } = JSON.parse(decodeBase64UrlToString(payload));
183
- return typeof exp === "number" && exp * 1000 > Date.now();
184
- } catch {
185
- return false;
186
- }
187
- }
188
-
189
- /** Derives ws:// or wss:// URL from the http(s) base URL. */
190
- get wsUrl(): string {
191
- return this.baseUrl
192
- .replace(/^https:\/\//, "wss://")
193
- .replace(/^http:\/\//, "ws://") + "/ws";
194
- }
195
-
196
- // ── Auth ─────────────────────────────────────────────────────────────────
197
-
198
- /** Register a new user with password. */
199
- async register(opts: {
200
- username: string;
201
- password: string;
202
- email?: string;
203
- displayName?: string;
204
- inviteCode?: string;
205
- }): Promise<UserProfile> {
206
- return this.request<UserProfile>("POST", "/auth/register", {
207
- body: opts,
208
- auth: false,
209
- });
210
- }
211
-
212
- /**
213
- * Register a new user with an Ed25519 public key (crypto auth).
214
- * Username is optional — if omitted, a short identifier is derived from the key.
215
- */
216
- async registerWithKey(opts: {
217
- publicKey: string;
218
- username?: string;
219
- deviceName?: string;
220
- displayName?: string;
221
- email?: string;
222
- inviteCode?: string;
223
- /** X25519 encryption public key paired with the Ed25519 identity key. Required for E2E channels. */
224
- x25519Key?: string;
225
- }): Promise<UserProfile> {
226
- const username = opts.username ?? `user-${opts.publicKey.slice(0, 8)}`;
227
- return this.request<UserProfile>("POST", "/auth/register", {
228
- body: {
229
- username,
230
- identityPublicKey: opts.publicKey,
231
- deviceName: opts.deviceName,
232
- displayName: opts.displayName,
233
- email: opts.email,
234
- inviteCode: opts.inviteCode,
235
- x25519Key: opts.x25519Key,
236
- },
237
- auth: false,
238
- });
239
- }
240
-
241
- /** Login with username + password. Auto-persists returned token. */
242
- async login(opts: { username: string; password: string }): Promise<string> {
243
- const res = await this.request<{ token: string }>("POST", "/auth/login", {
244
- body: opts,
245
- auth: false,
246
- });
247
- this.token = res.token;
248
- return res.token;
249
- }
250
-
251
- /** Request an Ed25519 crypto auth challenge for the given public key. */
252
- async challenge(publicKey: string): Promise<{ challenge: string; expiresAt: number }> {
253
- return this.request("POST", "/auth/challenge", {
254
- body: { publicKey },
255
- auth: false,
256
- });
257
- }
258
-
259
- /** Verify an Ed25519 signature to complete crypto auth. Auto-persists token. */
260
- async verify(opts: {
261
- publicKey: string;
262
- signature: string;
263
- challenge: string;
264
- }): Promise<string> {
265
- const res = await this.request<{ token: string }>("POST", "/auth/verify", {
266
- body: opts,
267
- auth: false,
268
- });
269
- this.token = res.token;
270
- return res.token;
271
- }
272
-
273
- /**
274
- * Full crypto auth flow: challenge → sign → verify.
275
- * Convenience method combining challenge() + external signing + verify().
276
- */
277
- async loginWithKey(
278
- publicKey: string,
279
- signChallenge: (challenge: string) => Promise<string>,
280
- ): Promise<string> {
281
- const { challenge } = await this.challenge(publicKey);
282
- const signature = await signChallenge(challenge);
283
- return this.verify({ publicKey, signature, challenge });
284
- }
285
-
286
- /** Add a new Ed25519 public key to the current user (multi-device). */
287
- async addKey(opts: { publicKey: string; deviceName?: string; x25519Key?: string }): Promise<void> {
288
- await this.request("POST", "/auth/keys", { body: { publicKey: opts.publicKey, deviceName: opts.deviceName, x25519Key: opts.x25519Key } });
289
- }
290
-
291
- /** List all registered public keys for the current user. */
292
- async listKeys(): Promise<PublicKeyInfo[]> {
293
- const res = await this.request<{ keys: PublicKeyInfo[] }>("GET", "/auth/keys");
294
- return res.keys;
295
- }
296
-
297
- /** Rename a registered device key. */
298
- async renameKey(keyId: string, deviceName: string): Promise<void> {
299
- await this.request("PATCH", `/auth/keys/${encodeURIComponent(keyId)}`, { body: { deviceName } });
300
- }
301
-
302
- /**
303
- * Revoke a public key by its ID. The server treats this as a panic
304
- * action: every outstanding JWT for the account is invalidated (a stolen
305
- * device's token must die immediately, and tokens carry no per-key
306
- * claim), and a fresh token for THIS session is returned and adopted
307
- * automatically — so the device performing the revocation stays
308
- * authenticated while every other device silently re-auths.
309
- */
310
- async revokeKey(keyId: string): Promise<void> {
311
- const res = await this.request<{ token?: string } | null>(
312
- "DELETE",
313
- `/auth/keys/${encodeURIComponent(keyId)}`,
314
- );
315
- // Older servers respond 204 with no body — keep working against them.
316
- if (res && typeof res === "object" && typeof res.token === "string") {
317
- this.token = res.token;
318
- }
319
- }
320
-
321
- // ── Device Invites ───────────────────────────────────────────────────────
322
-
323
- /** Create a single-use device invite code for pairing a new device to this account. */
324
- async createDeviceInvite(opts?: { expiresIn?: number }): Promise<{ code: string; expiresAt: number }> {
325
- return this.request<{ code: string; expiresAt: number }>("POST", "/auth/device-invite", {
326
- body: opts?.expiresIn != null ? { expiresIn: opts.expiresIn } : {},
327
- });
328
- }
329
-
330
- /** Redeem a device invite code to register a new device key. Returns a JWT token. */
331
- async redeemDeviceInvite(opts: {
332
- code: string;
333
- publicKey: string;
334
- x25519Key?: string;
335
- deviceName?: string;
336
- }): Promise<{ token: string; user: { id: string; username: string; publicKey: string } }> {
337
- return this.request("POST", "/auth/device-redeem", {
338
- body: { code: opts.code, publicKey: opts.publicKey, x25519Key: opts.x25519Key, deviceName: opts.deviceName },
339
- auth: false,
340
- });
341
- }
342
-
343
- // ── Device Sessions ────────────────────────────────────────────────────
344
-
345
- /** Request a device session token after successful crypto auth. Requires valid JWT. */
346
- async requestDeviceSession(opts: {
347
- publicKey: string;
348
- deviceName?: string;
349
- }): Promise<{ sessionId: string; sessionToken: string; expiresAt: number }> {
350
- return this.request("POST", "/auth/device-session", {
351
- body: { publicKey: opts.publicKey, deviceName: opts.deviceName },
352
- });
353
- }
354
-
355
- /** Exchange a device session token for a fresh JWT. No biometric/passkey needed. */
356
- async refreshWithDeviceSession(sessionToken: string): Promise<string> {
357
- const res = await this.request<{ token: string }>("POST", "/auth/refresh", {
358
- body: { sessionToken },
359
- auth: false,
360
- });
361
- this.token = res.token;
362
- return res.token;
363
- }
364
-
365
- /** List active device sessions for the authenticated user. */
366
- async listDeviceSessions(): Promise<
367
- Array<{ id: string; keyId: string; deviceName?: string; issuedAt: number; expiresAt: number; lastUsedAt?: number }>
368
- > {
369
- const res = await this.request<{
370
- sessions: Array<{ id: string; keyId: string; deviceName?: string; issuedAt: number; expiresAt: number; lastUsedAt?: number }>;
371
- }>("GET", "/auth/device-session");
372
- return res.sessions;
373
- }
374
-
375
- /** Revoke a device session by ID. */
376
- async revokeDeviceSession(sessionId: string): Promise<void> {
377
- await this.request("DELETE", `/auth/device-session/${encodeURIComponent(sessionId)}`);
378
- }
379
-
380
- // ── Pairing ─────────────────────────────────────────────────────────────
381
-
382
- /**
383
- * Fetch a short-lived anonymous pairing token for WebRTC signaling.
384
- * No authentication required. The token only grants access to `__pairing_*` rooms.
385
- */
386
- static async getPairingToken(serverUrl: string): Promise<string> {
387
- let base = serverUrl;
388
- while (base.endsWith("/")) base = base.slice(0, -1);
389
- const resp = await fetch(`${base}/auth/pairing-token`, { method: "POST" });
390
- if (!resp.ok) {
391
- throw new Error(`Failed to fetch pairing token: ${resp.status}`);
392
- }
393
- const { token } = (await resp.json()) as { token: string };
394
- return token;
395
- }
396
-
397
- // ── Encryption ───────────────────────────────────────────────────────────
398
-
399
- /** Get encryption info for a document. */
400
- async getDocEncryption(docId: string): Promise<DocEncryptionInfo> {
401
- return this.request<DocEncryptionInfo>("GET", `/docs/${encodeURIComponent(docId)}/encryption`);
402
- }
403
-
404
- /** Set the encryption mode for a document (no downgrade). */
405
- async setDocEncryption(docId: string, mode: "none" | "cse" | "e2e"): Promise<void> {
406
- await this.request("PATCH", `/docs/${encodeURIComponent(docId)}/encryption`, { body: { mode } });
407
- }
408
-
409
- /** Get the caller's key envelope for a document (for decrypting the DocKey). */
410
- async getMyKeyEnvelope(docId: string): Promise<{ encrypted_key: string; key_epoch: number } | null> {
411
- return this.requestOrNull<{ encrypted_key: string; key_epoch: number }>(
412
- "GET",
413
- `/docs/${encodeURIComponent(docId)}/key-envelope`,
414
- );
415
- }
416
-
417
- /** Upload key envelopes for a document (Owner only). */
418
- async uploadKeyEnvelopes(
419
- docId: string,
420
- opts: { key_epoch: number; envelopes: { recipient_key_id: string; encrypted_key: string }[] },
421
- ): Promise<void> {
422
- await this.request("POST", `/docs/${encodeURIComponent(docId)}/key-envelopes`, { body: opts });
423
- }
424
-
425
- /** Get the X25519 public key for a user. */
426
- async getUserX25519Key(userId: string): Promise<string | null> {
427
- const res = await this.requestOrNull<{ x25519_key: string }>(
428
- "GET",
429
- `/users/${encodeURIComponent(userId)}/x25519-key`,
430
- );
431
- return res?.x25519_key ?? null;
432
- }
433
-
434
- /** List all non-revoked keys for a user (Owner/Admin or self). */
435
- async listUserKeys(userId: string): Promise<{ id: string; publicKey: string; x25519Key: string | null }[]> {
436
- const res = await this.request<{ keys: { id: string; publicKey: string; x25519Key: string | null }[] }>(
437
- "GET",
438
- `/users/${encodeURIComponent(userId)}/keys`,
439
- );
440
- return res.keys;
441
- }
442
-
443
- /** Fetch encrypted E2E update blobs since a given sequence number. */
444
- async getE2EUpdatesSince(docId: string, sinceSeq: number): Promise<{ seq: number; data: Uint8Array }[]> {
445
- const res = await this.request<{ updates: { seq: number; data: string }[] }>(
446
- "GET",
447
- `/docs/${encodeURIComponent(docId)}/e2e-updates?since_seq=${sinceSeq}`,
448
- );
449
- return res.updates.map((u) => ({
450
- seq: u.seq,
451
- data: fromBase64(u.data),
452
- }));
453
- }
454
-
455
- /**
456
- * Clear token from memory and storage. Local-only; does NOT notify the
457
- * server. Use {@link logoutServer} or {@link logoutAll} when you also
458
- * want the JWT to land in the server's revocation cache.
459
- */
460
- logout(): void {
461
- this.token = null;
462
- }
463
-
464
- /**
465
- * Revoke the current JWT server-side and clear local state. Adds the
466
- * token's `jti` to the server's revocation cache so subsequent requests
467
- * with this token return 401, even if the JWT signature still verifies
468
- * and `exp` hasn't passed. Safe to call when no token is set — degrades
469
- * to a local clear.
470
- *
471
- * Network errors are swallowed (the local state is always cleared) so
472
- * a sign-out flow can't get stuck on a flaky connection. The endpoint
473
- * itself is idempotent.
474
- */
475
- async logoutServer(): Promise<void> {
476
- if (this._token) {
477
- try {
478
- await this.request("POST", "/auth/logout");
479
- } catch {
480
- // best-effort — local clear must always happen
481
- }
482
- }
483
- this.token = null;
484
- }
485
-
486
- /**
487
- * Bump the user's `tokens_invalid_before` watermark, revoking every
488
- * outstanding JWT for this user — every device, every browser, every
489
- * pending background tab. The current token is required (this is the
490
- * user's "I am who I say I am" assertion). After the call returns,
491
- * future authenticated requests with any pre-existing token return 401.
492
- */
493
- async logoutAll(): Promise<void> {
494
- await this.request("POST", "/auth/logout-all");
495
- this.token = null;
496
- }
497
-
498
- // ── Email verification ──────────────────────────────────────────────────
499
-
500
- /**
501
- * Request an email verification message be sent to the current user's
502
- * registered email address. Requires authentication. Server enforces a
503
- * per-user rate limit (1/min, 10/day). Returns 404 if email
504
- * verification is disabled in `[auth.email_verification]`.
505
- */
506
- async requestEmailVerification(): Promise<void> {
507
- await this.request("POST", "/auth/verify-email/request", { body: {} });
508
- }
509
-
510
- /**
511
- * Confirm an email verification token (typically opened from a link in
512
- * the verification email). On success the server sets
513
- * `users.email_verified_at`. No auth required — the token itself is
514
- * the proof.
515
- */
516
- async confirmEmailVerification(token: string): Promise<void> {
517
- await this.request("POST", "/auth/verify-email/confirm", {
518
- body: { token },
519
- auth: false,
520
- });
521
- }
522
-
523
- // ── Password lifecycle ──────────────────────────────────────────────────
524
-
525
- /**
526
- * Initiate a password reset for a user identified by username or
527
- * email. The server always returns 202 to avoid leaking whether the
528
- * identifier exists; a real reset email is only sent if the lookup
529
- * matched. Heavily rate-limited per-identifier and per-IP.
530
- */
531
- async requestPasswordReset(opts: { identifier: string }): Promise<void> {
532
- await this.request("POST", "/auth/password-reset/request", {
533
- body: opts,
534
- auth: false,
535
- });
536
- }
537
-
538
- /**
539
- * Complete a password reset using the token from the reset email.
540
- * On success the user's password is updated and every existing JWT for
541
- * the account is invalidated (the `tokens_invalid_before` watermark
542
- * bumps). The caller is NOT auto-logged-in — call {@link login} after.
543
- */
544
- async confirmPasswordReset(opts: { token: string; newPassword: string }): Promise<void> {
545
- await this.request("POST", "/auth/password-reset/confirm", {
546
- body: { token: opts.token, newPassword: opts.newPassword },
547
- auth: false,
548
- });
549
- }
550
-
551
- /**
552
- * Change the current user's password. Requires the current password —
553
- * a stolen JWT alone can't pivot to "I now own this account forever"
554
- * because the lockout counter (shared with `/auth/login`) trips after
555
- * a few wrong tries. The endpoint also bumps `tokens_invalid_before`,
556
- * so other sessions are forced to re-auth.
557
- */
558
- async changePassword(opts: { currentPassword: string; newPassword: string }): Promise<void> {
559
- await this.request("POST", "/auth/password-change", {
560
- body: { currentPassword: opts.currentPassword, newPassword: opts.newPassword },
561
- });
562
- }
563
-
564
- /**
565
- * Add a password to an account that doesn't have one yet — for example,
566
- * a key-based soft identity opting into a recovery credential. Requires
567
- * the caller to be authenticated. The server checks
568
- * `users.password_hash IS NULL` and returns 409 if a password is already
569
- * set — use {@link changePassword} in that case.
570
- *
571
- * Setting a password does not bump `tokens_invalid_before`: it adds an
572
- * orthogonal credential rather than rotating an existing one. Other
573
- * devices keep their sessions; this just unlocks the password-login
574
- * code path for future logins on new devices.
575
- */
576
- async setPassword(newPassword: string): Promise<void> {
577
- await this.request("POST", "/auth/set-password", {
578
- body: { newPassword },
579
- });
580
- }
581
-
582
- // ── User ─────────────────────────────────────────────────────────────────
583
-
584
- /** Get the current user's profile. */
585
- async getMe(): Promise<UserProfile> {
586
- if (this.cache) {
587
- const cached = await this.cache.getCurrentProfile();
588
- if (cached) return cached;
589
- }
590
- const profile = await this.request<UserProfile>("GET", "/users/me");
591
- if (this.cache) {
592
- await this.cache.setCurrentProfile(profile).catch(() => null);
593
- }
594
- return profile;
595
- }
596
-
597
- /** Update the current user's display name. */
598
- async updateMe(opts: { displayName?: string }): Promise<void> {
599
- await this.request("PATCH", "/users/me", { body: opts });
600
- }
601
-
602
- // ── Documents ────────────────────────────────────────────────────────────
603
-
604
- /**
605
- * Create a new root (top-level) document. Returns its metadata.
606
- *
607
- * Requires Admin-or-above unless the server sets
608
- * `[access].allow_user_top_level = true` — subtree docs go through
609
- * {@link createChild} instead and inherit creation rights from the parent.
610
- *
611
- * The options mirror the server's `CreateDocRequest`. They used to be typed
612
- * as just `{ id?: string }`, which is why `findOrCreateDmDoc` below reaches
613
- * past this method with a raw `request()` to set `kind` / `public_access`.
614
- */
615
- async createDoc(opts?: {
616
- id?: string;
617
- label?: string;
618
- description?: string;
619
- kind?: string;
620
- /** See {@link AbracadabraClient.setDocumentAccess} for what each value means. */
621
- public_access?: "none" | "private" | "observer" | "viewer" | "editor";
622
- }): Promise<DocumentMeta> {
623
- return this.request<DocumentMeta>("POST", "/docs", { body: opts ?? {} });
624
- }
625
-
626
- /** Get document metadata. */
627
- async getDoc(docId: string): Promise<DocumentMeta> {
628
- if (this.cache) {
629
- const cached = await this.cache.getDoc(docId);
630
- if (cached) return cached;
631
- }
632
- const meta = await this.request<DocumentMeta>("GET", `/docs/${encodeURIComponent(docId)}`);
633
- if (this.cache) {
634
- await this.cache.setDoc(meta).catch(() => null);
635
- }
636
- return meta;
637
- }
638
-
639
- /** Delete a document (requires Owner role). Cascades to children and uploads. */
640
- async deleteDoc(docId: string): Promise<void> {
641
- await this.request("DELETE", `/docs/${encodeURIComponent(docId)}`);
642
- if (this.cache) {
643
- await this.cache.invalidateDoc(docId).catch(() => null);
644
- }
645
- }
646
-
647
- /**
648
- * Restore a soft-deleted document (and its descendants). Requires the
649
- * same `manage` permission as {@link deleteDoc}, and works even when
650
- * the doc currently has `deleted_at` set — the cascade resolver walks
651
- * the ancestor chain regardless of soft-delete state. Returns the
652
- * number of restored rows in the audit log; the SDK call returns
653
- * `void` because the wire response is 204.
654
- */
655
- async restoreDoc(docId: string): Promise<void> {
656
- await this.request("POST", `/docs/${encodeURIComponent(docId)}/restore`);
657
- if (this.cache) {
658
- await this.cache.invalidateDoc(docId).catch(() => null);
659
- }
660
- }
661
-
662
- /**
663
- * Full-text search over document labels via `GET /docs/search`. The
664
- * server filters each candidate hit through the cascade resolver, so
665
- * results only include docs the caller can read at viewer or above.
666
- * Anonymous callers are permitted but only see public docs.
667
- *
668
- * `limit` is clamped to `[1, 50]` server-side; the default is 20.
669
- * Hits arrive in best-first order. `snippet` is HTML with `<mark>`
670
- * markers around matched tokens — sanitize before injecting.
671
- */
672
- async searchDocs(query: string, opts?: { limit?: number }): Promise<DocSearchHit[]> {
673
- const params = new URLSearchParams({ q: query });
674
- if (opts?.limit != null) params.set("limit", String(opts.limit));
675
- const res = await this.request<{ results: DocSearchHit[] }>(
676
- "GET",
677
- `/docs/search?${params.toString()}`,
678
- );
679
- return res.results;
680
- }
681
-
682
- /**
683
- * Documents that link TO `docId`, via `GET /docs/:id/backlinks`.
684
- *
685
- * Served from the server's `doc_links` index, which is rebuilt from each
686
- * document's CRDT state whenever a snapshot is written. Prefer this over
687
- * inverting links from a local cache: a client can only invert what it has
688
- * downloaded, so on a large space a purely local backlink list is silently
689
- * incomplete rather than empty-and-obviously-wrong.
690
- *
691
- * The caller must be able to read the target document, and each hit is
692
- * cascade-filtered, so this never reveals a document the caller couldn't
693
- * otherwise see. `limit` is clamped to `[1, 200]` server-side (default 50).
694
- *
695
- * Throws on servers that predate the endpoint — callers that need to work
696
- * against older deployments should catch and fall back to a local index.
697
- */
698
- async getBacklinks(
699
- docId: string,
700
- opts?: { limit?: number },
701
- ): Promise<DocBacklink[]> {
702
- const params = new URLSearchParams();
703
- if (opts?.limit != null) params.set("limit", String(opts.limit));
704
- const qs = params.toString();
705
- const res = await this.request<{ results: DocBacklink[] }>(
706
- "GET",
707
- `/docs/${encodeURIComponent(docId)}/backlinks${qs ? `?${qs}` : ""}`,
708
- );
709
- return res.results;
710
- }
711
-
712
- /**
713
- * Query for documents matching a structural predicate. v1 of the
714
- * indexed-query layer described in
715
- * `ARCHITECTURE/20-kickoff-phase3-queries.md`.
716
- *
717
- * The wire shape accepts a `where` field so v2 (meta-predicate
718
- * filtering on top of the `doc_meta_index` projection) can light up
719
- * without a compatibility break. Sending a non-empty `where` today
720
- * returns a 400 — callers should leave it absent.
721
- *
722
- * Returns docs the requester can read at viewer-or-above, filtered
723
- * through the cascading permission resolver server-side.
724
- */
725
- async queryDocs(opts: {
726
- type?: string;
727
- parentId?: string;
728
- labelContains?: string;
729
- limit?: number;
730
- }): Promise<DocumentMeta[]> {
731
- const body: Record<string, unknown> = {};
732
- if (opts.type != null) body.type = opts.type;
733
- if (opts.parentId != null) body.parent_id = opts.parentId;
734
- if (opts.labelContains != null) body.label_contains = opts.labelContains;
735
- if (opts.limit != null) body.limit = opts.limit;
736
- const res = await this.request<{ documents: DocumentMeta[]; v: number }>(
737
- "POST",
738
- "/docs/query",
739
- { body },
740
- );
741
- return res.documents;
742
- }
743
-
744
- /**
745
- * List the direct children of a document, returning full metadata. Pass
746
- * no argument to list the children of the server root — what the
747
- * dashboard renders as the Spaces sidebar.
748
- *
749
- * The cache (when configured) stores the bare `id[]` topology used by
750
- * recursive tree walks; callers that need it can read `meta.id` from
751
- * the returned metas.
752
- */
753
- async listChildren(
754
- parentId?: string,
755
- opts?: { kind?: string },
756
- ): Promise<DocumentMeta[]> {
757
- const kind = opts?.kind;
758
- if (parentId) {
759
- const res = await this.request<{
760
- documents: DocumentMeta[];
761
- children?: string[];
762
- }>("GET", `/docs/${encodeURIComponent(parentId)}/children`);
763
- if (this.cache && res.children) {
764
- await this.cache.setChildren(parentId, res.children).catch(() => null);
765
- }
766
- return kind
767
- ? res.documents.filter((d) => d.kind === kind)
768
- : res.documents;
769
- }
770
- // Root listing. The server runs the per-row permission cascade for
771
- // every top-level doc, so this is the expensive call. Send the
772
- // optional server-side `kind` filter — a fixed server skips the
773
- // cascade for non-matching docs; an old server ignores the unknown
774
- // param and we still filter client-side below, so the result is
775
- // identical either way. Concurrent identical root listings (a
776
- // connect fans out several) share one in-flight request.
777
- const key = kind ?? "";
778
- const existing = this.rootListInflight.get(key);
779
- const docs = existing
780
- ? await existing
781
- : await (() => {
782
- const p = this.request<{
783
- documents: DocumentMeta[];
784
- children?: string[];
785
- }>(
786
- "GET",
787
- kind
788
- ? `/docs?root=true&kind=${encodeURIComponent(kind)}`
789
- : "/docs?root=true",
790
- )
791
- .then((res) => res.documents)
792
- .finally(() => this.rootListInflight.delete(key));
793
- this.rootListInflight.set(key, p);
794
- return p;
795
- })();
796
- return kind ? docs.filter((d) => d.kind === kind) : docs;
797
- }
798
-
799
- /**
800
- * Create a child document under a parent (requires write permission).
801
- *
802
- * `kind` is the well-known tag (`Kind.Channel`, `Kind.Page`, etc.); the
803
- * server stores it in `documents.kind` but does not enforce semantics.
804
- * `description` is freeform metadata.
805
- */
806
- async createChild(
807
- docId: string,
808
- opts?: {
809
- child_id?: string;
810
- doc_type?: string;
811
- label?: string;
812
- kind?: string;
813
- description?: string;
814
- },
815
- ): Promise<DocumentMeta> {
816
- return this.request<DocumentMeta>(
817
- "POST",
818
- `/docs/${encodeURIComponent(docId)}/children`,
819
- { body: opts ?? {} },
820
- );
821
- }
822
-
823
- /** Broadcast a stateless message to all connected clients on a document (requires manage permission). */
824
- async broadcast(docId: string, payload: string): Promise<void> {
825
- await this.request("POST", `/docs/${encodeURIComponent(docId)}/broadcast`, { body: { payload } });
826
- }
827
-
828
- // ── Permissions ──────────────────────────────────────────────────────────
829
-
830
- /** List all permissions for a document (requires read access). */
831
- async listPermissions(docId: string): Promise<PermissionEntry[]> {
832
- if (this.cache) {
833
- const cached = await this.cache.getPermissions(docId);
834
- if (cached) return cached;
835
- }
836
- const res = await this.request<{ permissions: PermissionEntry[] }>(
837
- "GET",
838
- `/docs/${encodeURIComponent(docId)}/permissions`,
839
- );
840
- if (this.cache) {
841
- await this.cache.setPermissions(docId, res.permissions).catch(() => null);
842
- }
843
- return res.permissions;
844
- }
845
-
846
- /** List effective permissions including inherited ones from ancestor documents. */
847
- async listEffectivePermissions(
848
- docId: string,
849
- ): Promise<EffectivePermissionsResponse> {
850
- try {
851
- return await this.request<EffectivePermissionsResponse>(
852
- "GET",
853
- `/docs/${encodeURIComponent(docId)}/effective-permissions`,
854
- );
855
- } catch (e: unknown) {
856
- // Fallback for older servers that don't support this endpoint (404 only)
857
- if (typeof e === "object" && e !== null && "status" in e && (e as { status: number }).status === 404) {
858
- const perms = await this.listPermissions(docId);
859
- return {
860
- permissions: perms.map((p) => ({ ...p, source: "direct" as const })),
861
- default_role: "viewer",
862
- };
863
- }
864
- throw e;
865
- }
866
- }
867
-
868
- /** Grant or change a user's role on a document (requires Owner). */
869
- async setPermission(
870
- docId: string,
871
- opts: { user_id: string; role: "owner" | "editor" | "viewer" | "observer" },
872
- ): Promise<void> {
873
- await this.request(
874
- "POST",
875
- `/docs/${encodeURIComponent(docId)}/permissions`,
876
- { body: opts },
877
- );
878
- }
879
-
880
- /** Revoke a user's permission on a document (requires Owner). */
881
- async removePermission(docId: string, opts: { user_id: string }): Promise<void> {
882
- await this.request(
883
- "DELETE",
884
- `/docs/${encodeURIComponent(docId)}/permissions`,
885
- { body: opts },
886
- );
887
- }
888
-
889
- // ── Uploads ──────────────────────────────────────────────────────────────
890
-
891
- /** Upload a file to a document (requires write permission). */
892
- async upload(
893
- docId: string,
894
- file: File | Blob,
895
- filename?: string,
896
- ): Promise<UploadMeta> {
897
- const formData = new FormData();
898
- formData.append("file", file, filename);
899
-
900
- const headers: Record<string, string> = {};
901
- if (this._token) {
902
- headers["Authorization"] = `Bearer ${this._token}`;
903
- }
904
-
905
- const res = await this._fetch(
906
- `${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads`,
907
- { method: "POST", headers, body: formData },
908
- );
909
- if (!res.ok) {
910
- throw await this.toError(res);
911
- }
912
- const meta = await res.json() as UploadMeta;
913
- if (this.cache) {
914
- await this.cache.invalidateUploads(docId).catch(() => null);
915
- }
916
- return meta;
917
- }
918
-
919
- /** List all uploads for a document. */
920
- async listUploads(docId: string): Promise<UploadInfo[]> {
921
- if (this.cache) {
922
- const cached = await this.cache.getUploads(docId);
923
- if (cached) return cached;
924
- }
925
- const res = await this.request<{ uploads: UploadInfo[] }>(
926
- "GET",
927
- `/docs/${encodeURIComponent(docId)}/uploads`,
928
- );
929
- if (this.cache) {
930
- await this.cache.setUploads(docId, res.uploads).catch(() => null);
931
- }
932
- return res.uploads;
933
- }
934
-
935
- /** Download an upload as a Blob. */
936
- async getUpload(docId: string, uploadId: string): Promise<Blob> {
937
- const headers: Record<string, string> = {};
938
- if (this._token) {
939
- headers["Authorization"] = `Bearer ${this._token}`;
940
- }
941
-
942
- const res = await this._fetch(
943
- `${this.baseUrl}/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,
944
- { method: "GET", headers },
945
- );
946
- if (!res.ok) {
947
- throw await this.toError(res);
948
- }
949
- return res.blob();
950
- }
951
-
952
- /**
953
- * Mint a short-lived, read-only token bound to this one upload.
954
- * Prefer `getStreamUrl`, which caches and reuses the grant.
955
- */
956
- async createStreamToken(
957
- docId: string,
958
- uploadId: string,
959
- ): Promise<StreamTokenInfo> {
960
- return this.request<StreamTokenInfo>(
961
- "POST",
962
- `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/stream-token`,
963
- );
964
- }
965
-
966
- /**
967
- * Absolute URL that streams an upload straight from the server, safe to
968
- * hand to `<video src>` / `<audio src>`.
969
- *
970
- * Unlike `FileBlobStore.getBlobUrl` (which downloads the whole blob into
971
- * IndexedDB and hands back an object URL), this keeps the bytes on the
972
- * server so the browser can seek natively over HTTP Range — the difference
973
- * between "wait for 400 MB" and "scrub instantly". It needs the network,
974
- * so callers should fall back to `getBlobUrl` when offline.
975
- *
976
- * Grants are cached per upload and re-minted shortly before they expire.
977
- * Throws on servers older than the `stream-token` endpoint (404).
978
- */
979
- async getStreamUrl(docId: string, uploadId: string): Promise<string> {
980
- const key = `${docId}/${uploadId}`;
981
- const cached = this.streamTokens.get(key);
982
- // Re-mint a minute early so a URL handed to a media element doesn't
983
- // expire mid-request.
984
- if (cached && cached.expiresAt - 60_000 > Date.now()) return cached.url;
985
-
986
- // Single-flight: a page full of media blocks resolves the same upload
987
- // from several components at once, and each mint is a round trip.
988
- const inflight = this.streamTokenInflight.get(key);
989
- if (inflight) return inflight;
990
-
991
- const pending = this.createStreamToken(docId, uploadId)
992
- .then((info) => {
993
- const url = `${this.baseUrl}${info.url}`;
994
- this.streamTokens.set(key, {
995
- url,
996
- expiresAt: Date.now() + info.expires_in * 1000,
997
- });
998
- return url;
999
- })
1000
- .finally(() => {
1001
- this.streamTokenInflight.delete(key);
1002
- });
1003
- this.streamTokenInflight.set(key, pending);
1004
- return pending;
1005
- }
1006
-
1007
- /** Drop any cached stream grant for an upload (or all of them). */
1008
- clearStreamUrl(docId?: string, uploadId?: string): void {
1009
- if (docId && uploadId) {
1010
- this.streamTokens.delete(`${docId}/${uploadId}`);
1011
- this.streamTokenInflight.delete(`${docId}/${uploadId}`);
1012
- return;
1013
- }
1014
- this.streamTokens.clear();
1015
- this.streamTokenInflight.clear();
1016
- }
1017
-
1018
- /**
1019
- * Build the request path (with query string) for an upload's thumbnail.
1020
- * Also the canonical cache key suffix — the query string is deterministic
1021
- * in insertion order, so identical options map to the same URL and the
1022
- * same `FileBlobStore` cache entry.
1023
- */
1024
- thumbnailPath(docId: string, uploadId: string, opts: ThumbnailOptions = {}): string {
1025
- const p = new URLSearchParams();
1026
- if (opts.w != null) p.set("w", String(opts.w));
1027
- if (opts.h != null) p.set("h", String(opts.h));
1028
- if (opts.fit) p.set("fit", opts.fit);
1029
- if (opts.format) p.set("format", opts.format);
1030
- if (opts.q != null) p.set("q", String(opts.q));
1031
- const qs = p.toString();
1032
- return `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/thumbnail${qs ? `?${qs}` : ""}`;
1033
- }
1034
-
1035
- /**
1036
- * Download a generated thumbnail of an image upload as a Blob. The server
1037
- * renders + caches it on first request. Because a browser `<img>` can't
1038
- * send `Authorization`, callers render the returned Blob via an object URL
1039
- * (see `FileBlobStore.getThumbUrl`, which also caches it locally).
1040
- * Throws (with `.status = 415`) when the source isn't a thumbnailable
1041
- * raster image, or `422` for an out-of-allowlist size/format.
1042
- */
1043
- async getThumbnail(
1044
- docId: string,
1045
- uploadId: string,
1046
- opts: ThumbnailOptions = {},
1047
- ): Promise<Blob> {
1048
- const headers: Record<string, string> = {};
1049
- if (this._token) {
1050
- headers["Authorization"] = `Bearer ${this._token}`;
1051
- }
1052
-
1053
- const res = await this._fetch(
1054
- `${this.baseUrl}${this.thumbnailPath(docId, uploadId, opts)}`,
1055
- { method: "GET", headers },
1056
- );
1057
- if (!res.ok) {
1058
- throw await this.toError(res);
1059
- }
1060
- return res.blob();
1061
- }
1062
-
1063
- /** Delete an upload (requires uploader or document Owner). */
1064
- async deleteUpload(docId: string, uploadId: string): Promise<void> {
1065
- await this.request(
1066
- "DELETE",
1067
- `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}`,
1068
- );
1069
- if (this.cache) {
1070
- await this.cache.invalidateUploads(docId).catch(() => null);
1071
- }
1072
- }
1073
-
1074
- // ── Invites ──────────────────────────────────────────────────────────────
1075
-
1076
- /** Create an invite code (requires permission per server config). */
1077
- async createInvite(opts?: { role?: string; maxUses?: number; expiresIn?: number }): Promise<InviteRow> {
1078
- return this.request<InviteRow>("POST", "/invites", { body: opts ?? {} });
1079
- }
1080
-
1081
- /** List invite codes visible to the current user. */
1082
- async listInvites(): Promise<InviteRow[]> {
1083
- const res = await this.request<{ invites: InviteRow[] }>("GET", "/invites");
1084
- return res.invites;
1085
- }
1086
-
1087
- /** Revoke an invite by its code. */
1088
- async revokeInvite(code: string): Promise<void> {
1089
- await this.request("DELETE", `/invites/${encodeURIComponent(code)}`);
1090
- }
1091
-
1092
- /** Redeem an invite code for the currently authenticated user. */
1093
- async redeemInvite(code: string): Promise<void> {
1094
- await this.request("POST", "/invites/redeem", { body: { code } });
1095
- }
1096
-
1097
- // ── Document Access & Discovery ──────────────────────────────────────────
1098
-
1099
- /**
1100
- * Set the public_access level for a document. Pass null to inherit from parent.
1101
- *
1102
- * The values, and the two that are easy to confuse:
1103
- *
1104
- * - `"observer"` / `"viewer"` / `"editor"` — a FLOOR. Raises whoever reaches
1105
- * this document to at least that role, cascading to descendants.
1106
- * - `"none"` — no floor from here. Blocks anonymous, but an authenticated
1107
- * principal still falls through to the server's `[access].authenticated`
1108
- * default, so on a server with a floor this does NOT make a document private.
1109
- * - `"private"` — no floor AND no ambient default. Only explicit grants,
1110
- * ownership, Admin and Service reach a sealed document. This is what makes
1111
- * a document private without reconfiguring the whole server.
1112
- *
1113
- * The cascade takes the NEAREST ancestor that sets a value, not the strongest,
1114
- * so a descendant can re-publish itself out of a private parent.
1115
- *
1116
- * `"private"` requires server ≥ the release that introduced it. An older
1117
- * server rejects it with 400 rather than silently storing it.
1118
- */
1119
- async setDocumentAccess(
1120
- docId: string,
1121
- publicAccess: "none" | "private" | "observer" | "viewer" | "editor" | null,
1122
- ): Promise<void> {
1123
- await this.request("PATCH", `/docs/${encodeURIComponent(docId)}/access`, {
1124
- body: { public_access: publicAccess },
1125
- });
1126
- }
1127
-
1128
- /** Get the public_access info for a document. */
1129
- async getDocumentAccess(docId: string): Promise<{ public_access: string | null; effective_public_access: string | null }> {
1130
- return this.request("GET", `/docs/${encodeURIComponent(docId)}/access`);
1131
- }
1132
-
1133
- /**
1134
- * Update document metadata (label, description, kind, doc_type, parent_id).
1135
- * Requires manage permission on the doc; reparenting additionally requires
1136
- * manage on the new parent (or admin if moving under the server root).
1137
- *
1138
- * `doc_type` is the renderer hint (`"kanban"`, `"graph"`, …) — orthogonal
1139
- * to `kind` (the structural role). Use it for post-create type changes;
1140
- * never write renderer strings into `kind`. Servers older than migration
1141
- * 0014 ignore the field (unknown JSON fields are dropped server-side).
1142
- */
1143
- async updateDocumentMeta(
1144
- docId: string,
1145
- opts: {
1146
- label?: string | null;
1147
- description?: string | null;
1148
- kind?: string | null;
1149
- doc_type?: string | null;
1150
- parent_id?: string | null;
1151
- },
1152
- ): Promise<void> {
1153
- await this.request("PATCH", `/docs/${encodeURIComponent(docId)}`, { body: opts });
1154
- }
1155
-
1156
- // ── Spaces ───────────────────────────────────────────────────────────────
1157
- //
1158
- // "Spaces" are direct children of the server root with `kind: "space"`.
1159
- // They live in the regular `documents` table — there's no dedicated
1160
- // spaces resource on the server anymore. These helpers keep the familiar
1161
- // names so callers don't have to think about the underlying tree.
1162
-
1163
- /**
1164
- * List Spaces visible to the caller — top-level docs (children of the
1165
- * server root) tagged with `kind: "space"`. Authenticated users see
1166
- * spaces resolving to any role; anonymous users see public ones.
1167
- */
1168
- async listSpaces(): Promise<DocumentMeta[]> {
1169
- return this.listChildren(undefined, { kind: Kind.Space });
1170
- }
1171
-
1172
- /**
1173
- * Create a new top-level Space. Equivalent to a `POST /docs` with
1174
- * `kind: "space"` plus the supplied metadata in one round trip.
1175
- *
1176
- * `visibility: "public"` sets `public_access = "observer"` (anonymous
1177
- * read, no awareness or writes). `"private"` (the default) leaves
1178
- * `public_access` unset so only explicit grants apply.
1179
- */
1180
- async createSpace(opts: {
1181
- name: string;
1182
- description?: string;
1183
- visibility?: "public" | "private";
1184
- id?: string;
1185
- }): Promise<DocumentMeta> {
1186
- const public_access = opts.visibility === "public" ? "observer" : "none";
1187
- return this.request<DocumentMeta>("POST", "/docs", {
1188
- body: {
1189
- id: opts.id,
1190
- label: opts.name,
1191
- description: opts.description,
1192
- kind: Kind.Space,
1193
- public_access,
1194
- },
1195
- });
1196
- }
1197
-
1198
- /**
1199
- * Update a Space's metadata. `visibility` flips `public_access` between
1200
- * `"observer"` (public) and `"none"` (private). To leave visibility
1201
- * untouched, omit it. Pass any property as `null` to clear it.
1202
- */
1203
- async updateSpace(
1204
- docId: string,
1205
- opts: { name?: string | null; description?: string | null; visibility?: "public" | "private" },
1206
- ): Promise<void> {
1207
- const meta: { label?: string | null; description?: string | null } = {};
1208
- if (opts.name !== undefined) meta.label = opts.name;
1209
- if (opts.description !== undefined) meta.description = opts.description;
1210
- if (Object.keys(meta).length > 0) {
1211
- await this.updateDocumentMeta(docId, meta);
1212
- }
1213
- if (opts.visibility !== undefined) {
1214
- await this.setDocumentAccess(docId, opts.visibility === "public" ? "observer" : "none");
1215
- }
1216
- }
1217
-
1218
- /** Delete a Space (and every doc nested under it). Requires manage permission. */
1219
- async deleteSpace(docId: string): Promise<void> {
1220
- await this.deleteDoc(docId);
1221
- }
1222
-
1223
- /**
1224
- * Look up the DM doc between the calling user and `otherUserPk`, or
1225
- * create it if none exists. The doc id is deterministically derived from
1226
- * the sorted pubkey pair (see {@link deriveDmDocId}) so both sides
1227
- * compute the same target — race-tolerant by construction. The created
1228
- * doc has `kind = "dm"`, `public_access = "none"`, and explicit Editor
1229
- * permissions for both participants.
1230
- *
1231
- * The cascade resolver enforces that no other user can read the DM,
1232
- * because:
1233
- * - `public_access = "none"` blocks anonymous + falls through to the
1234
- * server-wide `[access].authenticated` floor for everyone else;
1235
- * - the explicit Editor rows only exist for the two participants, so
1236
- * non-participants get only the (capped) authenticated floor;
1237
- * - the doc lives at server root, so there's no ancestor that could
1238
- * leak via a higher cascade grant.
1239
- *
1240
- * Note: when `[access].authenticated >= "viewer"` is set server-wide,
1241
- * non-participants can still *read* the DM via the authenticated floor —
1242
- * `public_access = "none"` removes the floor but not the ambient default.
1243
- *
1244
- * Servers that support `public_access = "private"` can seal it properly:
1245
- * call `setDocumentAccess(dmId, "private")` after creating one. That is NOT
1246
- * done here, deliberately — this SDK talks to older servers too, and they
1247
- * reject the value with a 400. Callers that know their server version can
1248
- * opt in; a future major may make it the default.
1249
- *
1250
- * @param otherUserPk Base64url-encoded Ed25519 public key of the other party.
1251
- * @returns The DM doc's id (existing or newly created).
1252
- */
1253
- async findOrCreateDmDoc(otherUserPk: string): Promise<string> {
1254
- const me = await this.getMe();
1255
- if (!me.publicKey) {
1256
- throw new Error("findOrCreateDmDoc: caller has no public key");
1257
- }
1258
- const dmId = deriveDmDocId(me.publicKey, otherUserPk);
1259
- // Try to fetch the doc first — if it exists, we're done.
1260
- try {
1261
- const existing = await this.getDoc(dmId);
1262
- if (existing && existing.kind === Kind.Dm) {
1263
- return dmId;
1264
- }
1265
- } catch {
1266
- // 404 is the expected miss; any other error we let bubble up
1267
- // from createDoc below.
1268
- }
1269
- // Race-tolerant create: both clients hashing the same pubkey pair
1270
- // generate the same id, so whoever loses the create gets Conflict
1271
- // and the catch reuses the id.
1272
- try {
1273
- await this.request<DocumentMeta>("POST", "/docs", {
1274
- body: {
1275
- id: dmId,
1276
- kind: Kind.Dm,
1277
- public_access: "none",
1278
- },
1279
- });
1280
- } catch (err: any) {
1281
- // Conflict means the other side already created it; reuse.
1282
- const status = err?.status ?? err?.response?.status;
1283
- if (status !== 409) throw err;
1284
- }
1285
- // Idempotent permission grants (server upserts on (doc_id, user_id)).
1286
- await this.setPermission(dmId, { user_id: me.publicKey, role: "editor" });
1287
- await this.setPermission(dmId, { user_id: otherUserPk, role: "editor" });
1288
- return dmId;
1289
- }
1290
-
1291
- /**
1292
- * The reserved server root document id. Convenience accessor for the
1293
- * client; identical to {@link SERVER_ROOT_ID}. Use this as the parent for
1294
- * top-level docs / Spaces.
1295
- */
1296
- get rootDocId(): string {
1297
- return SERVER_ROOT_ID;
1298
- }
1299
-
1300
- // ── Admin ───────────────────────────────────────────────────────────────
1301
-
1302
- /** List all users (requires elevated role: admin or service). */
1303
- async adminListUsers(): Promise<{ users: (UserProfile & { revoked: boolean; deviceKeys: string[] })[] }> {
1304
- return this.request("GET", "/admin/users");
1305
- }
1306
-
1307
- /** Promote a user to admin (requires service role). */
1308
- async adminPromote(userId: string): Promise<void> {
1309
- await this.request("POST", `/admin/users/${encodeURIComponent(userId)}/admin`);
1310
- }
1311
-
1312
- /** Demote an admin user back to regular (requires service role). */
1313
- async adminDemote(userId: string): Promise<void> {
1314
- await this.request("DELETE", `/admin/users/${encodeURIComponent(userId)}/admin`);
1315
- }
1316
-
1317
- /** Sweep orphaned file blobs from storage (requires elevated role). */
1318
- async adminStorageSweep(): Promise<{ blobsDeleted: number }> {
1319
- return this.request("POST", "/admin/storage/sweep");
1320
- }
1321
-
1322
- /** Repair blob ref-counts and sweep orphans (requires elevated role). */
1323
- async adminStorageRepair(): Promise<{ refCountsRepaired: number; blobsSwept: number }> {
1324
- return this.request("POST", "/admin/storage/repair");
1325
- }
1326
-
1327
- /**
1328
- * Admin one-shot: populate the `snapshot_files` table for snapshots
1329
- * created before that migration ran, so `SnapshotMeta.file_count` and
1330
- * upload-ref tracking become accurate. Idempotent (insert-or-ignore).
1331
- * Requires elevated role.
1332
- */
1333
- async adminSnapshotsBackfillRefs(): Promise<{
1334
- snapshotsScanned: number;
1335
- refsWritten: number;
1336
- }> {
1337
- return this.request("POST", "/admin/snapshots/backfill-refs");
1338
- }
1339
-
1340
- /**
1341
- * Admin one-shot: migrate pre-dedup inline snapshot data into the
1342
- * content-addressed `snapshot_blobs` store. Idempotent (only migrates
1343
- * rows with `data_hash IS NULL`). Requires elevated role.
1344
- */
1345
- async adminSnapshotsBackfillBlobs(): Promise<{
1346
- snapshotsMigrated: number;
1347
- blobsAfter: number;
1348
- totalBytesAfter: number;
1349
- }> {
1350
- return this.request("POST", "/admin/snapshots/backfill-blobs");
1351
- }
1352
-
1353
- /**
1354
- * Admin: server-wide upload listing, joined with the owning document
1355
- * (label is best-effort — labels live in the CRDT, not the SQL row)
1356
- * and the content-addressed blob (`ref_count` exposes dedup).
1357
- * Server-side paginated + filtered. Requires elevated role.
1358
- */
1359
- async adminListUploads(
1360
- opts: { q?: string; docId?: string; limit?: number; offset?: number } = {},
1361
- ): Promise<{
1362
- uploads: Array<{
1363
- id: string;
1364
- doc_id: string;
1365
- doc_label: string | null;
1366
- filename: string;
1367
- mime_type: string | null;
1368
- size: number | null;
1369
- content_hash: string | null;
1370
- ref_count: number | null;
1371
- owner_id: string;
1372
- created_at: number;
1373
- }>;
1374
- total: number;
1375
- }> {
1376
- const p = new URLSearchParams();
1377
- if (opts.q) p.set("q", opts.q);
1378
- if (opts.docId) p.set("doc_id", opts.docId);
1379
- if (opts.limit != null) p.set("limit", String(opts.limit));
1380
- if (opts.offset != null) p.set("offset", String(opts.offset));
1381
- const qs = p.toString();
1382
- return this.request("GET", `/admin/uploads${qs ? `?${qs}` : ""}`);
1383
- }
1384
-
1385
- /**
1386
- * Admin: aggregate storage figures. `logicalBytes` is what users
1387
- * uploaded; `physicalBytes` is on-disk after content-addressed dedup;
1388
- * `dedupSaved` is the difference. Requires elevated role.
1389
- */
1390
- async adminStorageStats(): Promise<{
1391
- uploadCount: number;
1392
- blobCount: number;
1393
- logicalBytes: number;
1394
- physicalBytes: number;
1395
- dedupSaved: number;
1396
- }> {
1397
- return this.request("GET", "/admin/storage/stats");
1398
- }
1399
-
1400
- /**
1401
- * Clear the lockout state on a user account: zeroes the failed-login
1402
- * counter and `locked_until`. Requires elevated role (Admin or
1403
- * Service). The action is recorded in the audit log under
1404
- * `admin.user_unlock`.
1405
- */
1406
- async adminUnlockUser(userId: string): Promise<void> {
1407
- await this.request("POST", `/admin/users/${encodeURIComponent(userId)}/unlock`);
1408
- }
1409
-
1410
- /**
1411
- * Admin: every non-deleted document the user owns (`source: "owner"`)
1412
- * or has an explicit permission grant on (`source: "grant"`, with
1413
- * `role`). Answers "what does this identity touch" without an N+1
1414
- * client tree walk. Labels are best-effort (they live in the CRDT).
1415
- * Requires elevated role.
1416
- */
1417
- async adminUserDocs(
1418
- userId: string,
1419
- opts: { limit?: number } = {},
1420
- ): Promise<{
1421
- docs: Array<{
1422
- id: string;
1423
- label: string | null;
1424
- kind: string | null;
1425
- doc_type: string | null;
1426
- parent_id: string | null;
1427
- source: "owner" | "grant";
1428
- role: string | null;
1429
- }>;
1430
- }> {
1431
- const qs = opts.limit != null ? `?limit=${opts.limit}` : "";
1432
- return this.request(
1433
- "GET",
1434
- `/admin/users/${encodeURIComponent(userId)}/docs${qs}`,
1435
- );
1436
- }
1437
-
1438
- /**
1439
- * List `service`-role users (runners, demo seeders, automation
1440
- * identities). Requires Service role. Admins can see service users via
1441
- * `/admin/users` too but cannot mint or rotate them.
1442
- */
1443
- async adminListServiceAccounts(): Promise<{
1444
- items: Array<{
1445
- id: string;
1446
- username: string;
1447
- public_key: string | null;
1448
- revoked: boolean;
1449
- display_name: string | null;
1450
- }>;
1451
- }> {
1452
- return this.request("GET", "/admin/service-accounts");
1453
- }
1454
-
1455
- /**
1456
- * Create a new `service`-role user. When `public_key` is omitted the
1457
- * server generates a keypair and returns the private half in the
1458
- * response — show it to the operator **once** and discard; the server
1459
- * never persists it. Requires Service role.
1460
- */
1461
- async adminCreateServiceAccount(body: {
1462
- username: string;
1463
- public_key?: string;
1464
- }): Promise<{
1465
- id: string;
1466
- username: string;
1467
- public_key: string;
1468
- role: string;
1469
- private_key?: string;
1470
- }> {
1471
- return this.request("POST", "/admin/service-accounts", { body });
1472
- }
1473
-
1474
- /**
1475
- * Rotate the active keypair on a service account. Old JWTs are
1476
- * invalidated; old device keys are marked revoked; the canonical
1477
- * `users.public_key` swaps to the new value. `users.id` stays put so
1478
- * existing permission rows keep matching. Returns the new pubkey (and
1479
- * private half when the server generated it). Requires Service role.
1480
- */
1481
- async adminRotateServiceAccountKey(
1482
- userId: string,
1483
- body: { public_key?: string } = {},
1484
- ): Promise<{ id: string; public_key: string; private_key?: string }> {
1485
- return this.request(
1486
- "POST",
1487
- `/admin/service-accounts/${encodeURIComponent(userId)}/rotate-key`,
1488
- { body },
1489
- );
1490
- }
1491
-
1492
- /**
1493
- * Lock a service account and revoke all of its device keys. Idempotent.
1494
- * Refuses targets whose `users.role` isn't `"service"`. Requires
1495
- * Service role.
1496
- */
1497
- async adminRevokeServiceAccount(userId: string): Promise<void> {
1498
- await this.request(
1499
- "DELETE",
1500
- `/admin/service-accounts/${encodeURIComponent(userId)}`,
1501
- );
1502
- }
1503
-
1504
- /**
1505
- * Revoke a single device key on a user (any role). Bumps
1506
- * `tokens_invalid_before` so open WS sessions tied to the key must
1507
- * re-auth. Requires elevated role (Service or Admin@root).
1508
- */
1509
- async adminRevokeDeviceKey(userId: string, keyId: string): Promise<void> {
1510
- await this.request(
1511
- "POST",
1512
- `/admin/users/${encodeURIComponent(userId)}/device-keys/${encodeURIComponent(keyId)}/revoke`,
1513
- );
1514
- }
1515
-
1516
- /**
1517
- * Page through the audit log. Filters AND-combine; `limit` defaults to
1518
- * 100 server-side. Requires elevated role.
1519
- */
1520
- async adminAuditList(opts?: AuditQueryOpts): Promise<AuditLogEntry[]> {
1521
- const params = new URLSearchParams();
1522
- if (opts?.event_type) params.set("event_type", opts.event_type);
1523
- if (opts?.actor_user_id) params.set("actor_user_id", opts.actor_user_id);
1524
- if (opts?.target_type) params.set("target_type", opts.target_type);
1525
- if (opts?.target_id) params.set("target_id", opts.target_id);
1526
- if (opts?.since_ts != null) params.set("since_ts", String(opts.since_ts));
1527
- if (opts?.until_ts != null) params.set("until_ts", String(opts.until_ts));
1528
- if (opts?.limit != null) params.set("limit", String(opts.limit));
1529
- if (opts?.offset != null) params.set("offset", String(opts.offset));
1530
- const qs = params.toString();
1531
- const res = await this.request<{ items: AuditLogEntry[] }>(
1532
- "GET",
1533
- `/admin/audit${qs ? `?${qs}` : ""}`,
1534
- );
1535
- return res.items;
1536
- }
1537
-
1538
- /**
1539
- * Stream the audit log as NDJSON (one JSON object per line) for SIEM
1540
- * ingestion. Filters mirror {@link adminAuditList} minus `limit`/`offset`.
1541
- * The server pages internally so memory usage is bounded; this method
1542
- * buffers the full response into a string and is therefore best for
1543
- * moderate exports — large dumps should consume `/admin/audit/export`
1544
- * directly with a streaming HTTP client.
1545
- */
1546
- async adminAuditExport(opts?: Omit<AuditQueryOpts, "limit" | "offset">): Promise<string> {
1547
- const params = new URLSearchParams();
1548
- if (opts?.event_type) params.set("event_type", opts.event_type);
1549
- if (opts?.actor_user_id) params.set("actor_user_id", opts.actor_user_id);
1550
- if (opts?.target_type) params.set("target_type", opts.target_type);
1551
- if (opts?.target_id) params.set("target_id", opts.target_id);
1552
- if (opts?.since_ts != null) params.set("since_ts", String(opts.since_ts));
1553
- if (opts?.until_ts != null) params.set("until_ts", String(opts.until_ts));
1554
- const qs = params.toString();
1555
- const headers: Record<string, string> = {};
1556
- if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
1557
- const res = await this._fetch(
1558
- `${this.baseUrl}/admin/audit/export${qs ? `?${qs}` : ""}`,
1559
- { method: "GET", headers },
1560
- );
1561
- if (!res.ok) throw await this.toError(res, "GET", "/admin/audit/export");
1562
- return res.text();
1563
- }
1564
-
1565
- /**
1566
- * Verify the integrity of the audit-log hash chain. Returns the result
1567
- * unchanged: `status: "ok"` when the chain is intact, `status: "broken"`
1568
- * with a `break` payload identifying the first divergent row when
1569
- * tampering is detected. Wraps `GET /admin/audit/verify`. Requires
1570
- * elevated role.
1571
- *
1572
- * Note: the server returns HTTP 409 on a broken chain — this method
1573
- * special-cases the 409 status and returns the body as a successful
1574
- * result rather than throwing, because "broken" is a valid answer
1575
- * from the verifier, not an error.
1576
- */
1577
- async adminAuditVerify(): Promise<AuditVerifyResult> {
1578
- const headers: Record<string, string> = {};
1579
- if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
1580
- const res = await this._fetch(`${this.baseUrl}/admin/audit/verify`, {
1581
- method: "GET",
1582
- headers,
1583
- });
1584
- if (res.status === 200 || res.status === 409) {
1585
- return res.json() as Promise<AuditVerifyResult>;
1586
- }
1587
- throw await this.toError(res, "GET", "/admin/audit/verify");
1588
- }
1589
-
1590
- /**
1591
- * Download a tar archive of the schema-meaningful tables (users,
1592
- * documents, permissions, invites, optionally audit log). Requires
1593
- * elevated role. The server gzips the response when the client sends
1594
- * `Accept-Encoding: gzip` — `fetch` handles that transparently, so
1595
- * the returned Blob is the raw tar bytes.
1596
- */
1597
- async adminBackupDump(opts?: { includeAudit?: boolean }): Promise<Blob> {
1598
- const params = new URLSearchParams();
1599
- if (opts?.includeAudit) params.set("include_audit", "true");
1600
- const qs = params.toString();
1601
- const headers: Record<string, string> = {};
1602
- if (this._token) headers["Authorization"] = `Bearer ${this._token}`;
1603
- const res = await this._fetch(
1604
- `${this.baseUrl}/admin/backup/dump${qs ? `?${qs}` : ""}`,
1605
- { method: "GET", headers },
1606
- );
1607
- if (!res.ok) throw await this.toError(res, "GET", "/admin/backup/dump");
1608
- return res.blob();
1609
- }
1610
-
1611
- // ── Admin: runtime config store ──────────────────────────────────────────
1612
-
1613
- /**
1614
- * List every registered config field with current value + origin
1615
- * (`default` / `env` / `global_override` / `route_override`). Requires
1616
- * elevated role.
1617
- */
1618
- async adminConfigList(): Promise<AdminConfigField[]> {
1619
- const res = await this.request<{ items: AdminConfigField[] }>(
1620
- "GET", "/admin/config",
1621
- );
1622
- return res.items;
1623
- }
1624
-
1625
- /** Read a single config field by dotted path (e.g. `"access.authenticated"`). */
1626
- async adminConfigGet(path: string): Promise<AdminConfigField> {
1627
- return this.request<AdminConfigField>(
1628
- "GET", `/admin/config/fields/${encodeURIComponent(path)}`,
1629
- );
1630
- }
1631
-
1632
- /**
1633
- * Set a runtime override on a config field. The field must be marked
1634
- * `runtime_mutable = true` in the registry; immutable fields return a
1635
- * schema error. Persists to the `settings_overrides` table.
1636
- */
1637
- async adminConfigSet(path: string, value: unknown): Promise<AdminConfigField> {
1638
- return this.request<AdminConfigField>(
1639
- "PUT", `/admin/config/fields/${encodeURIComponent(path)}`,
1640
- { body: { value } },
1641
- );
1642
- }
1643
-
1644
- /**
1645
- * Clear a runtime override and revert the field to its env/TOML/default
1646
- * base value. Returns `true` when an override was actually removed.
1647
- */
1648
- async adminConfigUnset(path: string): Promise<boolean> {
1649
- const res = await this.request<{ existed: boolean }>(
1650
- "DELETE", `/admin/config/fields/${encodeURIComponent(path)}`,
1651
- );
1652
- return res.existed;
1653
- }
1654
-
1655
- /**
1656
- * Diagnostic dump of every `ABRA_*` env var the running process saw at
1657
- * boot, mapped to its config path. Use this to debug
1658
- * "I set this in `.env` but the server reports a different value".
1659
- * Secrets are redacted (`value: null`, `redacted: true`).
1660
- */
1661
- async adminConfigEnvSnapshot(): Promise<EnvSnapshotResponse> {
1662
- return this.request<EnvSnapshotResponse>("GET", "/admin/config/env-snapshot");
1663
- }
1664
-
1665
- /**
1666
- * List every route pattern that currently has at least one per-route
1667
- * config override. Use {@link adminConfigGetRoute} to read individual
1668
- * fields. Requires elevated role.
1669
- */
1670
- async adminConfigListRoutes(): Promise<string[]> {
1671
- const res = await this.request<{ routes: string[] }>(
1672
- "GET", "/admin/config/routes",
1673
- );
1674
- return res.routes;
1675
- }
1676
-
1677
- /**
1678
- * Read a field's effective value scoped to `route`, falling back to
1679
- * the global value when no per-route override exists. `origin_kind`
1680
- * is `"route_override"` only when an override is actually set.
1681
- */
1682
- async adminConfigGetRoute(route: string, path: string): Promise<AdminConfigField> {
1683
- return this.request<AdminConfigField>(
1684
- "GET",
1685
- `/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,
1686
- );
1687
- }
1688
-
1689
- /** Set or replace a per-route override. Mirrors {@link adminConfigSet}. */
1690
- async adminConfigSetRoute(route: string, path: string, value: unknown): Promise<AdminConfigField> {
1691
- return this.request<AdminConfigField>(
1692
- "PUT",
1693
- `/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,
1694
- { body: { value } },
1695
- );
1696
- }
1697
-
1698
- /** Clear a per-route override (falls back to global). True if one existed. */
1699
- async adminConfigUnsetRoute(route: string, path: string): Promise<boolean> {
1700
- const res = await this.request<{ existed: boolean }>(
1701
- "DELETE",
1702
- `/admin/config/routes/${encodeURIComponent(route)}/fields/${encodeURIComponent(path)}`,
1703
- );
1704
- return res.existed;
1705
- }
1706
-
1707
- // ── Snapshots ────────────────────────────────────────────────────────────
1708
-
1709
- /** List snapshot metadata for a document. */
1710
- async listSnapshots(docId: string, opts?: { limit?: number; offset?: number }): Promise<SnapshotMeta[]> {
1711
- const params = new URLSearchParams();
1712
- if (opts?.limit != null) params.set("limit", String(opts.limit));
1713
- if (opts?.offset != null) params.set("offset", String(opts.offset));
1714
- const qs = params.toString();
1715
- const res = await this.request<{ snapshots: SnapshotMeta[] }>(
1716
- "GET", `/docs/${encodeURIComponent(docId)}/snapshots${qs ? `?${qs}` : ""}`,
1717
- );
1718
- return res.snapshots;
1719
- }
1720
-
1721
- /** Fetch a single snapshot including its base64-encoded data blob.
1722
- * Pass `{ include: "files" }` to also receive the joined upload list
1723
- * (each `fileBlock` / `coverUploadId` resolved against `uploads`). */
1724
- async getSnapshot(
1725
- docId: string,
1726
- version: number,
1727
- opts?: { include?: "files" | string },
1728
- ): Promise<SnapshotData> {
1729
- const qs = opts?.include ? `?include=${encodeURIComponent(opts.include)}` : "";
1730
- return this.request<SnapshotData>(
1731
- "GET", `/docs/${encodeURIComponent(docId)}/snapshots/${version}${qs}`,
1732
- );
1733
- }
1734
-
1735
- /** Create a manual snapshot of the current document state. */
1736
- async createSnapshot(docId: string, opts?: { label?: string }): Promise<SnapshotCreateResult> {
1737
- return this.request<SnapshotCreateResult>(
1738
- "POST", `/docs/${encodeURIComponent(docId)}/snapshots`,
1739
- { body: opts ?? {} },
1740
- );
1741
- }
1742
-
1743
- /** Delete a specific snapshot version. Requires manage permission. */
1744
- async deleteSnapshot(docId: string, version: number): Promise<void> {
1745
- await this.request("DELETE", `/docs/${encodeURIComponent(docId)}/snapshots/${version}`);
1746
- }
1747
-
1748
- /** Restore a snapshot by merging it forward into the current document state. */
1749
- async restoreSnapshot(docId: string, version: number): Promise<SnapshotRestoreResult> {
1750
- return this.request<SnapshotRestoreResult>(
1751
- "POST", `/docs/${encodeURIComponent(docId)}/snapshots/${version}/restore`,
1752
- { body: {} },
1753
- );
1754
- }
1755
-
1756
- /** Fork a snapshot into a new document. */
1757
- async forkSnapshot(docId: string, version: number): Promise<SnapshotForkResult> {
1758
- return this.request<SnapshotForkResult>(
1759
- "POST", `/docs/${encodeURIComponent(docId)}/snapshots/${version}/fork`,
1760
- { body: {} },
1761
- );
1762
- }
1763
-
1764
- // ── System ───────────────────────────────────────────────────────────────
1765
-
1766
- /** Health check — no auth required. */
1767
- async health(): Promise<HealthStatus> {
1768
- return this.request<HealthStatus>("GET", "/health", { auth: false });
1769
- }
1770
-
1771
- /**
1772
- * Readiness probe — pings the database. Returns 200 with
1773
- * `status: "ready"` only when the server can serve traffic, 503 with
1774
- * `status: "unready"` otherwise (load balancers / Kubernetes probes
1775
- * use the status code; the body is informational).
1776
- *
1777
- * The 503 case is special-cased here: instead of throwing, the method
1778
- * returns the unready body so callers can react to the state without
1779
- * try/catch boilerplate.
1780
- */
1781
- async readyz(): Promise<ReadyzStatus> {
1782
- const res = await this._fetch(`${this.baseUrl}/readyz`, { method: "GET" });
1783
- if (res.status === 200 || res.status === 503) {
1784
- return res.json() as Promise<ReadyzStatus>;
1785
- }
1786
- throw await this.toError(res, "GET", "/readyz");
1787
- }
1788
-
1789
- /**
1790
- * Fetch server metadata including `root_doc_id` and the `[access]` policy.
1791
- * No auth required.
1792
- */
1793
- async serverInfo(): Promise<ServerInfo> {
1794
- return this.request<ServerInfo>("GET", "/info", { auth: false });
1795
- }
1796
-
1797
- /**
1798
- * Drop this browser's caches for this server if its database has been
1799
- * REPLACED since the last visit, and report what happened.
1800
- *
1801
- * **Call it before opening any provider**, and await it. A deleted database
1802
- * is not a tombstone — it is a peer that lost its memory — so a tab that
1803
- * reconnects with stale IndexedDB re-pushes the old tree into the fresh one
1804
- * and a seeder adds its own on top: every page twice, then three times. Once
1805
- * a provider holds a store open, `deleteDatabase` blocks instead of deleting
1806
- * and the damage is already queued; those stores come back in `blocked`,
1807
- * which is a signal that this ran too late rather than something to ignore.
1808
- *
1809
- * Returns `null` when there is nothing to do — no `server_id`, no browser
1810
- * storage, a first visit, or the same database as last time. It never
1811
- * throws: an app must not fail to start because a cache could not be tidied.
1812
- *
1813
- * @see dropCachesIfServerReplaced for what is dropped and what is kept.
1814
- */
1815
- async ensureFreshServer(): Promise<ServerResetOutcome | null> {
1816
- try {
1817
- const info = await this.serverInfo();
1818
- if (!info?.server_id) return null;
1819
- // `host`, matching how providers scope their stores — the port is part
1820
- // of a server's identity, so two servers on one machine do not share a
1821
- // cache namespace.
1822
- const host = new URL(this.wsUrl).host;
1823
- return await dropCachesIfServerReplaced(host, info.server_id);
1824
- } catch {
1825
- return null;
1826
- }
1827
- }
1828
-
1829
- /**
1830
- * Fetch ICE server configuration for WebRTC peer connections.
1831
- * Falls back to default Google STUN server if the endpoint is unavailable.
1832
- * No auth required.
1833
- */
1834
- async getIceServers(): Promise<RTCIceServer[]> {
1835
- try {
1836
- const res = await this.request<{ iceServers: RTCIceServer[] }>(
1837
- "GET",
1838
- "/ice-servers",
1839
- { auth: false },
1840
- );
1841
- return res.iceServers;
1842
- } catch {
1843
- return [{ urls: "stun:stun.l.google.com:19302" }];
1844
- }
1845
- }
1846
-
1847
- // ── Internals ────────────────────────────────────────────────────────────
1848
-
1849
- private async request<T = void>(
1850
- method: string,
1851
- path: string,
1852
- opts?: { body?: unknown; auth?: boolean },
1853
- ): Promise<T> {
1854
- const auth = opts?.auth ?? true;
1855
- const headers: Record<string, string> = {};
1856
-
1857
- if (auth && this._token) {
1858
- headers["Authorization"] = `Bearer ${this._token}`;
1859
- }
1860
-
1861
- const init: RequestInit = { method, headers, signal: AbortSignal.timeout(30_000) };
1862
-
1863
- if (opts?.body !== undefined) {
1864
- headers["Content-Type"] = "application/json";
1865
- init.body = JSON.stringify(opts.body);
1866
- }
1867
-
1868
- const res = await this._fetch(`${this.baseUrl}${path}`, init);
1869
-
1870
- if (!res.ok) {
1871
- throw await this.toError(res, method, path);
1872
- }
1873
-
1874
- // 204 No Content
1875
- if (res.status === 204) {
1876
- return undefined as T;
1877
- }
1878
-
1879
- return res.json() as Promise<T>;
1880
- }
1881
-
1882
- private async requestOrNull<T>(
1883
- method: string,
1884
- path: string,
1885
- opts?: { body?: unknown; auth?: boolean },
1886
- ): Promise<T | null> {
1887
- try {
1888
- return await this.request<T>(method, path, opts);
1889
- } catch (e: unknown) {
1890
- if (typeof e === "object" && e !== null && "status" in e && (e as { status: number }).status === 404) {
1891
- return null;
1892
- }
1893
- throw e;
1894
- }
1895
- }
1896
-
1897
- private async toError(res: Response, method?: string, path?: string): Promise<Error> {
1898
- let message: string;
1899
- try {
1900
- const body = await res.json() as { error?: string };
1901
- message = body.error ?? res.statusText;
1902
- } catch {
1903
- message = res.statusText;
1904
- }
1905
- const prefix = method && path ? `${method} ${path}: ` : "";
1906
- const err = new Error(`${prefix}${message} (${res.status})`);
1907
- (err as any).status = res.status;
1908
- // Surface 401/403 to the auth-failed handler so consumers can trigger
1909
- // reauth without waiting for the next WS action. Fire-and-forget —
1910
- // the original Promise still rejects so callers handle their own
1911
- // error path. Wrap in setTimeout(0) so the callback runs out-of-band
1912
- // of the current request's microtask queue.
1913
- if ((res.status === 401 || res.status === 403) && this._onAuthFailed) {
1914
- const lower = message.toLowerCase();
1915
- let reason: AuthFailureReason = res.status === 401 ? "unauthorized" : "forbidden";
1916
- if (/user not found|user_not_found|public key not registered|no such user/.test(lower)) {
1917
- reason = "user_not_found";
1918
- } else if (/account revoked|user account revoked/.test(lower)) {
1919
- reason = "account_revoked";
1920
- } else if (/forbidden|insufficient permissions/.test(lower)) {
1921
- reason = "forbidden";
1922
- }
1923
- const ctx: AuthFailureContext = {
1924
- status: res.status,
1925
- message,
1926
- reason,
1927
- method: method ?? "",
1928
- path: path ?? "",
1929
- };
1930
- try {
1931
- setTimeout(() => { try { this._onAuthFailed!(ctx); } catch { /* swallow */ } }, 0);
1932
- } catch { /* setTimeout unavailable in some sandboxes — drop the signal */ }
1933
- }
1934
- return err;
1935
- }
1936
-
1937
- private loadPersistedToken(): string | null {
1938
- try {
1939
- return localStorage.getItem(this.storageKey);
1940
- } catch {
1941
- return null;
1942
- }
1943
- }
1944
-
1945
- private persistToken(token: string): void {
1946
- try {
1947
- localStorage.setItem(this.storageKey, token);
1948
- } catch {
1949
- // localStorage unavailable (SSR / Node.js)
1950
- }
1951
- }
1952
-
1953
- private clearPersistedToken(): void {
1954
- try {
1955
- localStorage.removeItem(this.storageKey);
1956
- } catch {
1957
- // localStorage unavailable
1958
- }
1959
- }
1960
- }