@abraca/dabra 2.38.0 → 2.40.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
@@ -3053,6 +3053,53 @@ interface KeyAuthClient {
3053
3053
  inviteCode?: string;
3054
3054
  }): Promise<unknown>;
3055
3055
  }
3056
+ /**
3057
+ * Wider client surface needed by {@link loginOrRegisterWithPolicy}: it probes
3058
+ * `serverInfo()` (unauthenticated) to decide the access policy and reads
3059
+ * `getMe()` after connecting to detect a read-only (un-promoted) role.
3060
+ */
3061
+ interface PolicyAuthClient extends KeyAuthClient {
3062
+ serverInfo(): Promise<{
3063
+ name?: string;
3064
+ registration_allowed?: boolean;
3065
+ invite_only?: boolean;
3066
+ access?: {
3067
+ authenticated?: string;
3068
+ };
3069
+ }>;
3070
+ getMe(): Promise<{
3071
+ role?: string;
3072
+ }>;
3073
+ }
3074
+ /**
3075
+ * Outcome of {@link loginOrRegisterWithPolicy}. A discriminated union so callers
3076
+ * (MCP `connect_server`, CLI `server login`) can render an actionable message.
3077
+ *
3078
+ * - `connected` — logged in (existing account) or registered (open server / valid
3079
+ * invite). `needsPromotion` is set when the account is read-only (`observer`),
3080
+ * so the caller can suggest an admin grant a write role to `publicKey`.
3081
+ * - `needs_invite` — server is invite-only, the key isn't registered, and no
3082
+ * invite code was supplied. Surface `publicKey` so an admin can authorize it by
3083
+ * hand if no token is available.
3084
+ * - `registration_closed` — open registration is disabled; only an admin can
3085
+ * provision the account. Surface `publicKey`.
3086
+ */
3087
+ type ConnectPolicyResult = {
3088
+ status: "connected";
3089
+ token: string;
3090
+ publicKey: string;
3091
+ serverName?: string;
3092
+ role?: string;
3093
+ needsPromotion: boolean;
3094
+ } | {
3095
+ status: "needs_invite";
3096
+ publicKey: string;
3097
+ serverName?: string;
3098
+ } | {
3099
+ status: "registration_closed";
3100
+ publicKey: string;
3101
+ serverName?: string;
3102
+ };
3056
3103
  /** Options for {@link loginOrRegisterWithKey}. */
3057
3104
  interface LoginOrRegisterOptions {
3058
3105
  /**
@@ -3108,6 +3155,25 @@ declare function loadOrCreateKeyFile(keyPath?: string, opts?: LoadKeyFileOptions
3108
3155
  * re-login" dance previously copy-pasted into every Node consumer's connect().
3109
3156
  */
3110
3157
  declare function loginOrRegisterWithKey(client: KeyAuthClient, keypair: NodeKeypair, opts?: LoginOrRegisterOptions): Promise<string>;
3158
+ /**
3159
+ * Like {@link loginOrRegisterWithKey}, but probes the server's access policy
3160
+ * first so an un-registered key produces an *actionable* result instead of a raw
3161
+ * register error. This is what lets a running agent say "this server is
3162
+ * invite-only — give me a token, or have an admin authorize my public key"
3163
+ * rather than failing opaquely.
3164
+ *
3165
+ * Flow:
3166
+ * 1. `serverInfo()` (unauthenticated) for the access policy + server name.
3167
+ * 2. Try `loginWithKey`. Success → fetch `getMe()` for the role → `connected`.
3168
+ * 3. On a "not registered" error, branch on the policy:
3169
+ * - an `inviteCode` was supplied → register with it (works for invite-only
3170
+ * and open servers) → re-login → `connected`.
3171
+ * - no code + `invite_only` → `needs_invite`.
3172
+ * - no code + `registration_allowed === false` → `registration_closed`.
3173
+ * - otherwise (open registration) → register without a code → `connected`.
3174
+ * 4. Any other login error propagates.
3175
+ */
3176
+ declare function loginOrRegisterWithPolicy(client: PolicyAuthClient, keypair: NodeKeypair, opts?: LoginOrRegisterOptions): Promise<ConnectPolicyResult>;
3111
3177
  //#endregion
3112
3178
  //#region packages/provider/src/NodeConnect.d.ts
3113
3179
  /**
@@ -3140,6 +3206,94 @@ declare function pickEntrySpace(roots: DocumentMeta[]): {
3140
3206
  spaces: DocumentMeta[];
3141
3207
  };
3142
3208
  //#endregion
3209
+ //#region packages/provider/src/ServerRegistry.d.ts
3210
+ /**
3211
+ * ServerRegistry — a tiny on-disk registry of Abracadabra servers shared by the
3212
+ * Node-side consumers (`@abraca/mcp`, `@abraca/cli`).
3213
+ *
3214
+ * Historically each daemon read a single `ABRA_URL` and a single key file, so it
3215
+ * could only ever talk to one server. The registry lets a user remember several
3216
+ * servers by alias, keep a per-server identity (key file), and switch between
3217
+ * them — both from the CLI (`server add/use/login`) and from a running MCP agent
3218
+ * (`connect_server`/`switch_server`).
3219
+ *
3220
+ * Format: JSON at `~/.abracadabra/servers.json` (override with `ABRA_SERVERS_FILE`):
3221
+ *
3222
+ * {
3223
+ * "defaultAlias": "coop",
3224
+ * "servers": {
3225
+ * "coop": { "alias": "coop", "url": "https://coop.cou.sh",
3226
+ * "keyFile": "/home/me/.abracadabra/keys/coop.key" }
3227
+ * }
3228
+ * }
3229
+ *
3230
+ * Node-only: filesystem access is via dynamic `import("node:…")`, so importing
3231
+ * this module from a browser bundle is safe — only *calling* the load/save
3232
+ * helpers requires Node.
3233
+ */
3234
+ /** A single remembered server. */
3235
+ interface ServerProfile {
3236
+ /** Short, unique handle used on the CLI / in MCP tools. */
3237
+ alias: string;
3238
+ /** Base URL, e.g. `https://coop.cou.sh`. */
3239
+ url: string;
3240
+ /** Path to this server's Ed25519 key file (per-server identity). */
3241
+ keyFile: string;
3242
+ /** Display name presented to the server (presence / registration). */
3243
+ displayName?: string;
3244
+ /** Presence color (HSL string). */
3245
+ color?: string;
3246
+ /** Invite/registration token, when the server is invite-only. */
3247
+ inviteCode?: string;
3248
+ }
3249
+ /** The whole registry: a map of profiles plus which alias is the default. */
3250
+ interface ServerRegistry {
3251
+ /** Alias used when no `--server` / `connect_server` target is given. */
3252
+ defaultAlias?: string;
3253
+ servers: Record<string, ServerProfile>;
3254
+ }
3255
+ /** Resolve the registry path: `ABRA_SERVERS_FILE` env, else `~/.abracadabra/servers.json`. */
3256
+ declare function serverRegistryPath(override?: string): Promise<string>;
3257
+ /** Default per-server key-file path: `~/.abracadabra/keys/<alias>.key`. */
3258
+ declare function defaultKeyFileFor(alias: string): Promise<string>;
3259
+ /**
3260
+ * Load the registry from disk. A missing file yields an empty registry (never
3261
+ * throws on absence). A malformed file throws so the caller can surface it.
3262
+ */
3263
+ declare function loadServerRegistry(path?: string): Promise<ServerRegistry>;
3264
+ /** Persist the registry, creating `~/.abracadabra/` with `0o700` if needed. */
3265
+ declare function saveServerRegistry(reg: ServerRegistry, path?: string): Promise<void>;
3266
+ /**
3267
+ * Resolve `aliasOrUrl` against the registry.
3268
+ *
3269
+ * - A known alias → its stored profile.
3270
+ * - A bare URL (starts with `http://` / `https://`) → an ephemeral profile with
3271
+ * a derived alias (the URL host) and a default per-host key file. This is NOT
3272
+ * persisted; the caller decides whether to `addServer` it.
3273
+ * - Anything else → `null` (unknown alias).
3274
+ */
3275
+ declare function resolveServer(reg: ServerRegistry, aliasOrUrl: string): Promise<ServerProfile | null>;
3276
+ /** Add or replace a profile. The first server added becomes the default. */
3277
+ declare function addServer(reg: ServerRegistry, profile: ServerProfile): ServerRegistry;
3278
+ /** Remove a profile by alias. Clears `defaultAlias` if it pointed at it. */
3279
+ declare function removeServer(reg: ServerRegistry, alias: string): ServerRegistry;
3280
+ /** Mark `alias` as the default. Throws if the alias is unknown. */
3281
+ declare function setDefault(reg: ServerRegistry, alias: string): ServerRegistry;
3282
+ /**
3283
+ * Seed a `default` profile from a legacy single-key setup when the registry is
3284
+ * empty. Existing MCP/CLI users keep `~/.abracadabra/{agent,cli}.key` and an
3285
+ * `ABRA_URL`; without this they'd lose their identity the first time the
3286
+ * registry takes over. Returns the (possibly unchanged) registry; the caller
3287
+ * persists if `migrated` is true.
3288
+ *
3289
+ * @param url the legacy `ABRA_URL` (no migration without it).
3290
+ * @param legacyKeyFile path to the legacy key (e.g. `~/.abracadabra/agent.key`).
3291
+ */
3292
+ declare function migrateLegacyDefault(reg: ServerRegistry, url: string | undefined, legacyKeyFile: string): Promise<{
3293
+ registry: ServerRegistry;
3294
+ migrated: boolean;
3295
+ }>;
3296
+ //#endregion
3143
3297
  //#region packages/provider/src/SearchIndex.d.ts
3144
3298
  declare class SearchIndex {
3145
3299
  private readonly origin;
@@ -5707,4 +5861,4 @@ declare function collectMediaFileBlocks(root: Y.XmlFragment | Y.XmlElement): Med
5707
5861
  */
5708
5862
  declare function reconcileDocCover(treeMap: Y.Map<unknown>, docId: string, fragment: Y.XmlFragment | Y.XmlElement): void;
5709
5863
  //#endregion
5710
- 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 };
5864
+ 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, type ConnectPolicyResult, 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, type PolicyAuthClient, 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 ServerProfile, type ServerRegistry, 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, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, 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, removeServer, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, 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.38.0",
3
+ "version": "2.40.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.38.0"
44
+ "@abraca/schema": "2.40.0"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -83,6 +83,46 @@ export interface KeyAuthClient {
83
83
  }): Promise<unknown>;
84
84
  }
85
85
 
86
+ /**
87
+ * Wider client surface needed by {@link loginOrRegisterWithPolicy}: it probes
88
+ * `serverInfo()` (unauthenticated) to decide the access policy and reads
89
+ * `getMe()` after connecting to detect a read-only (un-promoted) role.
90
+ */
91
+ export interface PolicyAuthClient extends KeyAuthClient {
92
+ serverInfo(): Promise<{
93
+ name?: string;
94
+ registration_allowed?: boolean;
95
+ invite_only?: boolean;
96
+ access?: { authenticated?: string };
97
+ }>;
98
+ getMe(): Promise<{ role?: string }>;
99
+ }
100
+
101
+ /**
102
+ * Outcome of {@link loginOrRegisterWithPolicy}. A discriminated union so callers
103
+ * (MCP `connect_server`, CLI `server login`) can render an actionable message.
104
+ *
105
+ * - `connected` — logged in (existing account) or registered (open server / valid
106
+ * invite). `needsPromotion` is set when the account is read-only (`observer`),
107
+ * so the caller can suggest an admin grant a write role to `publicKey`.
108
+ * - `needs_invite` — server is invite-only, the key isn't registered, and no
109
+ * invite code was supplied. Surface `publicKey` so an admin can authorize it by
110
+ * hand if no token is available.
111
+ * - `registration_closed` — open registration is disabled; only an admin can
112
+ * provision the account. Surface `publicKey`.
113
+ */
114
+ export type ConnectPolicyResult =
115
+ | {
116
+ status: "connected";
117
+ token: string;
118
+ publicKey: string;
119
+ serverName?: string;
120
+ role?: string;
121
+ needsPromotion: boolean;
122
+ }
123
+ | { status: "needs_invite"; publicKey: string; serverName?: string }
124
+ | { status: "registration_closed"; publicKey: string; serverName?: string };
125
+
86
126
  /** Options for {@link loginOrRegisterWithKey}. */
87
127
  export interface LoginOrRegisterOptions {
88
128
  /**
@@ -236,3 +276,103 @@ export async function loginOrRegisterWithKey(
236
276
  return await client.loginWithKey(keypair.publicKeyB64, sign);
237
277
  }
238
278
  }
279
+
280
+ /**
281
+ * Like {@link loginOrRegisterWithKey}, but probes the server's access policy
282
+ * first so an un-registered key produces an *actionable* result instead of a raw
283
+ * register error. This is what lets a running agent say "this server is
284
+ * invite-only — give me a token, or have an admin authorize my public key"
285
+ * rather than failing opaquely.
286
+ *
287
+ * Flow:
288
+ * 1. `serverInfo()` (unauthenticated) for the access policy + server name.
289
+ * 2. Try `loginWithKey`. Success → fetch `getMe()` for the role → `connected`.
290
+ * 3. On a "not registered" error, branch on the policy:
291
+ * - an `inviteCode` was supplied → register with it (works for invite-only
292
+ * and open servers) → re-login → `connected`.
293
+ * - no code + `invite_only` → `needs_invite`.
294
+ * - no code + `registration_allowed === false` → `registration_closed`.
295
+ * - otherwise (open registration) → register without a code → `connected`.
296
+ * 4. Any other login error propagates.
297
+ */
298
+ export async function loginOrRegisterWithPolicy(
299
+ client: PolicyAuthClient,
300
+ keypair: NodeKeypair,
301
+ opts: LoginOrRegisterOptions = {},
302
+ ): Promise<ConnectPolicyResult> {
303
+ const sign = makeChallengeSigner(keypair);
304
+ const publicKey = keypair.publicKeyB64;
305
+
306
+ // Best-effort policy probe — never fatal (older servers may omit fields).
307
+ let info: Awaited<ReturnType<PolicyAuthClient["serverInfo"]>> = {};
308
+ try {
309
+ info = await client.serverInfo();
310
+ } catch {
311
+ /* fall through with empty policy → behave like open/unknown */
312
+ }
313
+ const serverName = info.name;
314
+
315
+ const connected = async (token: string): Promise<ConnectPolicyResult> => {
316
+ let role: string | undefined;
317
+ try {
318
+ role = (await client.getMe()).role;
319
+ } catch {
320
+ /* role unknown — don't block the connection on it */
321
+ }
322
+ // A bare `observer` is the read-only floor: connected, but can't write
323
+ // until an admin promotes the key. `service`/`admin`/`owner`/`editor` are
324
+ // write-capable; `viewer` is intentionally read-only by grant, not a
325
+ // missing-promotion signal, so only flag `observer`.
326
+ const needsPromotion = role === "observer";
327
+ return {
328
+ status: "connected",
329
+ token,
330
+ publicKey,
331
+ serverName,
332
+ role,
333
+ needsPromotion,
334
+ };
335
+ };
336
+
337
+ try {
338
+ return await connected(await client.loginWithKey(publicKey, sign));
339
+ } catch (err: unknown) {
340
+ const e = err as {
341
+ status?: number;
342
+ response?: { status?: number };
343
+ message?: string;
344
+ };
345
+ const status = e?.status ?? e?.response?.status;
346
+ const msg = String(e?.message ?? "").toLowerCase();
347
+ const notRegistered =
348
+ status === 404 ||
349
+ status === 422 ||
350
+ (status === 401 && /not registered|user not found|no such user/.test(msg));
351
+ if (!notRegistered) throw err;
352
+
353
+ // Not registered — decide based on policy + whether we have a code.
354
+ if (!opts.inviteCode) {
355
+ if (info.invite_only === true) {
356
+ return { status: "needs_invite", publicKey, serverName };
357
+ }
358
+ if (info.registration_allowed === false) {
359
+ return { status: "registration_closed", publicKey, serverName };
360
+ }
361
+ }
362
+
363
+ opts.onRegister?.();
364
+ const username =
365
+ opts.username ??
366
+ (opts.displayName
367
+ ? opts.displayName.replace(/\s+/g, "-").toLowerCase()
368
+ : undefined);
369
+ await client.registerWithKey({
370
+ publicKey,
371
+ username,
372
+ displayName: opts.displayName,
373
+ deviceName: opts.deviceName,
374
+ inviteCode: opts.inviteCode,
375
+ });
376
+ return await connected(await client.loginWithKey(publicKey, sign));
377
+ }
378
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * ServerRegistry — a tiny on-disk registry of Abracadabra servers shared by the
3
+ * Node-side consumers (`@abraca/mcp`, `@abraca/cli`).
4
+ *
5
+ * Historically each daemon read a single `ABRA_URL` and a single key file, so it
6
+ * could only ever talk to one server. The registry lets a user remember several
7
+ * servers by alias, keep a per-server identity (key file), and switch between
8
+ * them — both from the CLI (`server add/use/login`) and from a running MCP agent
9
+ * (`connect_server`/`switch_server`).
10
+ *
11
+ * Format: JSON at `~/.abracadabra/servers.json` (override with `ABRA_SERVERS_FILE`):
12
+ *
13
+ * {
14
+ * "defaultAlias": "coop",
15
+ * "servers": {
16
+ * "coop": { "alias": "coop", "url": "https://coop.cou.sh",
17
+ * "keyFile": "/home/me/.abracadabra/keys/coop.key" }
18
+ * }
19
+ * }
20
+ *
21
+ * Node-only: filesystem access is via dynamic `import("node:…")`, so importing
22
+ * this module from a browser bundle is safe — only *calling* the load/save
23
+ * helpers requires Node.
24
+ */
25
+
26
+ // ── Types ──────────────────────────────────────────────────────────────────
27
+
28
+ /** A single remembered server. */
29
+ export interface ServerProfile {
30
+ /** Short, unique handle used on the CLI / in MCP tools. */
31
+ alias: string;
32
+ /** Base URL, e.g. `https://coop.cou.sh`. */
33
+ url: string;
34
+ /** Path to this server's Ed25519 key file (per-server identity). */
35
+ keyFile: string;
36
+ /** Display name presented to the server (presence / registration). */
37
+ displayName?: string;
38
+ /** Presence color (HSL string). */
39
+ color?: string;
40
+ /** Invite/registration token, when the server is invite-only. */
41
+ inviteCode?: string;
42
+ }
43
+
44
+ /** The whole registry: a map of profiles plus which alias is the default. */
45
+ export interface ServerRegistry {
46
+ /** Alias used when no `--server` / `connect_server` target is given. */
47
+ defaultAlias?: string;
48
+ servers: Record<string, ServerProfile>;
49
+ }
50
+
51
+ // ── Paths ──────────────────────────────────────────────────────────────────
52
+
53
+ /** Resolve the registry path: `ABRA_SERVERS_FILE` env, else `~/.abracadabra/servers.json`. */
54
+ export async function serverRegistryPath(override?: string): Promise<string> {
55
+ const { homedir } = await import("node:os");
56
+ const { join } = await import("node:path");
57
+ return (
58
+ override ??
59
+ process.env.ABRA_SERVERS_FILE ??
60
+ join(homedir(), ".abracadabra", "servers.json")
61
+ );
62
+ }
63
+
64
+ /** Default per-server key-file path: `~/.abracadabra/keys/<alias>.key`. */
65
+ export async function defaultKeyFileFor(alias: string): Promise<string> {
66
+ const { homedir } = await import("node:os");
67
+ const { join } = await import("node:path");
68
+ const safe = alias.replace(/[^a-zA-Z0-9._-]/g, "_");
69
+ return join(homedir(), ".abracadabra", "keys", `${safe}.key`);
70
+ }
71
+
72
+ // ── Load / save ────────────────────────────────────────────────────────────
73
+
74
+ /**
75
+ * Load the registry from disk. A missing file yields an empty registry (never
76
+ * throws on absence). A malformed file throws so the caller can surface it.
77
+ */
78
+ export async function loadServerRegistry(
79
+ path?: string,
80
+ ): Promise<ServerRegistry> {
81
+ const { existsSync } = await import("node:fs");
82
+ const { readFile } = await import("node:fs/promises");
83
+ const file = await serverRegistryPath(path);
84
+
85
+ if (!existsSync(file)) return { servers: {} };
86
+
87
+ const raw = await readFile(file, "utf8");
88
+ if (!raw.trim()) return { servers: {} };
89
+ let parsed: unknown;
90
+ try {
91
+ parsed = JSON.parse(raw);
92
+ } catch (err) {
93
+ throw new Error(
94
+ `Malformed server registry at ${file}: ${(err as Error).message}`,
95
+ );
96
+ }
97
+ const reg = parsed as Partial<ServerRegistry>;
98
+ return {
99
+ defaultAlias: reg.defaultAlias,
100
+ servers: reg.servers ?? {},
101
+ };
102
+ }
103
+
104
+ /** Persist the registry, creating `~/.abracadabra/` with `0o700` if needed. */
105
+ export async function saveServerRegistry(
106
+ reg: ServerRegistry,
107
+ path?: string,
108
+ ): Promise<void> {
109
+ const { existsSync } = await import("node:fs");
110
+ const { writeFile, mkdir } = await import("node:fs/promises");
111
+ const { dirname } = await import("node:path");
112
+ const file = await serverRegistryPath(path);
113
+ const dir = dirname(file);
114
+ if (!existsSync(dir)) await mkdir(dir, { recursive: true, mode: 0o700 });
115
+ await writeFile(file, `${JSON.stringify(reg, null, 2)}\n`, { mode: 0o600 });
116
+ }
117
+
118
+ // ── Resolution ─────────────────────────────────────────────────────────────
119
+
120
+ /**
121
+ * Resolve `aliasOrUrl` against the registry.
122
+ *
123
+ * - A known alias → its stored profile.
124
+ * - A bare URL (starts with `http://` / `https://`) → an ephemeral profile with
125
+ * a derived alias (the URL host) and a default per-host key file. This is NOT
126
+ * persisted; the caller decides whether to `addServer` it.
127
+ * - Anything else → `null` (unknown alias).
128
+ */
129
+ export async function resolveServer(
130
+ reg: ServerRegistry,
131
+ aliasOrUrl: string,
132
+ ): Promise<ServerProfile | null> {
133
+ const direct = reg.servers[aliasOrUrl];
134
+ if (direct) return direct;
135
+
136
+ if (/^https?:\/\//i.test(aliasOrUrl)) {
137
+ let alias = aliasOrUrl;
138
+ try {
139
+ alias = new URL(aliasOrUrl).host || aliasOrUrl;
140
+ } catch {
141
+ /* keep the raw string as the alias */
142
+ }
143
+ return {
144
+ alias,
145
+ url: aliasOrUrl.replace(/\/+$/, ""),
146
+ keyFile: await defaultKeyFileFor(alias),
147
+ };
148
+ }
149
+
150
+ return null;
151
+ }
152
+
153
+ // ── Mutators (return a new registry; caller persists) ────────────────────────
154
+
155
+ /** Add or replace a profile. The first server added becomes the default. */
156
+ export function addServer(
157
+ reg: ServerRegistry,
158
+ profile: ServerProfile,
159
+ ): ServerRegistry {
160
+ const servers = { ...reg.servers, [profile.alias]: profile };
161
+ const defaultAlias =
162
+ reg.defaultAlias && reg.servers[reg.defaultAlias]
163
+ ? reg.defaultAlias
164
+ : profile.alias;
165
+ return { defaultAlias, servers };
166
+ }
167
+
168
+ /** Remove a profile by alias. Clears `defaultAlias` if it pointed at it. */
169
+ export function removeServer(
170
+ reg: ServerRegistry,
171
+ alias: string,
172
+ ): ServerRegistry {
173
+ if (!reg.servers[alias]) return reg;
174
+ const servers = { ...reg.servers };
175
+ delete servers[alias];
176
+ let defaultAlias = reg.defaultAlias;
177
+ if (defaultAlias === alias) {
178
+ defaultAlias = Object.keys(servers)[0];
179
+ }
180
+ return { defaultAlias, servers };
181
+ }
182
+
183
+ /** Mark `alias` as the default. Throws if the alias is unknown. */
184
+ export function setDefault(reg: ServerRegistry, alias: string): ServerRegistry {
185
+ if (!reg.servers[alias]) {
186
+ throw new Error(`Unknown server alias: ${alias}`);
187
+ }
188
+ return { ...reg, defaultAlias: alias };
189
+ }
190
+
191
+ // ── Migration ────────────────────────────────────────────────────────────────
192
+
193
+ /**
194
+ * Seed a `default` profile from a legacy single-key setup when the registry is
195
+ * empty. Existing MCP/CLI users keep `~/.abracadabra/{agent,cli}.key` and an
196
+ * `ABRA_URL`; without this they'd lose their identity the first time the
197
+ * registry takes over. Returns the (possibly unchanged) registry; the caller
198
+ * persists if `migrated` is true.
199
+ *
200
+ * @param url the legacy `ABRA_URL` (no migration without it).
201
+ * @param legacyKeyFile path to the legacy key (e.g. `~/.abracadabra/agent.key`).
202
+ */
203
+ export async function migrateLegacyDefault(
204
+ reg: ServerRegistry,
205
+ url: string | undefined,
206
+ legacyKeyFile: string,
207
+ ): Promise<{ registry: ServerRegistry; migrated: boolean }> {
208
+ if (!url || Object.keys(reg.servers).length > 0) {
209
+ return { registry: reg, migrated: false };
210
+ }
211
+ const { existsSync } = await import("node:fs");
212
+ if (!existsSync(legacyKeyFile)) return { registry: reg, migrated: false };
213
+
214
+ const profile: ServerProfile = {
215
+ alias: "default",
216
+ url: url.replace(/\/+$/, ""),
217
+ keyFile: legacyKeyFile,
218
+ };
219
+ return { registry: addServer(reg, profile), migrated: true };
220
+ }
package/src/index.ts CHANGED
@@ -24,14 +24,29 @@ export {
24
24
  deterministicKeypair,
25
25
  loadOrCreateKeyFile,
26
26
  loginOrRegisterWithKey,
27
+ loginOrRegisterWithPolicy,
27
28
  } from "./NodeIdentity.ts";
28
29
  export type {
29
30
  NodeKeypair,
30
31
  LoadKeyFileOptions,
31
32
  LoginOrRegisterOptions,
32
33
  KeyAuthClient,
34
+ PolicyAuthClient,
35
+ ConnectPolicyResult,
33
36
  } from "./NodeIdentity.ts";
34
37
  export { openSyncedProvider, pickEntrySpace } from "./NodeConnect.ts";
38
+ export {
39
+ serverRegistryPath,
40
+ defaultKeyFileFor,
41
+ loadServerRegistry,
42
+ saveServerRegistry,
43
+ resolveServer,
44
+ addServer,
45
+ removeServer,
46
+ setDefault,
47
+ migrateLegacyDefault,
48
+ } from "./ServerRegistry.ts";
49
+ export type { ServerProfile, ServerRegistry } from "./ServerRegistry.ts";
35
50
  export { DocumentCache } from "./DocumentCache.ts";
36
51
  export type { DocumentCacheOptions } from "./DocumentCache.ts";
37
52
  export { SearchIndex } from "./SearchIndex.ts";