@abraca/dabra 2.34.0 → 2.35.1

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.
package/dist/index.d.ts CHANGED
@@ -2969,6 +2969,146 @@ declare class SubdocMessage extends OutgoingMessage {
2969
2969
  get(args: Partial<AbracadabraOutgoingMessageArguments>): Encoder;
2970
2970
  }
2971
2971
  //#endregion
2972
+ //#region packages/provider/src/NodeIdentity.d.ts
2973
+ /**
2974
+ * NodeIdentity — Ed25519 identity helpers for Node-side consumers.
2975
+ *
2976
+ * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
2977
+ * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
2978
+ * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
2979
+ * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
2980
+ * the same challenge → sign → verify flow exposed by
2981
+ * {@link AbracadabraClient.loginWithKey}.
2982
+ *
2983
+ * Every one of those packages previously vendored a near-identical `crypto.ts`
2984
+ * (key-file load/create + `signChallenge`) plus a copy-pasted
2985
+ * "login → register-on-404 → re-login" block. These helpers are the single
2986
+ * shared home for both.
2987
+ *
2988
+ * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
2989
+ * touches the filesystem, and it does so via dynamic `import("node:…")` so this
2990
+ * module stays importable from browser bundles (the fs path simply isn't
2991
+ * reachable there).
2992
+ */
2993
+ /** A raw Node Ed25519 identity: 32-byte seed + base64url public key. */
2994
+ interface NodeKeypair {
2995
+ /** 32-byte Ed25519 private-key seed. */
2996
+ privateKey: Uint8Array;
2997
+ /** base64url-encoded 32-byte Ed25519 public key. */
2998
+ publicKeyB64: string;
2999
+ }
3000
+ /** Options for {@link loadOrCreateKeyFile}. */
3001
+ interface LoadKeyFileOptions {
3002
+ /**
3003
+ * File name under `~/.abracadabra/` used when `keyPath` is not given.
3004
+ * Lets each consumer keep its own identity slot (e.g. `"cli.key"`,
3005
+ * `"agent.key"`). Defaults to `"identity.key"`.
3006
+ */
3007
+ defaultFileName?: string;
3008
+ /** Invoked once when a brand-new key is generated (for logging). */
3009
+ onCreate?: (info: {
3010
+ path: string;
3011
+ publicKeyB64: string;
3012
+ }) => void;
3013
+ }
3014
+ /** Minimal client surface needed by {@link loginOrRegisterWithKey}. */
3015
+ interface KeyAuthClient {
3016
+ loginWithKey(publicKey: string, signChallenge: (challenge: string) => Promise<string>): Promise<string>;
3017
+ registerWithKey(opts: {
3018
+ publicKey: string;
3019
+ username?: string;
3020
+ displayName?: string;
3021
+ deviceName?: string;
3022
+ inviteCode?: string;
3023
+ }): Promise<unknown>;
3024
+ }
3025
+ /** Options for {@link loginOrRegisterWithKey}. */
3026
+ interface LoginOrRegisterOptions {
3027
+ /**
3028
+ * Account username. Defaults to a slug of `displayName`
3029
+ * (`/\s+/g → "-"`, lowercased) when omitted.
3030
+ */
3031
+ username?: string;
3032
+ displayName?: string;
3033
+ deviceName?: string;
3034
+ inviteCode?: string;
3035
+ /** Invoked right before auto-registering on first run (for logging). */
3036
+ onRegister?: () => void;
3037
+ }
3038
+ /**
3039
+ * Sign a base64url server challenge with a 32-byte Ed25519 seed.
3040
+ * Returns a base64url signature suitable for
3041
+ * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
3042
+ */
3043
+ declare function signChallengeWithSeed(challengeB64: string, seed: Uint8Array): string;
3044
+ /**
3045
+ * Build the async `signChallenge` callback that
3046
+ * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
3047
+ * returned function around to re-authenticate after a JWT expires.
3048
+ */
3049
+ declare function makeChallengeSigner(keypair: NodeKeypair): (challenge: string) => Promise<string>;
3050
+ /**
3051
+ * Derive a deterministic keypair from a seed string: the same input always
3052
+ * yields the same on-server identity. Used by `@abraca/orchestrator` so a named
3053
+ * actor maps to one reproducible account across runs.
3054
+ *
3055
+ * @param salt domain-separation suffix (default `"orchestrator-salt"`, the
3056
+ * historical value — change only if you intend a different identity space).
3057
+ */
3058
+ declare function deterministicKeypair(seed: string, salt?: string): NodeKeypair;
3059
+ /**
3060
+ * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
3061
+ * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
3062
+ * `~/.abracadabra/<defaultFileName>`.
3063
+ *
3064
+ * Node-only: filesystem modules are loaded via dynamic import, so importing
3065
+ * this symbol in a browser bundle is safe — only *calling* it requires Node.
3066
+ */
3067
+ declare function loadOrCreateKeyFile(keyPath?: string, opts?: LoadKeyFileOptions): Promise<NodeKeypair>;
3068
+ /**
3069
+ * Authenticate `keypair` against the server, auto-registering on first run.
3070
+ *
3071
+ * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
3072
+ * — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
3073
+ * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
3074
+ * Any other error propagates. Returns the JWT.
3075
+ *
3076
+ * This is the one shared implementation of the "login → register-on-404 →
3077
+ * re-login" dance previously copy-pasted into every Node consumer's connect().
3078
+ */
3079
+ declare function loginOrRegisterWithKey(client: KeyAuthClient, keypair: NodeKeypair, opts?: LoginOrRegisterOptions): Promise<string>;
3080
+ //#endregion
3081
+ //#region packages/provider/src/NodeConnect.d.ts
3082
+ /**
3083
+ * Open a fresh `AbracadabraProvider` bound to `docId` on `client` and wait for
3084
+ * its first sync. Returns the new `Y.Doc` + provider. Used for the root space
3085
+ * doc, child-space docs, and the inbox doc alike — every Node consumer opened
3086
+ * them with these exact options.
3087
+ *
3088
+ * Offline persistence is disabled (Node daemons/CLIs are online-only) and
3089
+ * subdocs load lazily.
3090
+ */
3091
+ declare function openSyncedProvider(opts: {
3092
+ client: AbracadabraClient;
3093
+ docId: string;
3094
+ syncTimeoutMs?: number;
3095
+ }): Promise<{
3096
+ doc: Y.Doc;
3097
+ provider: AbracadabraProvider;
3098
+ }>;
3099
+ /**
3100
+ * Pick the entry-point document from a server root's top-level children: the
3101
+ * first `Kind.Space`, falling back to the first top-level doc of any kind.
3102
+ * Returns `null` when the server has no top-level documents.
3103
+ *
3104
+ * `spaces` is returned alongside so callers that track the space list (most do)
3105
+ * don't have to re-filter.
3106
+ */
3107
+ declare function pickEntrySpace(roots: DocumentMeta[]): {
3108
+ entry: DocumentMeta | null;
3109
+ spaces: DocumentMeta[];
3110
+ };
3111
+ //#endregion
2972
3112
  //#region packages/provider/src/SearchIndex.d.ts
2973
3113
  declare class SearchIndex {
2974
3114
  private readonly origin;
@@ -3123,6 +3263,16 @@ declare class E2EAbracadabraProvider extends AbracadabraProvider {
3123
3263
  /** Quiescence debounce: reset on every update, fires the actual compaction. */
3124
3264
  private compactionDebounceTimer;
3125
3265
  private destroyed;
3266
+ /**
3267
+ * Plaintext local updates produced while this doc is not yet authenticated
3268
+ * on the connection. Unlike the plaintext provider, E2E does not convey
3269
+ * local state via SyncStep2 (it ships discrete encrypted update frames keyed
3270
+ * by server-assigned seq), so a pre-auth update that loses the AUTH race and
3271
+ * gets "not subscribed"-rejected would be lost. We queue them here and flush
3272
+ * (encrypt + send) once `authenticatedHandler` confirms the doc is
3273
+ * subscribed. Survives reconnects (only cleared on flush or destroy).
3274
+ */
3275
+ private _pendingPreAuthUpdates;
3126
3276
  constructor(configuration: E2EAbracadabraProviderConfiguration);
3127
3277
  /** Fetch the doc key from the server (requires WebAuthn if not cached). */
3128
3278
  private ensureDocKey;
@@ -3132,6 +3282,11 @@ declare class E2EAbracadabraProvider extends AbracadabraProvider {
3132
3282
  private _decryptAndApply;
3133
3283
  /** Encrypt local updates before sending over WebSocket. */
3134
3284
  documentUpdateHandler(update: Uint8Array, origin: unknown): void;
3285
+ /**
3286
+ * Flush updates buffered while unauthenticated once the server confirms the
3287
+ * doc is subscribed, then resume normal live sends.
3288
+ */
3289
+ authenticatedHandler(scope: string): void;
3135
3290
  private _encryptAndSend;
3136
3291
  /**
3137
3292
  * Force an immediate compaction attempt, bypassing the threshold and
@@ -5423,6 +5578,20 @@ declare function normalizeRootId(id: string | null | undefined, rootDocId: strin
5423
5578
  * Safely read a tree map value, converting Y.Map to plain object if needed.
5424
5579
  */
5425
5580
  declare function toPlain(val: unknown): unknown;
5581
+ /**
5582
+ * Read every entry of a `doc-tree` Y.Map into a flat {@link TreeEntry}[].
5583
+ *
5584
+ * Skips non-entry keys (e.g. `":updatedAt"` timestamps), and — when `selfId`
5585
+ * is given — the space root's own self-descriptor entry (keyed by the
5586
+ * connected root doc id, `parentId:null`, `order:-1`) so the space doesn't
5587
+ * render as a phantom first child of itself. Entry values are nested
5588
+ * `Y.Map`s, so each is resolved via {@link toPlain} (raw field access on a
5589
+ * Y.Map returns undefined).
5590
+ *
5591
+ * This is the single shared implementation; `@abraca/mcp`, `@abraca/cli`, and
5592
+ * `@abraca/resend` previously each carried a near-identical copy.
5593
+ */
5594
+ declare function readEntries(treeMap: Y.Map<unknown>, selfId?: string | null): TreeEntry[];
5426
5595
  /**
5427
5596
  * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
5428
5597
  * re-created key (create / duplicate / restore) where no concurrent
@@ -5493,4 +5662,4 @@ declare function collectMediaFileBlocks(root: Y.XmlFragment | Y.XmlElement): Med
5493
5662
  */
5494
5663
  declare function reconcileDocCover(treeMap: Y.Map<unknown>, docId: string, fragment: Y.XmlFragment | Y.XmlElement): void;
5495
5664
  //#endregion
5496
- export { AbracadabraBaseProvider, AbracadabraBaseProviderConfiguration, AbracadabraClient, AbracadabraClientConfig, AbracadabraOutgoingMessageArguments, AbracadabraProvider, AbracadabraProviderConfiguration, AbracadabraWS, AbracadabraWSConfiguration, AbracadabraWebRTC, type AbracadabraWebRTCConfiguration, AbracadabraWebSocketConn, AdminConfigField, AdminConfigOriginKind, AuditLogEntry, AuditQueryOpts, AuditVerifyResult, AuthFailureContext, AuthFailureReason, AuthMessageType, AuthorizedScope, AwarenessError, BackgroundSyncManager, type BackgroundSyncManagerOptions, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, type ChatChannel, ChatClient, type ChatClientTransport, type MarkReadInput as ChatMarkReadInput, type ChatMessage, type ChatReadCursor, type ChatReadReceipt, type ChatTypingEvent, type ChildrenPage, CloseEvent, CompleteAbracadabraBaseProviderConfiguration, CompleteAbracadabraWSConfiguration, CompleteHocuspocusProviderConfiguration, CompleteHocuspocusProviderWebsocketConfiguration, ConnectionTimeout, Constructable, ConstructableOutgoingMessage, ContentManager, type CreateNotificationInput, CryptoIdentity, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, type DeleteMessageInput, DevicePairingChannel, type DevicePairingConfig, DeviceRegistrationService, type DeviceServerStatus, type DeviceSessionRecord, type DeviceSessionStorage, type DeviceTier, type DocEncryptionInfo, DocKeyManager, DocSearchHit, type DocSyncState, type DocSyncStatus, type DocumentBlock, DocumentCache, type DocumentCacheOptions, type DocumentContent, DocumentManager, type DocumentManagerConfig, DocumentMeta, type DocumentMetaInfo, type DocumentMetaWire, E2EAbracadabraProvider, E2EEChannel, type E2EEIdentity, E2EOfflineStore, type EditMessageInput, EffectivePermissionEntry, EffectivePermissionsResponse, EffectiveRole, EncryptedChatClient, EncryptedYMap, EncryptedYText, EnvSnapshotExtension, EnvSnapshotItem, EnvSnapshotResponse, type FetchInboxInput, type FetchNotificationsInput, FileBlobStore, FileTransferChannel, FileTransferHandle, type FileTransferMeta, type FileTransferStatus, type FoldedMessage, Forbidden, GEO_TYPE_META_SCHEMAS, type GetChatHistoryInput, HealthStatus, HocusPocusWebSocket, HocuspocusProvider, HocuspocusProviderConfiguration, HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration, HocuspocusWebSocket, type IdentityDeviceEntry, type IdentityDocConfiguration, IdentityDocProvider, type IdentityProfile, type IdentityServerEntry, type IdentitySpaceEntry, type InboxEntry, type MarkReadInput$1 as InboxMarkReadInput, InviteRow, KEY_EXCHANGE_CHANNEL, Kind, LocalStorageDeviceSessionStorage, ManualSignaling, type ManualSignalingBlob, type MediaFileBlock, type MessageRecord, MessageTooBig, MessageType, MetaFieldType, MetaManager, MetaValidationError, type NotificationReadUpdate, type NotificationRecord, NotificationsClient, OfflineStore, OutgoingMessageArguments, OutgoingMessageInterface, PAGE_TYPES, PageMeta, PageTypeInfo, PageTypeMetaField, type PairingRequest, type PairingResult, PeerConnection, type PeerInfo, type PeerState, PendingSubdoc, PermissionEntry, PublicKeyInfo, QUERY_PREFIX, QueryClient, QueryError, type QueryFrame, type QueryKind, type QuerySpec, type QuerySubscriptionHandle, type QuerySubscriptionHandlers, type QueryTransport, RPC_PREFIX, ReadyzStatus, ResetConnection, type RpcCallHandle, type RpcCallOptions, RpcClient, RpcError, type RpcErrorCode, type RpcErrorPayload, type RpcFrame, type RpcHandler, type RpcHandlerContext, type RpcKind, type RpcTarget, type RpcTransport, SERVER_ROOT_ID, type SchemaDocTypeName, type SchemaMetaOf, type SchemaRegistryLike, type SchemaValidatorLike, SearchIndex, SearchResult, type SendChatMessageInput, type SendMessageInput, type SendMessageResult, ServerInfo, type SignalingIncoming, type SignalingOutgoing, SignalingSocket, SnapshotCreateResult, SnapshotData, SnapshotFileEntry, SnapshotForkResult, SnapshotMeta, SnapshotRestoreResult, StatesArray, SubdocMessage, SubdocRegisteredEvent, TYPE_ALIASES, TokenManager, type TokenManagerOptions, TreeEntry, TreeManager, TreeNode, TreeSearchResult, TypedDocTypeMismatchError, type TypedDocsClient, type TypedTreeEntry, Unauthorized, UploadInfo, UploadMeta, UploadQueueEntry, UploadQueueStatus, UserMetaField, UserProfile, WebSocketStatus, WsReadyStates, YjsDataChannel, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, deriveIdentityDocId, deriveSeedWrappingKey, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, onAuthenticatedParameters, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onCompactedParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onReconnectedParameters, onServerErrorParameters, onStatelessParameters, onStatusParameters, onSubdocLoadedParameters, onSubdocRegisteredParameters, onSyncedParameters, onUnsyncedChangesParameters, parseFrontmatter, patchEntry, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, reconcileDocCover, recordFromYAny, resolvePageType, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
5665
+ export { AbracadabraBaseProvider, AbracadabraBaseProviderConfiguration, AbracadabraClient, AbracadabraClientConfig, AbracadabraOutgoingMessageArguments, AbracadabraProvider, AbracadabraProviderConfiguration, AbracadabraWS, AbracadabraWSConfiguration, AbracadabraWebRTC, type AbracadabraWebRTCConfiguration, AbracadabraWebSocketConn, AdminConfigField, AdminConfigOriginKind, AuditLogEntry, AuditQueryOpts, AuditVerifyResult, AuthFailureContext, AuthFailureReason, AuthMessageType, AuthorizedScope, AwarenessError, BackgroundSyncManager, type BackgroundSyncManagerOptions, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, type ChatChannel, ChatClient, type ChatClientTransport, type MarkReadInput as ChatMarkReadInput, type ChatMessage, type ChatReadCursor, type ChatReadReceipt, type ChatTypingEvent, type ChildrenPage, CloseEvent, CompleteAbracadabraBaseProviderConfiguration, CompleteAbracadabraWSConfiguration, CompleteHocuspocusProviderConfiguration, CompleteHocuspocusProviderWebsocketConfiguration, ConnectionTimeout, Constructable, ConstructableOutgoingMessage, ContentManager, type CreateNotificationInput, CryptoIdentity, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, type DeleteMessageInput, DevicePairingChannel, type DevicePairingConfig, DeviceRegistrationService, type DeviceServerStatus, type DeviceSessionRecord, type DeviceSessionStorage, type DeviceTier, type DocEncryptionInfo, DocKeyManager, DocSearchHit, type DocSyncState, type DocSyncStatus, type DocumentBlock, DocumentCache, type DocumentCacheOptions, type DocumentContent, DocumentManager, type DocumentManagerConfig, DocumentMeta, type DocumentMetaInfo, type DocumentMetaWire, E2EAbracadabraProvider, E2EEChannel, type E2EEIdentity, E2EOfflineStore, type EditMessageInput, EffectivePermissionEntry, EffectivePermissionsResponse, EffectiveRole, EncryptedChatClient, EncryptedYMap, EncryptedYText, EnvSnapshotExtension, EnvSnapshotItem, EnvSnapshotResponse, type FetchInboxInput, type FetchNotificationsInput, FileBlobStore, FileTransferChannel, FileTransferHandle, type FileTransferMeta, type FileTransferStatus, type FoldedMessage, Forbidden, GEO_TYPE_META_SCHEMAS, type GetChatHistoryInput, HealthStatus, HocusPocusWebSocket, HocuspocusProvider, HocuspocusProviderConfiguration, HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration, HocuspocusWebSocket, type IdentityDeviceEntry, type IdentityDocConfiguration, IdentityDocProvider, type IdentityProfile, type IdentityServerEntry, type IdentitySpaceEntry, type InboxEntry, type MarkReadInput$1 as InboxMarkReadInput, InviteRow, KEY_EXCHANGE_CHANNEL, type KeyAuthClient, Kind, type LoadKeyFileOptions, LocalStorageDeviceSessionStorage, type LoginOrRegisterOptions, ManualSignaling, type ManualSignalingBlob, type MediaFileBlock, type MessageRecord, MessageTooBig, MessageType, MetaFieldType, MetaManager, MetaValidationError, type NodeKeypair, type NotificationReadUpdate, type NotificationRecord, NotificationsClient, OfflineStore, OutgoingMessageArguments, OutgoingMessageInterface, PAGE_TYPES, PageMeta, PageTypeInfo, PageTypeMetaField, type PairingRequest, type PairingResult, PeerConnection, type PeerInfo, type PeerState, PendingSubdoc, PermissionEntry, PublicKeyInfo, QUERY_PREFIX, QueryClient, QueryError, type QueryFrame, type QueryKind, type QuerySpec, type QuerySubscriptionHandle, type QuerySubscriptionHandlers, type QueryTransport, RPC_PREFIX, ReadyzStatus, ResetConnection, type RpcCallHandle, type RpcCallOptions, RpcClient, RpcError, type RpcErrorCode, type RpcErrorPayload, type RpcFrame, type RpcHandler, type RpcHandlerContext, type RpcKind, type RpcTarget, type RpcTransport, SERVER_ROOT_ID, type SchemaDocTypeName, type SchemaMetaOf, type SchemaRegistryLike, type SchemaValidatorLike, SearchIndex, SearchResult, type SendChatMessageInput, type SendMessageInput, type SendMessageResult, ServerInfo, type SignalingIncoming, type SignalingOutgoing, SignalingSocket, SnapshotCreateResult, SnapshotData, SnapshotFileEntry, SnapshotForkResult, SnapshotMeta, SnapshotRestoreResult, StatesArray, SubdocMessage, SubdocRegisteredEvent, TYPE_ALIASES, TokenManager, type TokenManagerOptions, TreeEntry, TreeManager, TreeNode, TreeSearchResult, TypedDocTypeMismatchError, type TypedDocsClient, type TypedTreeEntry, Unauthorized, UploadInfo, UploadMeta, UploadQueueEntry, UploadQueueStatus, UserMetaField, UserProfile, WebSocketStatus, WsReadyStates, YjsDataChannel, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, loadOrCreateKeyFile, loginOrRegisterWithKey, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, onAuthenticatedParameters, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onCompactedParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onReconnectedParameters, onServerErrorParameters, onStatelessParameters, onStatusParameters, onSubdocLoadedParameters, onSubdocRegisteredParameters, onSyncedParameters, onUnsyncedChangesParameters, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, resolvePageType, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/dabra",
3
- "version": "2.34.0",
3
+ "version": "2.35.1",
4
4
  "description": "abracadabra provider",
5
5
  "keywords": [
6
6
  "abracadabra",
@@ -41,7 +41,7 @@
41
41
  "yjs": "^13.6.8"
42
42
  },
43
43
  "devDependencies": {
44
- "@abraca/schema": "2.34.0"
44
+ "@abraca/schema": "2.35.1"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -414,11 +414,33 @@ export class AbracadabraBaseProvider extends EventEmitter {
414
414
  return;
415
415
  }
416
416
 
417
+ // Don't push live updates over a connection that hasn't authenticated this
418
+ // document yet. On the shared multiplexed socket, onOpen() does
419
+ // `await sendToken()` before the doc's AUTH frame actually goes out; an edit
420
+ // firing in that async window would race ahead of the AUTH frame and the
421
+ // server rejects it with "not subscribed: send AUTH for this document
422
+ // first". State is NOT lost: subclasses persist to the offline store before
423
+ // calling super (and re-flush pending updates on `synced`), and the
424
+ // post-AUTH SyncStep1/2 handshake conveys all local state regardless. So
425
+ // skipping the live wire-send here is safe — it only closes the race.
426
+ if (!this.isAuthenticated) {
427
+ return;
428
+ }
429
+
417
430
  this.incrementUnsyncedChanges();
418
431
  this.send(UpdateMessage, { update, documentName: this.configuration.name });
419
432
  }
420
433
 
421
434
  awarenessUpdateHandler({ added, updated, removed }: any, origin: any) {
435
+ // Same AUTH-ordering guard as documentUpdateHandler. Awareness churn
436
+ // (cursor / presence / focus) during the connect AUTH window must not race
437
+ // ahead of the doc's AUTH frame. Awareness is ephemeral and re-sent in full
438
+ // by startSync() immediately after AUTH plus on the next local change, so
439
+ // dropping pre-auth awareness frames loses nothing.
440
+ if (!this.isAuthenticated) {
441
+ return;
442
+ }
443
+
422
444
  const changedClients = added.concat(updated).concat(removed);
423
445
 
424
446
  this.send(AwarenessMessage, {
package/src/DocUtils.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  * `mcp/src/server.ts`, `cli/src/connection.ts`, and `mcp/src/tools/tree.ts`.
6
6
  */
7
7
  import * as Y from "yjs";
8
+ import type { PageMeta, TreeEntry } from "./DocTypes.ts";
8
9
 
9
10
  /**
10
11
  * Wait for a provider's `synced` event with a timeout.
@@ -29,6 +30,9 @@ export function waitForSync(
29
30
 
30
31
  function handler() {
31
32
  clearTimeout(timer);
33
+ // Detach so a one-shot `waitForSync` never leaves a dangling
34
+ // `synced` listener on a long-lived provider.
35
+ provider.off("synced", handler);
32
36
  resolve();
33
37
  }
34
38
 
@@ -88,6 +92,43 @@ export function toPlain(val: unknown): unknown {
88
92
  return val instanceof Y.Map ? val.toJSON() : val;
89
93
  }
90
94
 
95
+ /**
96
+ * Read every entry of a `doc-tree` Y.Map into a flat {@link TreeEntry}[].
97
+ *
98
+ * Skips non-entry keys (e.g. `":updatedAt"` timestamps), and — when `selfId`
99
+ * is given — the space root's own self-descriptor entry (keyed by the
100
+ * connected root doc id, `parentId:null`, `order:-1`) so the space doesn't
101
+ * render as a phantom first child of itself. Entry values are nested
102
+ * `Y.Map`s, so each is resolved via {@link toPlain} (raw field access on a
103
+ * Y.Map returns undefined).
104
+ *
105
+ * This is the single shared implementation; `@abraca/mcp`, `@abraca/cli`, and
106
+ * `@abraca/resend` previously each carried a near-identical copy.
107
+ */
108
+ export function readEntries(
109
+ treeMap: Y.Map<unknown>,
110
+ selfId?: string | null,
111
+ ): TreeEntry[] {
112
+ const entries: TreeEntry[] = [];
113
+ treeMap.forEach((raw, id) => {
114
+ if (selfId && id === selfId) return;
115
+ const value = toPlain(raw);
116
+ if (typeof value !== "object" || value === null) return;
117
+ const v = value as Record<string, unknown>;
118
+ entries.push({
119
+ id,
120
+ label: typeof v.label === "string" && v.label ? v.label : "Untitled",
121
+ parentId: (v.parentId as string | null) ?? null,
122
+ order: typeof v.order === "number" ? v.order : 0,
123
+ type: typeof v.type === "string" ? v.type : undefined,
124
+ meta: v.meta as PageMeta | undefined,
125
+ createdAt: typeof v.createdAt === "number" ? v.createdAt : undefined,
126
+ updatedAt: typeof v.updatedAt === "number" ? v.updatedAt : undefined,
127
+ });
128
+ });
129
+ return entries;
130
+ }
131
+
91
132
  /**
92
133
  * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
93
134
  * re-created key (create / duplicate / restore) where no concurrent
@@ -110,6 +110,16 @@ export class E2EAbracadabraProvider extends AbracadabraProvider {
110
110
  /** Quiescence debounce: reset on every update, fires the actual compaction. */
111
111
  private compactionDebounceTimer: ReturnType<typeof setTimeout> | null = null;
112
112
  private destroyed = false;
113
+ /**
114
+ * Plaintext local updates produced while this doc is not yet authenticated
115
+ * on the connection. Unlike the plaintext provider, E2E does not convey
116
+ * local state via SyncStep2 (it ships discrete encrypted update frames keyed
117
+ * by server-assigned seq), so a pre-auth update that loses the AUTH race and
118
+ * gets "not subscribed"-rejected would be lost. We queue them here and flush
119
+ * (encrypt + send) once `authenticatedHandler` confirms the doc is
120
+ * subscribed. Survives reconnects (only cleared on flush or destroy).
121
+ */
122
+ private _pendingPreAuthUpdates: Uint8Array[] = [];
113
123
 
114
124
  constructor(configuration: E2EAbracadabraProviderConfiguration) {
115
125
  // Disable the parent's offline store — E2E uses its own encrypted store.
@@ -245,12 +255,39 @@ export class E2EAbracadabraProvider extends AbracadabraProvider {
245
255
  /** Encrypt local updates before sending over WebSocket. */
246
256
  override documentUpdateHandler(update: Uint8Array, origin: unknown): void {
247
257
  if (origin === this) return;
258
+
259
+ // AUTH-ordering guard (see _pendingPreAuthUpdates): until the doc is
260
+ // authenticated on the connection, an encrypted update would race ahead
261
+ // of the AUTH frame on the shared multiplexed socket and be rejected with
262
+ // "not subscribed". Queue it and flush on authenticatedHandler instead of
263
+ // racing (and losing) it.
264
+ if (!this.isAuthenticated) {
265
+ this._pendingPreAuthUpdates.push(update);
266
+ return;
267
+ }
268
+
248
269
  // Don't call super (which would send plaintext); encrypt first
249
270
  this._encryptAndSend(update).catch((e) => {
250
271
  console.error("[E2EAbracadabraProvider] failed to encrypt update:", e);
251
272
  });
252
273
  }
253
274
 
275
+ /**
276
+ * Flush updates buffered while unauthenticated once the server confirms the
277
+ * doc is subscribed, then resume normal live sends.
278
+ */
279
+ override authenticatedHandler(scope: string): void {
280
+ super.authenticatedHandler(scope);
281
+ if (this._pendingPreAuthUpdates.length === 0) return;
282
+ const pending = this._pendingPreAuthUpdates;
283
+ this._pendingPreAuthUpdates = [];
284
+ for (const update of pending) {
285
+ this._encryptAndSend(update).catch((e) => {
286
+ console.error("[E2EAbracadabraProvider] failed to flush pre-auth update:", e);
287
+ });
288
+ }
289
+ }
290
+
254
291
  private async _encryptAndSend(update: Uint8Array): Promise<void> {
255
292
  const key = await this.ensureDocKey();
256
293
  if (!key) {
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Node connection helpers — shared bootstrap primitives for the Node consumers
3
+ * (`@abraca/mcp`, `@abraca/cli`, `@abraca/orchestrator`, `@abraca/resend`).
4
+ *
5
+ * Each of those packages opened a synced root/space/inbox provider with the
6
+ * exact same incantation (`new Y.Doc({ guid }) → new AbracadabraProvider({
7
+ * disableOfflineStore, subdocLoading:'lazy' }) → waitForSync`) and selected the
8
+ * entry space with the same "first Kind.Space, else first top-level doc" rule.
9
+ * Both live here now so there is one implementation.
10
+ *
11
+ * These are deliberately small, faithful extractions — they do NOT own auth
12
+ * (see {@link loginOrRegisterWithKey}), awareness, child-provider caching, or
13
+ * the reconnect/heal loop. Those stay with each consumer.
14
+ */
15
+
16
+ import * as Y from "yjs";
17
+ import { AbracadabraProvider } from "./AbracadabraProvider.ts";
18
+ import { AbracadabraClient } from "./AbracadabraClient.ts";
19
+ import { waitForSync } from "./DocUtils.ts";
20
+ import { Kind } from "./types.ts";
21
+ import type { DocumentMeta } from "./types.ts";
22
+
23
+ /**
24
+ * Open a fresh `AbracadabraProvider` bound to `docId` on `client` and wait for
25
+ * its first sync. Returns the new `Y.Doc` + provider. Used for the root space
26
+ * doc, child-space docs, and the inbox doc alike — every Node consumer opened
27
+ * them with these exact options.
28
+ *
29
+ * Offline persistence is disabled (Node daemons/CLIs are online-only) and
30
+ * subdocs load lazily.
31
+ */
32
+ export async function openSyncedProvider(opts: {
33
+ client: AbracadabraClient;
34
+ docId: string;
35
+ syncTimeoutMs?: number;
36
+ }): Promise<{ doc: Y.Doc; provider: AbracadabraProvider }> {
37
+ const doc = new Y.Doc({ guid: opts.docId });
38
+ const provider = new AbracadabraProvider({
39
+ name: opts.docId,
40
+ document: doc,
41
+ client: opts.client,
42
+ disableOfflineStore: true,
43
+ subdocLoading: "lazy",
44
+ });
45
+ await waitForSync(provider, opts.syncTimeoutMs);
46
+ return { doc, provider };
47
+ }
48
+
49
+ /**
50
+ * Pick the entry-point document from a server root's top-level children: the
51
+ * first `Kind.Space`, falling back to the first top-level doc of any kind.
52
+ * Returns `null` when the server has no top-level documents.
53
+ *
54
+ * `spaces` is returned alongside so callers that track the space list (most do)
55
+ * don't have to re-filter.
56
+ */
57
+ export function pickEntrySpace(roots: DocumentMeta[]): {
58
+ entry: DocumentMeta | null;
59
+ spaces: DocumentMeta[];
60
+ } {
61
+ const spaces = roots.filter((d) => d.kind === Kind.Space);
62
+ return { entry: spaces[0] ?? roots[0] ?? null, spaces };
63
+ }