@abraca/dabra 2.33.0 → 2.35.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.
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;
@@ -5423,6 +5563,20 @@ declare function normalizeRootId(id: string | null | undefined, rootDocId: strin
5423
5563
  * Safely read a tree map value, converting Y.Map to plain object if needed.
5424
5564
  */
5425
5565
  declare function toPlain(val: unknown): unknown;
5566
+ /**
5567
+ * Read every entry of a `doc-tree` Y.Map into a flat {@link TreeEntry}[].
5568
+ *
5569
+ * Skips non-entry keys (e.g. `":updatedAt"` timestamps), and — when `selfId`
5570
+ * is given — the space root's own self-descriptor entry (keyed by the
5571
+ * connected root doc id, `parentId:null`, `order:-1`) so the space doesn't
5572
+ * render as a phantom first child of itself. Entry values are nested
5573
+ * `Y.Map`s, so each is resolved via {@link toPlain} (raw field access on a
5574
+ * Y.Map returns undefined).
5575
+ *
5576
+ * This is the single shared implementation; `@abraca/mcp`, `@abraca/cli`, and
5577
+ * `@abraca/resend` previously each carried a near-identical copy.
5578
+ */
5579
+ declare function readEntries(treeMap: Y.Map<unknown>, selfId?: string | null): TreeEntry[];
5426
5580
  /**
5427
5581
  * Build a tree/trash entry as a nested `Y.Map`. Use for a brand-new or
5428
5582
  * re-created key (create / duplicate / restore) where no concurrent
@@ -5493,4 +5647,4 @@ declare function collectMediaFileBlocks(root: Y.XmlFragment | Y.XmlElement): Med
5493
5647
  */
5494
5648
  declare function reconcileDocCover(treeMap: Y.Map<unknown>, docId: string, fragment: Y.XmlFragment | Y.XmlElement): void;
5495
5649
  //#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 };
5650
+ 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.33.0",
3
+ "version": "2.35.0",
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.33.0"
44
+ "@abraca/schema": "2.35.0"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
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
@@ -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
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * NodeIdentity — Ed25519 identity helpers for Node-side consumers.
3
+ *
4
+ * The browser identity story lives in {@link CryptoIdentityKeystore} (WebAuthn
5
+ * PRF + IndexedDB). Node CLIs and daemons (`@abraca/mcp`, `@abraca/cli`,
6
+ * `@abraca/orchestrator`, `@abraca/resend`, `@abraca/wiki`) instead use a raw
7
+ * 32-byte Ed25519 seed kept in a key file, and authenticate to the server with
8
+ * the same challenge → sign → verify flow exposed by
9
+ * {@link AbracadabraClient.loginWithKey}.
10
+ *
11
+ * Every one of those packages previously vendored a near-identical `crypto.ts`
12
+ * (key-file load/create + `signChallenge`) plus a copy-pasted
13
+ * "login → register-on-404 → re-login" block. These helpers are the single
14
+ * shared home for both.
15
+ *
16
+ * The signing helpers are environment-agnostic. Only {@link loadOrCreateKeyFile}
17
+ * touches the filesystem, and it does so via dynamic `import("node:…")` so this
18
+ * module stays importable from browser bundles (the fs path simply isn't
19
+ * reachable there).
20
+ */
21
+
22
+ import * as ed from "@noble/ed25519";
23
+ import { sha512 } from "@noble/hashes/sha2.js";
24
+
25
+ // @noble/ed25519 v3: wire sha512 for the sync sign/getPublicKey paths and an
26
+ // async hook for *Async variants. Idempotent with the same assignment in
27
+ // CryptoIdentityKeystore / MnemonicKeyDerivation — whichever module loads first
28
+ // wins, and the value is identical.
29
+ ed.hashes.sha512 = sha512;
30
+ ed.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));
31
+
32
+ // ── base64url (browser-safe; mirrors CryptoIdentityKeystore) ─────────────────
33
+
34
+ function toBase64url(bytes: Uint8Array): string {
35
+ return btoa(String.fromCharCode(...bytes))
36
+ .replace(/\+/g, "-")
37
+ .replace(/\//g, "_")
38
+ .replace(/=/g, "");
39
+ }
40
+
41
+ function fromBase64url(b64: string): Uint8Array {
42
+ const padded = b64.replace(/-/g, "+").replace(/_/g, "/");
43
+ const padLen = (4 - (padded.length % 4)) % 4;
44
+ return Uint8Array.from(atob(padded + "=".repeat(padLen)), (c) =>
45
+ c.charCodeAt(0),
46
+ );
47
+ }
48
+
49
+ // ── Types ────────────────────────────────────────────────────────────────────
50
+
51
+ /** A raw Node Ed25519 identity: 32-byte seed + base64url public key. */
52
+ export interface NodeKeypair {
53
+ /** 32-byte Ed25519 private-key seed. */
54
+ privateKey: Uint8Array;
55
+ /** base64url-encoded 32-byte Ed25519 public key. */
56
+ publicKeyB64: string;
57
+ }
58
+
59
+ /** Options for {@link loadOrCreateKeyFile}. */
60
+ export interface LoadKeyFileOptions {
61
+ /**
62
+ * File name under `~/.abracadabra/` used when `keyPath` is not given.
63
+ * Lets each consumer keep its own identity slot (e.g. `"cli.key"`,
64
+ * `"agent.key"`). Defaults to `"identity.key"`.
65
+ */
66
+ defaultFileName?: string;
67
+ /** Invoked once when a brand-new key is generated (for logging). */
68
+ onCreate?: (info: { path: string; publicKeyB64: string }) => void;
69
+ }
70
+
71
+ /** Minimal client surface needed by {@link loginOrRegisterWithKey}. */
72
+ export interface KeyAuthClient {
73
+ loginWithKey(
74
+ publicKey: string,
75
+ signChallenge: (challenge: string) => Promise<string>,
76
+ ): Promise<string>;
77
+ registerWithKey(opts: {
78
+ publicKey: string;
79
+ username?: string;
80
+ displayName?: string;
81
+ deviceName?: string;
82
+ inviteCode?: string;
83
+ }): Promise<unknown>;
84
+ }
85
+
86
+ /** Options for {@link loginOrRegisterWithKey}. */
87
+ export interface LoginOrRegisterOptions {
88
+ /**
89
+ * Account username. Defaults to a slug of `displayName`
90
+ * (`/\s+/g → "-"`, lowercased) when omitted.
91
+ */
92
+ username?: string;
93
+ displayName?: string;
94
+ deviceName?: string;
95
+ inviteCode?: string;
96
+ /** Invoked right before auto-registering on first run (for logging). */
97
+ onRegister?: () => void;
98
+ }
99
+
100
+ // ── Signing ──────────────────────────────────────────────────────────────────
101
+
102
+ /**
103
+ * Sign a base64url server challenge with a 32-byte Ed25519 seed.
104
+ * Returns a base64url signature suitable for
105
+ * {@link AbracadabraClient.verify}. Synchronous (the sha512 hook is set above).
106
+ */
107
+ export function signChallengeWithSeed(
108
+ challengeB64: string,
109
+ seed: Uint8Array,
110
+ ): string {
111
+ return toBase64url(ed.sign(fromBase64url(challengeB64), seed));
112
+ }
113
+
114
+ /**
115
+ * Build the async `signChallenge` callback that
116
+ * {@link AbracadabraClient.loginWithKey} expects, bound to a keypair. Keep the
117
+ * returned function around to re-authenticate after a JWT expires.
118
+ */
119
+ export function makeChallengeSigner(
120
+ keypair: NodeKeypair,
121
+ ): (challenge: string) => Promise<string> {
122
+ return (challenge: string) =>
123
+ Promise.resolve(signChallengeWithSeed(challenge, keypair.privateKey));
124
+ }
125
+
126
+ /**
127
+ * Derive a deterministic keypair from a seed string: the same input always
128
+ * yields the same on-server identity. Used by `@abraca/orchestrator` so a named
129
+ * actor maps to one reproducible account across runs.
130
+ *
131
+ * @param salt domain-separation suffix (default `"orchestrator-salt"`, the
132
+ * historical value — change only if you intend a different identity space).
133
+ */
134
+ export function deterministicKeypair(
135
+ seed: string,
136
+ salt = "orchestrator-salt",
137
+ ): NodeKeypair {
138
+ const privateKey = sha512(
139
+ new TextEncoder().encode(`${seed}:${salt}`),
140
+ ).slice(0, 32);
141
+ return { privateKey, publicKeyB64: toBase64url(ed.getPublicKey(privateKey)) };
142
+ }
143
+
144
+ // ── Key file (Node only) ─────────────────────────────────────────────────────
145
+
146
+ /**
147
+ * Load an existing 32-byte Ed25519 seed from `keyPath`, or generate one and
148
+ * persist it with `0o600` (dir `0o700`). When `keyPath` is omitted the file is
149
+ * `~/.abracadabra/<defaultFileName>`.
150
+ *
151
+ * Node-only: filesystem modules are loaded via dynamic import, so importing
152
+ * this symbol in a browser bundle is safe — only *calling* it requires Node.
153
+ */
154
+ export async function loadOrCreateKeyFile(
155
+ keyPath?: string,
156
+ opts: LoadKeyFileOptions = {},
157
+ ): Promise<NodeKeypair> {
158
+ const { existsSync } = await import("node:fs");
159
+ const { readFile, writeFile, mkdir } = await import("node:fs/promises");
160
+ const { homedir } = await import("node:os");
161
+ const { join, dirname } = await import("node:path");
162
+
163
+ const path =
164
+ keyPath ??
165
+ join(homedir(), ".abracadabra", opts.defaultFileName ?? "identity.key");
166
+
167
+ if (existsSync(path)) {
168
+ const seed = await readFile(path);
169
+ if (seed.length !== 32) {
170
+ throw new Error(
171
+ `Invalid key file at ${path}: expected 32 bytes, got ${seed.length}`,
172
+ );
173
+ }
174
+ const privateKey = new Uint8Array(seed);
175
+ return {
176
+ privateKey,
177
+ publicKeyB64: toBase64url(ed.getPublicKey(privateKey)),
178
+ };
179
+ }
180
+
181
+ const privateKey = ed.utils.randomSecretKey();
182
+ const publicKeyB64 = toBase64url(ed.getPublicKey(privateKey));
183
+
184
+ const dir = dirname(path);
185
+ if (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });
186
+ await writeFile(path, privateKey, { mode: 0o600 });
187
+
188
+ opts.onCreate?.({ path, publicKeyB64 });
189
+ return { privateKey, publicKeyB64 };
190
+ }
191
+
192
+ // ── Login / register ─────────────────────────────────────────────────────────
193
+
194
+ /**
195
+ * Authenticate `keypair` against the server, auto-registering on first run.
196
+ *
197
+ * Tries {@link AbracadabraClient.loginWithKey}; if the key isn't registered yet
198
+ * — signalled by HTTP 404/422, or 401 with a "not registered / user not found"
199
+ * message — it calls {@link AbracadabraClient.registerWithKey} and re-logs in.
200
+ * Any other error propagates. Returns the JWT.
201
+ *
202
+ * This is the one shared implementation of the "login → register-on-404 →
203
+ * re-login" dance previously copy-pasted into every Node consumer's connect().
204
+ */
205
+ export async function loginOrRegisterWithKey(
206
+ client: KeyAuthClient,
207
+ keypair: NodeKeypair,
208
+ opts: LoginOrRegisterOptions = {},
209
+ ): Promise<string> {
210
+ const sign = makeChallengeSigner(keypair);
211
+ try {
212
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
213
+ } catch (err: unknown) {
214
+ const e = err as { status?: number; response?: { status?: number }; message?: string };
215
+ const status = e?.status ?? e?.response?.status;
216
+ const msg = String(e?.message ?? "").toLowerCase();
217
+ const notRegistered =
218
+ status === 404 ||
219
+ status === 422 ||
220
+ (status === 401 && /not registered|user not found|no such user/.test(msg));
221
+ if (!notRegistered) throw err;
222
+
223
+ opts.onRegister?.();
224
+ const username =
225
+ opts.username ??
226
+ (opts.displayName
227
+ ? opts.displayName.replace(/\s+/g, "-").toLowerCase()
228
+ : undefined);
229
+ await client.registerWithKey({
230
+ publicKey: keypair.publicKeyB64,
231
+ username,
232
+ displayName: opts.displayName,
233
+ deviceName: opts.deviceName,
234
+ inviteCode: opts.inviteCode,
235
+ });
236
+ return await client.loginWithKey(keypair.publicKeyB64, sign);
237
+ }
238
+ }
package/src/index.ts CHANGED
@@ -18,6 +18,20 @@ export * from "./CloseEvents.ts";
18
18
  export * from "./awarenessStatesToArray.ts";
19
19
  export { SubdocMessage } from "./OutgoingMessages/SubdocMessage.ts";
20
20
  export { CryptoIdentityKeystore } from "./CryptoIdentityKeystore.ts";
21
+ export {
22
+ signChallengeWithSeed,
23
+ makeChallengeSigner,
24
+ deterministicKeypair,
25
+ loadOrCreateKeyFile,
26
+ loginOrRegisterWithKey,
27
+ } from "./NodeIdentity.ts";
28
+ export type {
29
+ NodeKeypair,
30
+ LoadKeyFileOptions,
31
+ LoginOrRegisterOptions,
32
+ KeyAuthClient,
33
+ } from "./NodeIdentity.ts";
34
+ export { openSyncedProvider, pickEntrySpace } from "./NodeConnect.ts";
21
35
  export { DocumentCache } from "./DocumentCache.ts";
22
36
  export type { DocumentCacheOptions } from "./DocumentCache.ts";
23
37
  export { SearchIndex } from "./SearchIndex.ts";
@@ -153,6 +167,7 @@ export {
153
167
  withTimeout,
154
168
  normalizeRootId,
155
169
  toPlain,
170
+ readEntries,
156
171
  makeEntryMap,
157
172
  patchEntry,
158
173
  isPlaceholderLabel,